hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
7f90b046b0f75213adc2a3ab29e839675a6f0d92
5,490
h
C
base/referencecountedsingletonfactory.h
MIPS/external-chromium_org-third_party-libjingle-source-talk
06a093c73d10bd918baa95312974108bf37b54b4
[ "BSL-1.0", "BSD-3-Clause" ]
284
2015-01-05T08:31:00.000Z
2022-03-25T06:12:55.000Z
base/referencecountedsingletonfactory.h
MIPS/external-chromium_org-third_party-libjingle-source-talk
06a093c73d10bd918baa95312974108bf37b54b4
[ "BSL-1.0", "BSD-3-Clause" ]
1
2019-11-12T20:07:52.000Z
2019-11-12T20:07:52.000Z
base/referencecountedsingletonfactory.h
MIPS/external-chromium_org-third_party-libjingle-source-talk
06a093c73d10bd918baa95312974108bf37b54b4
[ "BSL-1.0", "BSD-3-Clause" ]
171
2015-01-06T06:56:02.000Z
2022-01-24T03:56:37.000Z
/* * libjingle * Copyright 2004--2010, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TALK_BASE_REFERENCECOUNTEDSINGLETONFACTORY_H_ #define TALK_BASE_REFERENCECOUNTEDSINGLETONFACTORY_H_ #include "talk/base/common.h" #include "talk/base/criticalsection.h" #include "talk/base/logging.h" #include "talk/base/scoped_ptr.h" namespace talk_base { template <typename Interface> class rcsf_ptr; // A ReferenceCountedSingletonFactory is an object which owns another object, // and doles out the owned object to consumers in a reference-counted manner. // Thus, the factory owns at most one object of the desired kind, and // hands consumers a special pointer to it, through which they can access it. // When the consumers delete the pointer, the reference count goes down, // and if the reference count hits zero, the factory can throw the object // away. If a consumer requests the pointer and the factory has none, // it can create one on the fly and pass it back. template <typename Interface> class ReferenceCountedSingletonFactory { friend class rcsf_ptr<Interface>; public: ReferenceCountedSingletonFactory() : ref_count_(0) {} virtual ~ReferenceCountedSingletonFactory() { ASSERT(ref_count_ == 0); } protected: // Must be implemented in a sub-class. The sub-class may choose whether or not // to cache the instance across lifetimes by either reset()'ing or not // reset()'ing the scoped_ptr in CleanupInstance(). virtual bool SetupInstance() = 0; virtual void CleanupInstance() = 0; scoped_ptr<Interface> instance_; private: Interface* GetInstance() { talk_base::CritScope cs(&crit_); if (ref_count_ == 0) { if (!SetupInstance()) { LOG(LS_VERBOSE) << "Failed to setup instance"; return NULL; } ASSERT(instance_.get() != NULL); } ++ref_count_; LOG(LS_VERBOSE) << "Number of references: " << ref_count_; return instance_.get(); } void ReleaseInstance() { talk_base::CritScope cs(&crit_); ASSERT(ref_count_ > 0); ASSERT(instance_.get() != NULL); --ref_count_; LOG(LS_VERBOSE) << "Number of references: " << ref_count_; if (ref_count_ == 0) { CleanupInstance(); } } CriticalSection crit_; int ref_count_; DISALLOW_COPY_AND_ASSIGN(ReferenceCountedSingletonFactory); }; template <typename Interface> class rcsf_ptr { public: // Create a pointer that uses the factory to get the instance. // This is lazy - it won't generate the instance until it is requested. explicit rcsf_ptr(ReferenceCountedSingletonFactory<Interface>* factory) : instance_(NULL), factory_(factory) { } ~rcsf_ptr() { release(); } Interface& operator*() { EnsureAcquired(); return *instance_; } Interface* operator->() { EnsureAcquired(); return instance_; } // Gets the pointer, creating the singleton if necessary. May return NULL if // creation failed. Interface* get() { Acquire(); return instance_; } // Set instance to NULL and tell the factory we aren't using the instance // anymore. void release() { if (instance_) { instance_ = NULL; factory_->ReleaseInstance(); } } // Lets us know whether instance is valid or not right now. // Even though attempts to use the instance will automatically create it, it // is advisable to check this because creation can fail. bool valid() const { return instance_ != NULL; } // Returns the factory that this pointer is using. ReferenceCountedSingletonFactory<Interface>* factory() const { return factory_; } private: void EnsureAcquired() { Acquire(); ASSERT(instance_ != NULL); } void Acquire() { // Since we're getting a singleton back, acquire is a noop if instance is // already populated. if (!instance_) { instance_ = factory_->GetInstance(); } } Interface* instance_; ReferenceCountedSingletonFactory<Interface>* factory_; DISALLOW_IMPLICIT_CONSTRUCTORS(rcsf_ptr); }; }; // namespace talk_base #endif // TALK_BASE_REFERENCECOUNTEDSINGLETONFACTORY_H_
31.371429
80
0.715301
[ "object" ]
7f94abedac27b82a18cece0a47ec02e5960221b5
3,831
h
C
include/def5.8/defiUser.h
rsyn/rsyn.design
99dc1241ef523c416be2617c7c7bdd3eec15413f
[ "Apache-2.0" ]
58
2018-08-28T18:39:15.000Z
2021-12-21T09:06:15.000Z
rsyn/include/def5.8/defiUser.h
zrpstc/rsyn-x
3855afbf6d25347f7d91f86aba8d1b1664373563
[ "Apache-2.0" ]
15
2018-08-31T11:44:37.000Z
2021-12-30T07:21:38.000Z
rsyn/include/def5.8/defiUser.h
zrpstc/rsyn-x
3855afbf6d25347f7d91f86aba8d1b1664373563
[ "Apache-2.0" ]
37
2018-09-14T07:59:03.000Z
2022-03-28T06:30:22.000Z
/* ************************************************************************** */ /* ************************************************************************** */ /* ATTENTION: THIS IS AN AUTO-GENERATED FILE. DO NOT CHANGE IT! */ /* ************************************************************************** */ /* ************************************************************************** */ /* Copyright 2013, Cadence Design Systems */ /* */ /* This file is part of the Cadence LEF/DEF Open Source */ /* Distribution, Product Version 5.8. */ /* */ /* 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. */ /* */ /* For updates, support, or to become part of the LEF/DEF Community, */ /* check www.openeda.org for details. */ /* */ /* $Author: dell $ */ /* $Revision: #2 $ */ /* $Date: 2014/06/05 $ */ /* $State: $ */ /* ************************************************************************** */ /* ************************************************************************** */ /* * User header file for the DEF Interface. This includes * all of the header files which are relevant to both the * reader and the writer. * * defrReader.h and defwWriter.h include this file, so that * an application only needs to include either defwReader.h * or defwWriter.h. */ #ifndef CDEFIUSER_H #define CDEFIUSER_H #include "defiAssertion.h" #include "defiBlockage.h" #include "defiComponent.h" #include "defiDebug.h" #include "defiFill.h" #include "defiFPC.h" #include "defiGroup.h" #include "defiIOTiming.h" #include "defiMisc.h" #include "defiNet.h" #include "defiNonDefault.h" #include "defiPartition.h" #include "defiPath.h" #include "defiPinCap.h" #include "defiPinProp.h" #include "defiProp.h" #include "defiPropType.h" #include "defiRegion.h" #include "defiRowTrack.h" #include "defiScanchain.h" #include "defiSite.h" #include "defiSlot.h" #include "defiTimingDisable.h" #include "defiVia.h" /* General utilities. */ /* #include "defiMalloc.hpp" */ /* #include "defiUtils.hpp" */ /* * API objects */ /* NEW CALLBACK - If you are creating a new .cpp and .hpp file to * describe a new class of object in the parser, then add a reference * to the .hpp here. * * You must also add an entry for the .h and the .hpp in the package_list * file of the ../../../release directory. */ #endif
43.044944
80
0.425215
[ "object" ]
7f9b676a9f9c8e42fc6252af95aeee60fe11cde9
861
h
C
bootstrap/include/panda$util$JSONParser$closure199.h
ethannicholas/panda-old
75576bcf5c4e5a34e964547d623a5de874e6e47c
[ "MIT" ]
null
null
null
bootstrap/include/panda$util$JSONParser$closure199.h
ethannicholas/panda-old
75576bcf5c4e5a34e964547d623a5de874e6e47c
[ "MIT" ]
null
null
null
bootstrap/include/panda$util$JSONParser$closure199.h
ethannicholas/panda-old
75576bcf5c4e5a34e964547d623a5de874e6e47c
[ "MIT" ]
null
null
null
// This file was automatically generated by the Panda compiler #ifndef panda$util$JSONParser$closure199_H #define panda$util$JSONParser$closure199_H extern panda$core$Class panda$util$JSONParser$closure199_class; #ifndef CLASS_panda$util$JSONParser$closure199 #define CLASS_panda$util$JSONParser$closure199 struct panda$util$JSONParser$closure199 { panda$core$Class* cl; }; #define panda$util$JSONParser$closure199$closure_panda$parser$GLRParser$State_$Rpanda$core$Object$Z_INDEX 4 typedef panda$core$Object*(panda$util$JSONParser$closure199$closure_panda$parser$GLRParser$State_$Rpanda$core$Object$Z_TYPE)(panda$util$JSONParser$closure199* self, panda$parser$GLRParser$State*); void panda$util$JSONParser$closure199$init(panda$util$JSONParser$closure199* self); panda$util$JSONParser$closure199* new_panda$util$JSONParser$closure199$init(); #endif #endif
50.647059
196
0.832753
[ "object" ]
7fa0cca79f7a2e273d966e56f4ea4dd257ca5e21
1,422
h
C
include/pacbio/pancake/OverlapWriterPAF.h
ahehn-nv/pancake
273a035d3b858256d0847f773f6fa4560c2d37f8
[ "BSD-3-Clause-Clear", "BSL-1.0", "BSD-3-Clause", "MIT" ]
8
2020-11-18T20:39:36.000Z
2022-03-02T19:14:14.000Z
include/pacbio/pancake/OverlapWriterPAF.h
ahehn-nv/pancake
273a035d3b858256d0847f773f6fa4560c2d37f8
[ "BSD-3-Clause-Clear", "BSL-1.0", "BSD-3-Clause", "MIT" ]
4
2020-12-01T15:47:46.000Z
2021-09-02T14:53:23.000Z
include/pacbio/pancake/OverlapWriterPAF.h
ahehn-nv/pancake
273a035d3b858256d0847f773f6fa4560c2d37f8
[ "BSD-3-Clause-Clear", "BSL-1.0", "BSD-3-Clause", "MIT" ]
5
2020-11-19T18:24:05.000Z
2021-03-18T16:08:23.000Z
// Author: Ivan Sovic #ifndef PANCAKE_OVERLAPHIFI_OVERLAP_WRITER_PAF_H #define PANCAKE_OVERLAPHIFI_OVERLAP_WRITER_PAF_H #include <pacbio/pancake/FastaSequenceId.h> #include <pacbio/pancake/Overlap.h> #include <pacbio/pancake/OverlapWriterBase.h> #include <pacbio/pancake/SeqDBReaderCached.h> #include <pacbio/pancake/SeqDBReaderCachedBlock.h> #include <pacbio/util/Util.h> #include <cstdint> #include <memory> #include <unordered_map> #include <vector> namespace PacBio { namespace Pancake { class OverlapWriterPAF : public OverlapWriterBase { public: OverlapWriterPAF(FILE* fpOut, bool writeIds, bool writeCigar); ~OverlapWriterPAF(); void WriteHeader(const PacBio::Pancake::SeqDBReaderCached& targetSeqs) override; void WriteHeader(const PacBio::Pancake::SeqDBReaderCachedBlock& targetSeqs) override; void Write(const Overlap& ovl, const PacBio::Pancake::SeqDBReaderCached& targetSeqs, const PacBio::Pancake::FastaSequenceId& querySeq) override; void Write(const Overlap& ovl, const PacBio::Pancake::SeqDBReaderCachedBlock& targetSeqs, const PacBio::Pancake::FastaSequenceCached& querySeq) override; private: std::string outFile_; FILE* fpOut_ = NULL; bool shouldClose_ = false; bool writeIds_ = false; bool writeCigar_ = false; }; } // namespace Pancake } // namespace PacBio #endif // PANCAKE_OVERLAPHIFI_OVERLAP_WRITER_IPA_OVL_H
29.625
93
0.761603
[ "vector" ]
7fa1b963ef3e7c703fec8861fdc5f8a950a24307
150,768
c
C
ext/phar/phar_object.c
tzmfreedom/php-src
a06c20a17c97a76956f3454291ba0a46ee39eda1
[ "PHP-3.01" ]
null
null
null
ext/phar/phar_object.c
tzmfreedom/php-src
a06c20a17c97a76956f3454291ba0a46ee39eda1
[ "PHP-3.01" ]
null
null
null
ext/phar/phar_object.c
tzmfreedom/php-src
a06c20a17c97a76956f3454291ba0a46ee39eda1
[ "PHP-3.01" ]
null
null
null
/* +----------------------------------------------------------------------+ | phar php single-file executable PHP extension | +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Gregory Beaver <cellog@php.net> | | Marcus Boerger <helly@php.net> | +----------------------------------------------------------------------+ */ #include "phar_internal.h" #include "func_interceptors.h" #include "phar_object_arginfo.h" static zend_class_entry *phar_ce_archive; static zend_class_entry *phar_ce_data; static zend_class_entry *phar_ce_PharException; static zend_class_entry *phar_ce_entry; static int phar_file_type(HashTable *mimes, char *file, char **mime_type) /* {{{ */ { char *ext; phar_mime_type *mime; ext = strrchr(file, '.'); if (!ext) { *mime_type = "text/plain"; /* no file extension = assume text/plain */ return PHAR_MIME_OTHER; } ++ext; if (NULL == (mime = zend_hash_str_find_ptr(mimes, ext, strlen(ext)))) { *mime_type = "application/octet-stream"; return PHAR_MIME_OTHER; } *mime_type = mime->mime; return mime->type; } /* }}} */ static void phar_mung_server_vars(char *fname, char *entry, size_t entry_len, char *basename, size_t request_uri_len) /* {{{ */ { HashTable *_SERVER; zval *stuff; char *path_info; size_t basename_len = strlen(basename); size_t code; zval temp; /* "tweak" $_SERVER variables requested in earlier call to Phar::mungServer() */ if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_UNDEF) { return; } _SERVER = Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]); /* PATH_INFO and PATH_TRANSLATED should always be munged */ if (NULL != (stuff = zend_hash_str_find(_SERVER, "PATH_INFO", sizeof("PATH_INFO")-1))) { path_info = Z_STRVAL_P(stuff); code = Z_STRLEN_P(stuff); if (code > (size_t)entry_len && !memcmp(path_info, entry, entry_len)) { ZVAL_STR(&temp, Z_STR_P(stuff)); ZVAL_STRINGL(stuff, path_info + entry_len, request_uri_len); zend_hash_str_update(_SERVER, "PHAR_PATH_INFO", sizeof("PHAR_PATH_INFO")-1, &temp); } } if (NULL != (stuff = zend_hash_str_find(_SERVER, "PATH_TRANSLATED", sizeof("PATH_TRANSLATED")-1))) { zend_string *str = strpprintf(4096, "phar://%s%s", fname, entry); ZVAL_STR(&temp, Z_STR_P(stuff)); ZVAL_NEW_STR(stuff, str); zend_hash_str_update(_SERVER, "PHAR_PATH_TRANSLATED", sizeof("PHAR_PATH_TRANSLATED")-1, &temp); } if (!PHAR_G(phar_SERVER_mung_list)) { return; } if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_REQUEST_URI) { if (NULL != (stuff = zend_hash_str_find(_SERVER, "REQUEST_URI", sizeof("REQUEST_URI")-1))) { path_info = Z_STRVAL_P(stuff); code = Z_STRLEN_P(stuff); if (code > basename_len && !memcmp(path_info, basename, basename_len)) { ZVAL_STR(&temp, Z_STR_P(stuff)); ZVAL_STRINGL(stuff, path_info + basename_len, code - basename_len); zend_hash_str_update(_SERVER, "PHAR_REQUEST_URI", sizeof("PHAR_REQUEST_URI")-1, &temp); } } } if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_PHP_SELF) { if (NULL != (stuff = zend_hash_str_find(_SERVER, "PHP_SELF", sizeof("PHP_SELF")-1))) { path_info = Z_STRVAL_P(stuff); code = Z_STRLEN_P(stuff); if (code > basename_len && !memcmp(path_info, basename, basename_len)) { ZVAL_STR(&temp, Z_STR_P(stuff)); ZVAL_STRINGL(stuff, path_info + basename_len, code - basename_len); zend_hash_str_update(_SERVER, "PHAR_PHP_SELF", sizeof("PHAR_PHP_SELF")-1, &temp); } } } if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_SCRIPT_NAME) { if (NULL != (stuff = zend_hash_str_find(_SERVER, "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1))) { ZVAL_STR(&temp, Z_STR_P(stuff)); ZVAL_STRINGL(stuff, entry, entry_len); zend_hash_str_update(_SERVER, "PHAR_SCRIPT_NAME", sizeof("PHAR_SCRIPT_NAME")-1, &temp); } } if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_SCRIPT_FILENAME) { if (NULL != (stuff = zend_hash_str_find(_SERVER, "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1))) { zend_string *str = strpprintf(4096, "phar://%s%s", fname, entry); ZVAL_STR(&temp, Z_STR_P(stuff)); ZVAL_NEW_STR(stuff, str); zend_hash_str_update(_SERVER, "PHAR_SCRIPT_FILENAME", sizeof("PHAR_SCRIPT_FILENAME")-1, &temp); } } } /* }}} */ static int phar_file_action(phar_archive_data *phar, phar_entry_info *info, char *mime_type, int code, char *entry, size_t entry_len, char *arch, char *basename, char *ru, size_t ru_len) /* {{{ */ { char *name = NULL, buf[8192]; const char *cwd; zend_syntax_highlighter_ini syntax_highlighter_ini; sapi_header_line ctr = {0}; size_t got; zval dummy; size_t name_len; zend_file_handle file_handle; zend_op_array *new_op_array; zval result; php_stream *fp; zend_off_t position; switch (code) { case PHAR_MIME_PHPS: efree(basename); /* highlight source */ if (entry[0] == '/') { spprintf(&name, 4096, "phar://%s%s", arch, entry); } else { spprintf(&name, 4096, "phar://%s/%s", arch, entry); } php_get_highlight_struct(&syntax_highlighter_ini); highlight_file(name, &syntax_highlighter_ini); efree(name); #ifdef PHP_WIN32 efree(arch); #endif zend_bailout(); case PHAR_MIME_OTHER: /* send headers, output file contents */ efree(basename); ctr.line_len = spprintf((char **) &(ctr.line), 0, "Content-type: %s", mime_type); sapi_header_op(SAPI_HEADER_REPLACE, &ctr); efree((void *) ctr.line); ctr.line_len = spprintf((char **) &(ctr.line), 0, "Content-length: %u", info->uncompressed_filesize); sapi_header_op(SAPI_HEADER_REPLACE, &ctr); efree((void *) ctr.line); if (FAILURE == sapi_send_headers()) { zend_bailout(); } /* prepare to output */ fp = phar_get_efp(info, 1); if (!fp) { char *error; if (!phar_open_jit(phar, info, &error)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } return -1; } fp = phar_get_efp(info, 1); } position = 0; phar_seek_efp(info, 0, SEEK_SET, 0, 1); do { got = php_stream_read(fp, buf, MIN(8192, info->uncompressed_filesize - position)); if (got > 0) { PHPWRITE(buf, got); position += got; if (position == (zend_off_t) info->uncompressed_filesize) { break; } } } while (1); zend_bailout(); case PHAR_MIME_PHP: if (basename) { phar_mung_server_vars(arch, entry, entry_len, basename, ru_len); efree(basename); } if (entry[0] == '/') { name_len = spprintf(&name, 4096, "phar://%s%s", arch, entry); } else { name_len = spprintf(&name, 4096, "phar://%s/%s", arch, entry); } zend_stream_init_filename(&file_handle, name); PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; ZVAL_NULL(&dummy); if (zend_hash_str_add(&EG(included_files), name, name_len, &dummy) != NULL) { if ((cwd = zend_memrchr(entry, '/', entry_len))) { PHAR_G(cwd_init) = 1; if (entry == cwd) { /* root directory */ PHAR_G(cwd_len) = 0; PHAR_G(cwd) = NULL; } else if (entry[0] == '/') { PHAR_G(cwd_len) = (cwd - (entry + 1)); PHAR_G(cwd) = estrndup(entry + 1, PHAR_G(cwd_len)); } else { PHAR_G(cwd_len) = (cwd - entry); PHAR_G(cwd) = estrndup(entry, PHAR_G(cwd_len)); } } new_op_array = zend_compile_file(&file_handle, ZEND_REQUIRE); if (!new_op_array) { zend_hash_str_del(&EG(included_files), name, name_len); } zend_destroy_file_handle(&file_handle); } else { efree(name); new_op_array = NULL; } #ifdef PHP_WIN32 efree(arch); #endif if (new_op_array) { ZVAL_UNDEF(&result); zend_try { zend_execute(new_op_array, &result); if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; } PHAR_G(cwd_init) = 0; efree(name); destroy_op_array(new_op_array); efree(new_op_array); zval_ptr_dtor(&result); } zend_catch { if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; } PHAR_G(cwd_init) = 0; efree(name); } zend_end_try(); zend_bailout(); } return PHAR_MIME_PHP; } return -1; } /* }}} */ static void phar_do_403(char *entry, size_t entry_len) /* {{{ */ { sapi_header_line ctr = {0}; ctr.response_code = 403; ctr.line_len = sizeof("HTTP/1.0 403 Access Denied")-1; ctr.line = "HTTP/1.0 403 Access Denied"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr); sapi_send_headers(); PHPWRITE("<html>\n <head>\n <title>Access Denied</title>\n </head>\n <body>\n <h1>403 - File ", sizeof("<html>\n <head>\n <title>Access Denied</title>\n </head>\n <body>\n <h1>403 - File ") - 1); PHPWRITE("Access Denied</h1>\n </body>\n</html>", sizeof("Access Denied</h1>\n </body>\n</html>") - 1); } /* }}} */ static void phar_do_404(phar_archive_data *phar, char *fname, size_t fname_len, char *f404, size_t f404_len, char *entry, size_t entry_len) /* {{{ */ { sapi_header_line ctr = {0}; phar_entry_info *info; if (phar && f404_len) { info = phar_get_entry_info(phar, f404, f404_len, NULL, 1); if (info) { phar_file_action(phar, info, "text/html", PHAR_MIME_PHP, f404, f404_len, fname, NULL, NULL, 0); return; } } ctr.response_code = 404; ctr.line_len = sizeof("HTTP/1.0 404 Not Found")-1; ctr.line = "HTTP/1.0 404 Not Found"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr); sapi_send_headers(); PHPWRITE("<html>\n <head>\n <title>File Not Found</title>\n </head>\n <body>\n <h1>404 - File ", sizeof("<html>\n <head>\n <title>File Not Found</title>\n </head>\n <body>\n <h1>404 - File ") - 1); PHPWRITE("Not Found</h1>\n </body>\n</html>", sizeof("Not Found</h1>\n </body>\n</html>") - 1); } /* }}} */ /* post-process REQUEST_URI and retrieve the actual request URI. This is for cases like http://localhost/blah.phar/path/to/file.php/extra/stuff which calls "blah.phar" file "path/to/file.php" with PATH_INFO "/extra/stuff" */ static void phar_postprocess_ru_web(char *fname, size_t fname_len, char **entry, size_t *entry_len, char **ru, size_t *ru_len) /* {{{ */ { char *e = *entry + 1, *u = NULL, *u1 = NULL, *saveu = NULL; size_t e_len = *entry_len - 1, u_len = 0; phar_archive_data *pphar; /* we already know we can retrieve the phar if we reach here */ pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len); if (!pphar && PHAR_G(manifest_cached)) { pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len); } do { if (zend_hash_str_exists(&(pphar->manifest), e, e_len)) { if (u) { u[0] = '/'; *ru = estrndup(u, u_len+1); ++u_len; u[0] = '\0'; } else { *ru = NULL; } *ru_len = u_len; *entry_len = e_len + 1; return; } if (u) { u1 = strrchr(e, '/'); u[0] = '/'; saveu = u; e_len += u_len + 1; u = u1; if (!u) { return; } } else { u = strrchr(e, '/'); if (!u) { if (saveu) { saveu[0] = '/'; } return; } } u[0] = '\0'; u_len = strlen(u + 1); e_len -= u_len + 1; } while (1); } /* }}} */ /* {{{ return the name of the currently running phar archive. If the optional parameter * is set to true, return the phar:// URL to the currently running phar */ PHP_METHOD(Phar, running) { char *fname, *arch, *entry; size_t fname_len, arch_len, entry_len; bool retphar = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &retphar) == FAILURE) { RETURN_THROWS(); } fname = (char*)zend_get_executed_filename(); fname_len = strlen(fname); if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { efree(entry); if (retphar) { RETVAL_STRINGL(fname, arch_len + 7); efree(arch); return; } else { // TODO: avoid reallocation ??? RETVAL_STRINGL(arch, arch_len); efree(arch); return; } } RETURN_EMPTY_STRING(); } /* }}} */ /* {{{ mount an external file or path to a location within the phar. This maps * an external file or directory to a location within the phar archive, allowing * reference to an external location as if it were within the phar archive. This * is useful for writable temp files like databases */ PHP_METHOD(Phar, mount) { char *fname, *arch = NULL, *entry = NULL, *path, *actual; size_t fname_len, arch_len, entry_len; size_t path_len, actual_len; phar_archive_data *pphar; #ifdef PHP_WIN32 char *save_fname; ALLOCA_FLAG(fname_use_heap) #endif if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &path, &path_len, &actual, &actual_len) == FAILURE) { RETURN_THROWS(); } fname = (char*)zend_get_executed_filename(); fname_len = strlen(fname); #ifdef PHP_WIN32 save_fname = fname; if (memchr(fname, '\\', fname_len)) { fname = do_alloca(fname_len + 1, fname_use_heap); memcpy(fname, save_fname, fname_len); fname[fname_len] = '\0'; phar_unixify_path_separators(fname, fname_len); } #endif if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { efree(entry); entry = NULL; if (path_len > 7 && !memcmp(path, "phar://", 7)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path); efree(arch); goto finish; } carry_on2: if (NULL == (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len))) { if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len))) { if (SUCCESS == phar_copy_on_write(&pphar)) { goto carry_on; } } zend_throw_exception_ex(phar_ce_PharException, 0, "%s is not a phar archive, cannot mount", arch); if (arch) { efree(arch); } goto finish; } carry_on: if (SUCCESS != phar_mount_entry(pphar, actual, actual_len, path, path_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s within phar %s failed", path, actual, arch); if (path && path == entry) { efree(entry); } if (arch) { efree(arch); } goto finish; } if (entry && path && path == entry) { efree(entry); } if (arch) { efree(arch); } goto finish; } else if (HT_IS_INITIALIZED(&PHAR_G(phar_fname_map)) && NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) { goto carry_on; } else if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) { if (SUCCESS == phar_copy_on_write(&pphar)) { goto carry_on; } goto carry_on; } else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { path = entry; path_len = entry_len; goto carry_on2; } zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s failed", path, actual); finish: ; #ifdef PHP_WIN32 if (fname != save_fname) { free_alloca(fname, fname_use_heap); fname = save_fname; } #endif } /* }}} */ /* {{{ mapPhar for web-based phars. Reads the currently executed file (a phar) * and registers its manifest. When executed in the CLI or CGI command-line sapi, * this works exactly like mapPhar(). When executed by a web-based sapi, this * reads $_SERVER['REQUEST_URI'] (the actual original value) and parses out the * intended internal file. */ PHP_METHOD(Phar, webPhar) { zval *mimeoverride = NULL; zend_fcall_info rewrite_fci = {0}; zend_fcall_info_cache rewrite_fcc; char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL; size_t alias_len = 0, f404_len = 0, free_pathinfo = 0; size_t ru_len = 0; char *fname, *path_info, *mime_type = NULL, *entry, *pt; const char *basename; size_t fname_len, index_php_len = 0; size_t entry_len; int code, not_cgi; phar_archive_data *phar = NULL; phar_entry_info *info = NULL; size_t sapi_mod_name_len = strlen(sapi_module.name); if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!s!saf!", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite_fci, &rewrite_fcc) == FAILURE) { RETURN_THROWS(); } phar_request_initialize(); fname = (char*)zend_get_executed_filename(); fname_len = strlen(fname); if (phar_open_executed_filename(alias, alias_len, &error) != SUCCESS) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } return; } /* retrieve requested file within phar */ if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST") || !strcmp(SG(request_info).request_method, "DELETE") || !strcmp(SG(request_info).request_method, "HEAD") || !strcmp(SG(request_info).request_method, "OPTIONS") || !strcmp(SG(request_info).request_method, "PATCH") || !strcmp(SG(request_info).request_method, "PUT") ) ) ) { return; } #ifdef PHP_WIN32 if (memchr(fname, '\\', fname_len)) { fname = estrndup(fname, fname_len); phar_unixify_path_separators(fname, fname_len); } #endif basename = zend_memrchr(fname, '/', fname_len); if (!basename) { basename = fname; } else { ++basename; } if ((sapi_mod_name_len == sizeof("cgi-fcgi") - 1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi") - 1)) || (sapi_mod_name_len == sizeof("fpm-fcgi") - 1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi") - 1)) || (sapi_mod_name_len == sizeof("cgi") - 1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi") - 1))) { if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) != IS_UNDEF) { HashTable *_server = Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]); zval *z_script_name, *z_path_info; if (NULL == (z_script_name = zend_hash_str_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) || IS_STRING != Z_TYPE_P(z_script_name) || !strstr(Z_STRVAL_P(z_script_name), basename)) { goto finish; } if (NULL != (z_path_info = zend_hash_str_find(_server, "PATH_INFO", sizeof("PATH_INFO")-1)) && IS_STRING == Z_TYPE_P(z_path_info)) { entry_len = Z_STRLEN_P(z_path_info); entry = estrndup(Z_STRVAL_P(z_path_info), entry_len); path_info = emalloc(Z_STRLEN_P(z_script_name) + entry_len + 1); memcpy(path_info, Z_STRVAL_P(z_script_name), Z_STRLEN_P(z_script_name)); memcpy(path_info + Z_STRLEN_P(z_script_name), entry, entry_len + 1); free_pathinfo = 1; } else { entry_len = 0; entry = estrndup("", 0); path_info = Z_STRVAL_P(z_script_name); } pt = estrndup(Z_STRVAL_P(z_script_name), Z_STRLEN_P(z_script_name)); } else { char *testit; testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1); if (!(pt = strstr(testit, basename))) { efree(testit); goto finish; } path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1); if (path_info) { entry = path_info; entry_len = strlen(entry); spprintf(&path_info, 0, "%s%s", testit, path_info); free_pathinfo = 1; } else { path_info = testit; free_pathinfo = 1; entry = estrndup("", 0); entry_len = 0; } pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname))); } not_cgi = 0; } else { path_info = SG(request_info).request_uri; if (!(pt = strstr(path_info, basename))) { /* this can happen with rewrite rules - and we have no idea what to do then, so return */ goto finish; } entry_len = strlen(path_info); entry_len -= (pt - path_info) + (fname_len - (basename - fname)); entry = estrndup(pt + (fname_len - (basename - fname)), entry_len); pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname))); not_cgi = 1; } if (ZEND_FCI_INITIALIZED(rewrite_fci)) { zval params, retval; ZVAL_STRINGL(&params, entry, entry_len); rewrite_fci.param_count = 1; rewrite_fci.params = &params; rewrite_fci.retval = &retval; if (FAILURE == zend_call_function(&rewrite_fci, &rewrite_fcc)) { if (!EG(exception)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: failed to call rewrite callback"); } goto cleanup_fail; } if (Z_TYPE_P(rewrite_fci.retval) == IS_UNDEF || Z_TYPE(retval) == IS_UNDEF) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: rewrite callback must return a string or false"); goto cleanup_fail; } switch (Z_TYPE(retval)) { case IS_STRING: efree(entry); entry = estrndup(Z_STRVAL_P(rewrite_fci.retval), Z_STRLEN_P(rewrite_fci.retval)); entry_len = Z_STRLEN_P(rewrite_fci.retval); break; case IS_TRUE: case IS_FALSE: phar_do_403(entry, entry_len); if (free_pathinfo) { efree(path_info); } efree(pt); zend_bailout(); default: zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: rewrite callback must return a string or false"); cleanup_fail: zval_ptr_dtor(&params); if (free_pathinfo) { efree(path_info); } efree(entry); efree(pt); #ifdef PHP_WIN32 efree(fname); #endif RETURN_THROWS(); } } if (entry_len) { phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len); } if (!entry_len || (entry_len == 1 && entry[0] == '/')) { efree(entry); /* direct request */ if (index_php_len) { entry = index_php; entry_len = index_php_len; if (entry[0] != '/') { spprintf(&entry, 0, "/%s", index_php); ++entry_len; } } else { /* assume "index.php" is starting point */ entry = estrndup("/index.php", sizeof("/index.php")); entry_len = sizeof("/index.php")-1; } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len); if (free_pathinfo) { efree(path_info); } zend_bailout(); } else { char *tmp = NULL, sa = '\0'; sapi_header_line ctr = {0}; ctr.response_code = 301; ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1; ctr.line = "HTTP/1.1 301 Moved Permanently"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr); if (not_cgi) { tmp = strstr(path_info, basename) + fname_len; sa = *tmp; *tmp = '\0'; } ctr.response_code = 0; if (path_info[strlen(path_info)-1] == '/') { ctr.line_len = spprintf((char **) &(ctr.line), 4096, "Location: %s%s", path_info, entry + 1); } else { ctr.line_len = spprintf((char **) &(ctr.line), 4096, "Location: %s%s", path_info, entry); } if (not_cgi) { *tmp = sa; } if (free_pathinfo) { efree(path_info); } sapi_header_op(SAPI_HEADER_REPLACE, &ctr); sapi_send_headers(); efree((void *) ctr.line); zend_bailout(); } } if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL) || (info = phar_get_entry_info(phar, entry, entry_len, NULL, 0)) == NULL) { phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len); zend_bailout(); } if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) { const char *ext = zend_memrchr(entry, '.', entry_len); zval *val; if (ext) { ++ext; if (NULL != (val = zend_hash_str_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)))) { switch (Z_TYPE_P(val)) { case IS_LONG: if (Z_LVAL_P(val) == PHAR_MIME_PHP || Z_LVAL_P(val) == PHAR_MIME_PHPS) { mime_type = ""; code = Z_LVAL_P(val); } else { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed"); if (free_pathinfo) { efree(path_info); } efree(pt); efree(entry); #ifdef PHP_WIN32 efree(fname); #endif RETURN_THROWS(); } break; case IS_STRING: mime_type = Z_STRVAL_P(val); code = PHAR_MIME_OTHER; break; default: zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed"); if (free_pathinfo) { efree(path_info); } efree(pt); efree(entry); #ifdef PHP_WIN32 efree(fname); #endif RETURN_THROWS(); } } } } if (!mime_type) { code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type); } phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len); finish: ; #ifdef PHP_WIN32 efree(fname); #endif } /* }}} */ /* {{{ Defines a list of up to 4 $_SERVER variables that should be modified for execution * to mask the presence of the phar archive. This should be used in conjunction with * Phar::webPhar(), and has no effect otherwise * SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME */ PHP_METHOD(Phar, mungServer) { zval *mungvalues, *data; if (zend_parse_parameters(ZEND_NUM_ARGS(), "a", &mungvalues) == FAILURE) { RETURN_THROWS(); } if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) { zend_throw_exception_ex(phar_ce_PharException, 0, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); RETURN_THROWS(); } if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) { zend_throw_exception_ex(phar_ce_PharException, 0, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); RETURN_THROWS(); } phar_request_initialize(); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(mungvalues), data) { if (Z_TYPE_P(data) != IS_STRING) { zend_throw_exception_ex(phar_ce_PharException, 0, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME"); RETURN_THROWS(); } if (Z_STRLEN_P(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_P(data), "PHP_SELF", sizeof("PHP_SELF")-1)) { PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_PHP_SELF; } if (Z_STRLEN_P(data) == sizeof("REQUEST_URI")-1) { if (!strncmp(Z_STRVAL_P(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) { PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_REQUEST_URI; } if (!strncmp(Z_STRVAL_P(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) { PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_SCRIPT_NAME; } } if (Z_STRLEN_P(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_P(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) { PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_SCRIPT_FILENAME; } } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions * and return stat on files within the phar for relative paths * * Once called, this cannot be reversed, and continue until the end of the request. * * This allows legacy scripts to be pharred unmodified */ PHP_METHOD(Phar, interceptFileFuncs) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } phar_intercept_functions(); } /* }}} */ /* {{{ Return a stub that can be used to run a phar-based archive without the phar extension * indexfile is the CLI startup filename, which defaults to "index.php", webindexfile * is the web startup filename, and also defaults to "index.php" */ PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *error; zend_string *stub; size_t index_len = 0, webindex_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|p!p!", &index, &index_len, &webindex, &webindex_len) == FAILURE) { RETURN_THROWS(); } stub = phar_create_default_stub(index, webindex, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } RETURN_NEW_STR(stub); } /* }}} */ /* {{{ Reads the currently executed file (a phar) and registers its manifest */ PHP_METHOD(Phar, mapPhar) { char *alias = NULL, *error; size_t alias_len = 0; zend_long dataoffset = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) { RETURN_THROWS(); } phar_request_initialize(); RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ Loads any phar archive with an alias */ PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { RETURN_THROWS(); } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ Returns the api version */ PHP_METHOD(Phar, apiVersion) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1); } /* }}}*/ /* {{{ Returns whether phar extension supports compression using zlib/bzip2 */ PHP_METHOD(Phar, canCompress) { zend_long method = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &method) == FAILURE) { RETURN_THROWS(); } phar_request_initialize(); switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (PHAR_G(has_zlib)) { RETURN_TRUE; } else { RETURN_FALSE; } case PHAR_ENT_COMPRESSED_BZ2: if (PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } default: if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) { RETURN_TRUE; } else { RETURN_FALSE; } } } /* }}} */ /* {{{ Returns whether phar extension supports writing and creating phars */ PHP_METHOD(Phar, canWrite) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } RETURN_BOOL(!PHAR_G(readonly)); } /* }}} */ /* {{{ Returns whether the given filename is a valid phar filename */ PHP_METHOD(Phar, isValidPharFilename) { char *fname; const char *ext_str; size_t fname_len; size_t ext_len; int is_executable; bool executable = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|b", &fname, &fname_len, &executable) == FAILURE) { RETURN_THROWS(); } is_executable = executable; RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1) == SUCCESS); } /* }}} */ /** * from spl_directory */ static void phar_spl_foreign_dtor(spl_filesystem_object *object) /* {{{ */ { phar_archive_data *phar = (phar_archive_data *) object->oth; if (!phar->is_persistent) { phar_archive_delref(phar); } object->oth = NULL; } /* }}} */ /** * from spl_directory */ static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst) /* {{{ */ { phar_archive_data *phar_data = (phar_archive_data *) dst->oth; if (!phar_data->is_persistent) { ++(phar_data->refcount); } } /* }}} */ static const spl_other_handler phar_spl_foreign_handler = { phar_spl_foreign_dtor, phar_spl_foreign_clone }; /* {{{ Construct a Phar archive object * * proto PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR]) * Construct a PharData archive object * * This function is used as the constructor for both the Phar and PharData * classes, hence the two prototypes above. */ PHP_METHOD(Phar, __construct) { char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; size_t fname_len, alias_len = 0; size_t arch_len, entry_len; bool is_data; zend_long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; zend_long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = ZEND_THIS, arg1, arg2; phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { RETURN_THROWS(); } } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { RETURN_THROWS(); } } if (phar_obj->archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); RETURN_THROWS(); } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar creation or opening failed"); } RETURN_THROWS(); } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar class can only be used for executable tar and zip archives"); } efree(entry); RETURN_THROWS(); } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } ZVAL_STRINGL(&arg1, fname, fname_len); ZVAL_LONG(&arg2, flags); zend_call_known_instance_method_with_2_params(spl_ce_RecursiveDirectoryIterator->constructor, Z_OBJ_P(zobj), NULL, &arg1, &arg2); zval_ptr_dtor(&arg1); if (!phar_data->is_persistent) { phar_obj->archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_str_add_ptr(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive), phar_obj); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); } /* }}} */ /* {{{ Return array of supported signature types */ PHP_METHOD(Phar, getSupportedSignatures) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } array_init(return_value); add_next_index_stringl(return_value, "MD5", 3); add_next_index_stringl(return_value, "SHA-1", 5); add_next_index_stringl(return_value, "SHA-256", 7); add_next_index_stringl(return_value, "SHA-512", 7); #ifdef PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, "OpenSSL", 7); #else if (zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) { add_next_index_stringl(return_value, "OpenSSL", 7); } #endif } /* }}} */ /* {{{ Return array of supported comparession algorithms */ PHP_METHOD(Phar, getSupportedCompression) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } array_init(return_value); phar_request_initialize(); if (PHAR_G(has_zlib)) { add_next_index_stringl(return_value, "GZ", 2); } if (PHAR_G(has_bz2)) { add_next_index_stringl(return_value, "BZIP2", 5); } } /* }}} */ /* {{{ Completely remove a phar archive from memory and disk */ PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; size_t fname_len; size_t zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { RETURN_THROWS(); } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\""); RETURN_THROWS(); } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname); } RETURN_THROWS(); } zname = (char*)zend_get_executed_filename(); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { if ((size_t)arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname); efree(arch); efree(entry); RETURN_THROWS(); } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname); RETURN_THROWS(); } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname); RETURN_THROWS(); } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar); unlink(fname); efree(fname); RETURN_TRUE; } /* }}} */ #define PHAR_ARCHIVE_OBJECT() \ zval *zobj = ZEND_THIS; \ phar_archive_object *phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); \ if (!phar_obj->archive) { \ zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Cannot call method on an uninitialized Phar object"); \ RETURN_THROWS(); \ } /* {{{ if persistent, remove from the cache */ PHP_METHOD(Phar, __destruct) { zval *zobj = ZEND_THIS; phar_archive_object *phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } if (phar_obj->archive && phar_obj->archive->is_persistent) { zend_hash_str_del(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive)); } } /* }}} */ struct _phar_t { phar_archive_object *p; zend_class_entry *c; char *b; zval *ret; php_stream *fp; uint32_t l; int count; }; static int phar_build(zend_object_iterator *iter, void *puser) /* {{{ */ { zval *value; bool close_fp = 1; struct _phar_t *p_obj = (struct _phar_t*) puser; size_t str_key_len, base_len = p_obj->l; phar_entry_data *data; php_stream *fp; size_t fname_len; size_t contents_len; char *fname, *error = NULL, *base = p_obj->b, *save = NULL, *temp = NULL; zend_string *opened; char *str_key; zend_class_entry *ce = p_obj->c; phar_archive_object *phar_obj = p_obj->p; php_stream_statbuf ssb; value = iter->funcs->get_current_data(iter); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (!value) { /* failure in get_current_data */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned no value", ZSTR_VAL(ce->name)); return ZEND_HASH_APPLY_STOP; } switch (Z_TYPE_P(value)) { case IS_STRING: break; case IS_RESOURCE: php_stream_from_zval_no_verify(fp, value); if (!fp) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Iterator %s returned an invalid stream handle", ZSTR_VAL(ce->name)); return ZEND_HASH_APPLY_STOP; } if (iter->funcs->get_current_key) { zval key; iter->funcs->get_current_key(iter, &key); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (Z_TYPE(key) != IS_STRING) { zval_ptr_dtor(&key); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name)); return ZEND_HASH_APPLY_STOP; } str_key_len = Z_STRLEN(key); str_key = estrndup(Z_STRVAL(key), str_key_len); save = str_key; zval_ptr_dtor_str(&key); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name)); return ZEND_HASH_APPLY_STOP; } close_fp = 0; opened = zend_string_init("[stream]", sizeof("[stream]") - 1, 0); goto after_open_fp; case IS_OBJECT: if (instanceof_function(Z_OBJCE_P(value), spl_ce_SplFileInfo)) { char *test = NULL; zval dummy; spl_filesystem_object *intern = (spl_filesystem_object*)((char*)Z_OBJ_P(value) - Z_OBJ_P(value)->handlers->offset); if (!base_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Iterator %s returns an SplFileInfo object, so base directory must be specified", ZSTR_VAL(ce->name)); return ZEND_HASH_APPLY_STOP; } switch (intern->type) { case SPL_FS_DIR: test = spl_filesystem_object_get_path(intern, NULL); fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); php_stat(fname, fname_len, FS_IS_DIR, &dummy); if (Z_TYPE(dummy) == IS_TRUE) { /* ignore directories */ efree(fname); return ZEND_HASH_APPLY_KEEP; } test = expand_filepath(fname, NULL); efree(fname); if (test) { fname = test; fname_len = strlen(fname); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Could not resolve file path"); return ZEND_HASH_APPLY_STOP; } save = fname; goto phar_spl_fileinfo; case SPL_FS_INFO: case SPL_FS_FILE: fname = expand_filepath(intern->file_name, NULL); if (!fname) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Could not resolve file path"); return ZEND_HASH_APPLY_STOP; } fname_len = strlen(fname); save = fname; goto phar_spl_fileinfo; } } /* fall-through */ default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid value (must return a string)", ZSTR_VAL(ce->name)); return ZEND_HASH_APPLY_STOP; } fname = Z_STRVAL_P(value); fname_len = Z_STRLEN_P(value); phar_spl_fileinfo: if (base_len) { temp = expand_filepath(base, NULL); if (!temp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Could not resolve file path"); if (save) { efree(save); } return ZEND_HASH_APPLY_STOP; } base = temp; base_len = strlen(base); if (strstr(fname, base)) { str_key_len = fname_len - base_len; if (str_key_len <= 0) { if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_KEEP; } str_key = fname + base_len; if (*str_key == '/' || *str_key == '\\') { str_key++; str_key_len--; } } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned a path \"%s\" that is not in the base directory \"%s\"", ZSTR_VAL(ce->name), fname, base); if (save) { efree(save); efree(temp); } return ZEND_HASH_APPLY_STOP; } } else { if (iter->funcs->get_current_key) { zval key; iter->funcs->get_current_key(iter, &key); if (EG(exception)) { return ZEND_HASH_APPLY_STOP; } if (Z_TYPE(key) != IS_STRING) { zval_ptr_dtor(&key); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name)); return ZEND_HASH_APPLY_STOP; } str_key_len = Z_STRLEN(key); str_key = estrndup(Z_STRVAL(key), str_key_len); save = str_key; zval_ptr_dtor_str(&key); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name)); return ZEND_HASH_APPLY_STOP; } } if (php_check_open_basedir(fname)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned a path \"%s\" that open_basedir prevents opening", ZSTR_VAL(ce->name), fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } /* try to open source file, then create internal phar file and copy contents */ fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened); if (!fp) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned a file that could not be opened \"%s\"", ZSTR_VAL(ce->name), fname); if (save) { efree(save); } if (temp) { efree(temp); } return ZEND_HASH_APPLY_STOP; } after_open_fp: if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) { /* silently skip any files that would be added to the magic .phar directory */ if (save) { efree(save); } if (temp) { efree(temp); } if (opened) { zend_string_release_ex(opened, 0); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_KEEP; } if (!(data = phar_get_or_create_entry_data(phar_obj->archive->fname, phar_obj->archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s cannot be created: %s", str_key, error); efree(error); if (save) { efree(save); } if (opened) { zend_string_release_ex(opened, 0); } if (temp) { efree(temp); } if (close_fp) { php_stream_close(fp); } return ZEND_HASH_APPLY_STOP; } else { if (error) { efree(error); } /* convert to PHAR_UFP */ if (data->internal_file->fp_type == PHAR_MOD) { php_stream_close(data->internal_file->fp); } data->internal_file->fp = NULL; data->internal_file->fp_type = PHAR_UFP; data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); data->fp = NULL; php_stream_copy_to_stream_ex(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = php_stream_tell(p_obj->fp) - data->internal_file->offset; if (php_stream_stat(fp, &ssb) != -1) { data->internal_file->flags = ssb.sb.st_mode & PHAR_ENT_PERM_MASK ; } else { #ifndef _WIN32 mode_t mask; mask = umask(0); umask(mask); data->internal_file->flags &= ~mask; #endif } } if (close_fp) { php_stream_close(fp); } add_assoc_str(p_obj->ret, str_key, opened); if (save) { efree(save); } if (temp) { efree(temp); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; phar_entry_delref(data); return ZEND_HASH_APPLY_KEEP; } /* }}} */ /* {{{ Construct a phar archive from an existing directory, recursively. * Optional second parameter is a regular expression for filtering directory contents. * * Return value is an array mapping phar index to actual files added. */ PHP_METHOD(Phar, buildFromDirectory) { char *dir, *error, *regex = NULL; size_t dir_len, regex_len = 0; bool apply_reg = 0; zval arg, arg2, iter, iteriter, regexiter; struct _phar_t pass; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s", &dir, &dir_len, &regex, &regex_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write to archive - write operations restricted by INI setting"); RETURN_THROWS(); } if (ZEND_SIZE_T_UINT_OVFL(dir_len)) { RETURN_FALSE; } if (SUCCESS != object_init_ex(&iter, spl_ce_RecursiveDirectoryIterator)) { zval_ptr_dtor(&iter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname); RETURN_THROWS(); } ZVAL_STRINGL(&arg, dir, dir_len); ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS); zend_call_known_instance_method_with_2_params(spl_ce_RecursiveDirectoryIterator->constructor, Z_OBJ(iter), NULL, &arg, &arg2); zval_ptr_dtor(&arg); if (EG(exception)) { zval_ptr_dtor(&iter); RETURN_THROWS(); } if (SUCCESS != object_init_ex(&iteriter, spl_ce_RecursiveIteratorIterator)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname); RETURN_THROWS(); } zend_call_known_instance_method_with_1_params(spl_ce_RecursiveIteratorIterator->constructor, Z_OBJ(iteriter), NULL, &iter); if (EG(exception)) { zval_ptr_dtor(&iter); zval_ptr_dtor(&iteriter); RETURN_THROWS(); } zval_ptr_dtor(&iter); if (regex_len > 0) { apply_reg = 1; if (SUCCESS != object_init_ex(&regexiter, spl_ce_RegexIterator)) { zval_ptr_dtor(&iteriter); zval_ptr_dtor(&regexiter); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate regex iterator for %s", phar_obj->archive->fname); RETURN_THROWS(); } ZVAL_STRINGL(&arg2, regex, regex_len); zend_call_known_instance_method_with_2_params(spl_ce_RegexIterator->constructor, Z_OBJ(regexiter), NULL, &iteriter, &arg2); zval_ptr_dtor(&arg2); } array_init(return_value); pass.c = apply_reg ? Z_OBJCE(regexiter) : Z_OBJCE(iteriter); pass.p = phar_obj; pass.b = dir; pass.l = (uint32_t)dir_len; pass.count = 0; pass.ret = return_value; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" unable to create temporary file", phar_obj->archive->fname); RETURN_THROWS(); } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } if (SUCCESS == spl_iterator_apply((apply_reg ? &regexiter : &iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass)) { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } phar_obj->archive->ufp = pass.fp; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } else { zval_ptr_dtor(&iteriter); if (apply_reg) { zval_ptr_dtor(&regexiter); } php_stream_close(pass.fp); } } /* }}} */ /* {{{ Construct a phar archive from an iterator. The iterator must return a series of strings * that are full paths to files that should be added to the phar. The iterator key should * be the path that the file will have within the phar archive. * * If base directory is specified, then the key will be ignored, and instead the portion of * the current value minus the base directory will be used * * Returned is an array mapping phar index to actual file added */ PHP_METHOD(Phar, buildFromIterator) { zval *obj; char *error; size_t base_len = 0; char *base = NULL; struct _phar_t pass; if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|s!", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out phar archive, phar is read-only"); RETURN_THROWS(); } if (ZEND_SIZE_T_UINT_OVFL(base_len)) { RETURN_FALSE; } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } array_init(return_value); pass.c = Z_OBJCE_P(obj); pass.p = phar_obj; pass.b = base; pass.l = (uint32_t)base_len; pass.ret = return_value; pass.count = 0; pass.fp = php_stream_fopen_tmpfile(); if (pass.fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\": unable to create temporary file", phar_obj->archive->fname); RETURN_THROWS(); } if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass)) { phar_obj->archive->ufp = pass.fp; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } else { php_stream_close(pass.fp); } } /* }}} */ /* {{{ Returns the number of entries in the Phar archive */ PHP_METHOD(Phar, count) { /* mode can be ignored, maximum depth is 1 */ zend_long mode; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &mode) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); RETURN_LONG(zend_hash_num_elements(&phar_obj->archive->manifest)); } /* }}} */ /* {{{ Returns true if the phar archive is based on the tar/zip/phar file format depending * on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in */ PHP_METHOD(Phar, isFileFormat) { zend_long type; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &type) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); switch (type) { case PHAR_FORMAT_TAR: RETURN_BOOL(phar_obj->archive->is_tar); case PHAR_FORMAT_ZIP: RETURN_BOOL(phar_obj->archive->is_zip); case PHAR_FORMAT_PHAR: RETURN_BOOL(!phar_obj->archive->is_tar && !phar_obj->archive->is_zip); default: zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown file format specified"); } } /* }}} */ static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp) /* {{{ */ { char *error; zend_off_t offset; phar_entry_info *link; if (FAILURE == phar_open_entry_fp(entry, &error, 1)) { if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename); } return FAILURE; } /* copy old contents in entirety */ phar_seek_efp(entry, 0, SEEK_SET, 0, 1); offset = php_stream_tell(fp); link = phar_get_link_source(entry); if (!link) { link = entry; } if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(link, 0), fp, link->uncompressed_filesize, NULL)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename); return FAILURE; } if (entry->fp_type == PHAR_MOD) { /* save for potential restore on error */ entry->cfp = entry->fp; entry->fp = NULL; } /* set new location of file contents */ entry->fp_type = PHAR_FP; entry->offset = offset; return SUCCESS; } /* }}} */ static zend_object *phar_rename_archive(phar_archive_data **sphar, char *ext) /* {{{ */ { const char *oldname = NULL; phar_archive_data *phar = *sphar; char *oldpath = NULL; char *basename = NULL, *basepath = NULL; char *newname = NULL, *newpath = NULL; zval ret, arg1; zend_class_entry *ce; char *error = NULL; const char *pcr_error; size_t ext_len = ext ? strlen(ext) : 0; size_t new_len, oldname_len, phar_ext_len; phar_archive_data *pphar = NULL; php_stream_statbuf ssb; int phar_ext_list_len, i = 0; char *ext_pos = NULL; /* Array of PHAR extensions, Must be in order, starting with longest * ending with the shortest. */ char *phar_ext_list[] = { ".phar.tar.bz2", ".phar.tar.gz", ".phar.php", ".phar.bz2", ".phar.zip", ".phar.tar", ".phar.gz", ".tar.bz2", ".tar.gz", ".phar", ".tar", ".zip" }; if (!ext) { if (phar->is_zip) { if (phar->is_data) { ext = "zip"; } else { ext = "phar.zip"; } } else if (phar->is_tar) { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: if (phar->is_data) { ext = "tar.gz"; } else { ext = "phar.tar.gz"; } break; case PHAR_FILE_COMPRESSED_BZ2: if (phar->is_data) { ext = "tar.bz2"; } else { ext = "phar.tar.bz2"; } break; default: if (phar->is_data) { ext = "tar"; } else { ext = "phar.tar"; } } } else { switch (phar->flags) { case PHAR_FILE_COMPRESSED_GZ: ext = "phar.gz"; break; case PHAR_FILE_COMPRESSED_BZ2: ext = "phar.bz2"; break; default: ext = "phar"; } } } else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) { if (phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext); } return NULL; } oldpath = estrndup(phar->fname, phar->fname_len); if ((oldname = zend_memrchr(phar->fname, '/', phar->fname_len))) { ++oldname; } else { oldname = phar->fname; } oldname_len = strlen(oldname); /* Copy the old name to create base for the new name */ basename = estrndup(oldname, oldname_len); phar_ext_list_len = sizeof(phar_ext_list)/sizeof(phar_ext_list[0]); /* Remove possible PHAR extensions */ /* phar_ext_list must be in order of longest extension to shortest */ for (i=0; i < phar_ext_list_len; i++) { phar_ext_len = strlen(phar_ext_list[i]); if (phar_ext_len && oldname_len > phar_ext_len) { /* Check if the basename strings ends with the extension */ if (memcmp(phar_ext_list[i], basename + (oldname_len - phar_ext_len), phar_ext_len) == 0) { ext_pos = basename + (oldname_len - phar_ext_len); ext_pos[0] = '\0'; break; } } ext_pos = NULL; } /* If no default PHAR extension found remove the last extension */ if (!ext_pos) { ext_pos = strrchr(basename, '.'); if (ext_pos) { ext_pos[0] = '\0'; } } ext_pos = NULL; if (ext[0] == '.') { ++ext; } /* Append extension to the basename */ spprintf(&newname, 0, "%s.%s", basename, ext); efree(basename); basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len)); new_len = spprintf(&newpath, 0, "%s%s", basepath, newname); phar->fname_len = new_len; phar->fname = newpath; phar->ext = newpath + phar->fname_len - strlen(ext) - 1; efree(basepath); efree(newname); if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, newpath, phar->fname_len))) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname); return NULL; } if (NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), newpath, phar->fname_len))) { if (pphar->fname_len == phar->fname_len && !memcmp(pphar->fname, phar->fname, phar->fname_len)) { if (!zend_hash_num_elements(&phar->manifest)) { pphar->is_tar = phar->is_tar; pphar->is_zip = phar->is_zip; pphar->is_data = phar->is_data; pphar->flags = phar->flags; pphar->fp = phar->fp; phar->fp = NULL; phar_destroy_phar_data(phar); *sphar = NULL; phar = pphar; phar->refcount++; newpath = oldpath; goto its_ok; } } efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname); return NULL; } its_ok: if (SUCCESS == php_stream_stat_path(newpath, &ssb)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar \"%s\" exists and must be unlinked prior to conversion", newpath); efree(oldpath); return NULL; } if (!phar->is_data) { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &ext_len, 1, 1, 1)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar \"%s\" has invalid extension %s", phar->fname, ext); return NULL; } phar->ext_len = ext_len; if (phar->alias) { if (phar->is_temporary_alias) { phar->alias = NULL; phar->alias_len = 0; } else { phar->alias = estrndup(newpath, strlen(newpath)); phar->alias_len = strlen(newpath); phar->is_temporary_alias = 1; zend_hash_str_update_ptr(&(PHAR_G(phar_alias_map)), newpath, phar->fname_len, phar); } } } else { if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &ext_len, 0, 1, 1)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "data phar \"%s\" has invalid extension %s", phar->fname, ext); return NULL; } phar->ext_len = ext_len; phar->alias = NULL; phar->alias_len = 0; } if ((!pphar || phar == pphar) && NULL == zend_hash_str_update_ptr(&(PHAR_G(phar_fname_map)), newpath, phar->fname_len, phar)) { efree(oldpath); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname); return NULL; } phar_flush(phar, 0, 0, 1, &error); if (error) { zend_hash_str_del(&(PHAR_G(phar_fname_map)), newpath, phar->fname_len); *sphar = NULL; zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "%s", error); efree(error); efree(oldpath); return NULL; } efree(oldpath); if (phar->is_data) { ce = phar_ce_data; } else { ce = phar_ce_archive; } ZVAL_NULL(&ret); if (SUCCESS != object_init_ex(&ret, ce)) { zval_ptr_dtor(&ret); zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname); return NULL; } ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len); zend_call_known_instance_method_with_1_params(ce->constructor, Z_OBJ(ret), NULL, &arg1); zval_ptr_dtor(&arg1); return Z_OBJ(ret); } /* }}} */ static zend_object *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, uint32_t flags) /* {{{ */ { phar_archive_data *phar; phar_entry_info *entry, newentry; zend_object *ret; /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data)); /* set whole-archive compression and type from parameter */ phar->flags = flags; phar->is_data = source->is_data; switch (convert) { case PHAR_FORMAT_TAR: phar->is_tar = 1; break; case PHAR_FORMAT_ZIP: phar->is_zip = 1; break; default: phar->is_data = 0; break; } zend_hash_init(&(phar->manifest), sizeof(phar_entry_info), zend_get_hash_value, destroy_phar_manifest_entry, 0); zend_hash_init(&phar->mounted_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); zend_hash_init(&phar->virtual_dirs, sizeof(char *), zend_get_hash_value, NULL, 0); phar->fp = php_stream_fopen_tmpfile(); if (phar->fp == NULL) { zend_throw_exception_ex(phar_ce_PharException, 0, "unable to create temporary file"); return NULL; } phar->fname = source->fname; phar->fname_len = source->fname_len; phar->is_temporary_alias = source->is_temporary_alias; phar->alias = source->alias; phar_metadata_tracker_copy(&phar->metadata_tracker, &source->metadata_tracker, phar->is_persistent); /* first copy each file's uncompressed contents to a temporary file and set per-file flags */ ZEND_HASH_FOREACH_PTR(&source->manifest, entry) { newentry = *entry; if (newentry.link) { newentry.link = estrdup(newentry.link); goto no_copy; } if (newentry.tmp) { newentry.tmp = estrdup(newentry.tmp); goto no_copy; } if (FAILURE == phar_copy_file_contents(&newentry, phar->fp)) { zend_hash_destroy(&(phar->manifest)); php_stream_close(phar->fp); efree(phar); /* exception already thrown */ return NULL; } no_copy: newentry.filename = estrndup(newentry.filename, newentry.filename_len); phar_metadata_tracker_clone(&newentry.metadata_tracker); newentry.is_zip = phar->is_zip; newentry.is_tar = phar->is_tar; if (newentry.is_tar) { newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE); } newentry.is_modified = 1; newentry.phar = phar; newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */ phar_set_inode(&newentry); zend_hash_str_add_mem(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info)); phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len); } ZEND_HASH_FOREACH_END(); if ((ret = phar_rename_archive(&phar, ext))) { return ret; } else { if(phar != NULL) { zend_hash_destroy(&(phar->manifest)); zend_hash_destroy(&(phar->mounted_dirs)); zend_hash_destroy(&(phar->virtual_dirs)); if (phar->fp) { php_stream_close(phar->fp); } efree(phar->fname); efree(phar); } return NULL; } } /* }}} */ /* {{{ Convert a phar.tar or phar.zip archive to the phar file format. The * optional parameter allows the user to determine the new * filename extension (default is phar). */ PHP_METHOD(Phar, convertToExecutable) { char *ext = NULL; int is_data; size_t ext_len = 0; uint32_t flags; zend_object *ret; zend_long format, method; bool format_is_null = 1, method_is_null = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!l!s!", &format, &format_is_null, &method, &method_is_null, &ext, &ext_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out executable phar archive, phar is read-only"); RETURN_THROWS(); } if (format_is_null) { format = PHAR_FORMAT_SAME; } switch (format) { case 9021976: /* Retained for BC */ case PHAR_FORMAT_SAME: /* by default, use the existing format */ if (phar_obj->archive->is_tar) { format = PHAR_FORMAT_TAR; } else if (phar_obj->archive->is_zip) { format = PHAR_FORMAT_ZIP; } else { format = PHAR_FORMAT_PHAR; } break; case PHAR_FORMAT_PHAR: case PHAR_FORMAT_TAR: case PHAR_FORMAT_ZIP: break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unknown file format specified, please pass one of Phar::PHAR, Phar::TAR or Phar::ZIP"); RETURN_THROWS(); } if (method_is_null) { flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK; } else { switch (method) { case 9021976: /* Retained for BC */ flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK; break; case 0: flags = PHAR_FILE_COMPRESSED_NONE; break; case PHAR_ENT_COMPRESSED_GZ: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with gzip, zip archives do not support whole-archive compression"); RETURN_THROWS(); } if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with gzip, enable ext/zlib in php.ini"); RETURN_THROWS(); } flags = PHAR_FILE_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with bz2, zip archives do not support whole-archive compression"); RETURN_THROWS(); } if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini"); RETURN_THROWS(); } flags = PHAR_FILE_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); RETURN_THROWS(); } } is_data = phar_obj->archive->is_data; phar_obj->archive->is_data = 0; ret = phar_convert_to_other(phar_obj->archive, format, ext, flags); phar_obj->archive->is_data = is_data; if (ret) { RETURN_OBJ(ret); } else { RETURN_NULL(); } } /* }}} */ /* {{{ Convert an archive to a non-executable .tar or .zip. * The optional parameter allows the user to determine the new * filename extension (default is .zip or .tar). */ PHP_METHOD(Phar, convertToData) { char *ext = NULL; int is_data; size_t ext_len = 0; uint32_t flags; zend_object *ret; zend_long format, method; bool format_is_null = 1, method_is_null = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!l!s!", &format, &format_is_null, &method, &method_is_null, &ext, &ext_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (format_is_null) { format = PHAR_FORMAT_SAME; } switch (format) { case 9021976: /* Retained for BC */ case PHAR_FORMAT_SAME: /* by default, use the existing format */ if (phar_obj->archive->is_tar) { format = PHAR_FORMAT_TAR; } else if (phar_obj->archive->is_zip) { format = PHAR_FORMAT_ZIP; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out data phar archive, use Phar::TAR or Phar::ZIP"); RETURN_THROWS(); } break; case PHAR_FORMAT_PHAR: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out data phar archive, use Phar::TAR or Phar::ZIP"); RETURN_THROWS(); case PHAR_FORMAT_TAR: case PHAR_FORMAT_ZIP: break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unknown file format specified, please pass one of Phar::TAR or Phar::ZIP"); RETURN_THROWS(); } if (method_is_null) { flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK; } else { switch (method) { case 9021976: /* Retained for BC */ flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK; break; case 0: flags = PHAR_FILE_COMPRESSED_NONE; break; case PHAR_ENT_COMPRESSED_GZ: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with gzip, zip archives do not support whole-archive compression"); RETURN_THROWS(); } if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with gzip, enable ext/zlib in php.ini"); RETURN_THROWS(); } flags = PHAR_FILE_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (format == PHAR_FORMAT_ZIP) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with bz2, zip archives do not support whole-archive compression"); RETURN_THROWS(); } if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini"); RETURN_THROWS(); } flags = PHAR_FILE_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); RETURN_THROWS(); } } is_data = phar_obj->archive->is_data; phar_obj->archive->is_data = 1; ret = phar_convert_to_other(phar_obj->archive, (int)format, ext, flags); phar_obj->archive->is_data = is_data; if (ret) { RETURN_OBJ(ret); } else { RETURN_NULL(); } } /* }}} */ /* {{{ Returns Phar::GZ or PHAR::BZ2 if the entire archive is compressed * (.tar.gz/tar.bz2 and so on), or FALSE otherwise. */ PHP_METHOD(Phar, isCompressed) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (phar_obj->archive->flags & PHAR_FILE_COMPRESSED_GZ) { RETURN_LONG(PHAR_ENT_COMPRESSED_GZ); } if (phar_obj->archive->flags & PHAR_FILE_COMPRESSED_BZ2) { RETURN_LONG(PHAR_ENT_COMPRESSED_BZ2); } RETURN_FALSE; } /* }}} */ /* {{{ Returns true if phar.readonly=0 or phar is a PharData AND the actual file is writable. */ PHP_METHOD(Phar, isWritable) { php_stream_statbuf ssb; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (!phar_obj->archive->is_writeable) { RETURN_FALSE; } if (SUCCESS != php_stream_stat_path(phar_obj->archive->fname, &ssb)) { if (phar_obj->archive->is_brandnew) { /* assume it works if the file doesn't exist yet */ RETURN_TRUE; } RETURN_FALSE; } RETURN_BOOL((ssb.sb.st_mode & (S_IWOTH | S_IWGRP | S_IWUSR)) != 0); } /* }}} */ /* {{{ Deletes a named file within the archive. */ PHP_METHOD(Phar, delete) { char *fname; size_t fname_len; char *error; phar_entry_info *entry; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out phar archive, phar is read-only"); RETURN_THROWS(); } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint32_t) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint32_t) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_TRUE; } else { entry->is_deleted = 1; entry->is_modified = 1; phar_obj->archive->is_modified = 1; } } } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname); RETURN_THROWS(); } phar_flush(phar_obj->archive, NULL, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } RETURN_TRUE; } /* }}} */ /* {{{ Returns the alias for the Phar or NULL. */ PHP_METHOD(Phar, getAlias) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (phar_obj->archive->alias && phar_obj->archive->alias != phar_obj->archive->fname) { RETURN_STRINGL(phar_obj->archive->alias, phar_obj->archive->alias_len); } } /* }}} */ /* {{{ Returns the real path to the phar archive on disk */ PHP_METHOD(Phar, getPath) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); RETURN_STRINGL(phar_obj->archive->fname, phar_obj->archive->fname_len); } /* }}} */ /* {{{ Sets the alias for a Phar archive. The default value is the full path * to the archive. */ PHP_METHOD(Phar, setAlias) { char *alias, *error, *oldalias; phar_archive_data *fd_ptr; size_t alias_len, oldalias_len; int old_temp, readd = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &alias, &alias_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out phar archive, phar is read-only"); RETURN_THROWS(); } /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; if (phar_obj->archive->is_data) { if (phar_obj->archive->is_tar) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "A Phar alias cannot be set in a plain tar archive"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "A Phar alias cannot be set in a plain zip archive"); } RETURN_THROWS(); } if (alias_len == phar_obj->archive->alias_len && memcmp(phar_obj->archive->alias, alias, alias_len) == 0) { RETURN_TRUE; } if (alias_len && NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) { spprintf(&error, 0, "alias \"%s\" is already used for archive \"%s\" and cannot be used for other archives", alias, fd_ptr->fname); if (SUCCESS == phar_free_alias(fd_ptr, alias, alias_len)) { efree(error); goto valid_alias; } zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } if (!phar_validate_alias(alias, alias_len)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Invalid alias \"%s\" specified for phar \"%s\"", alias, phar_obj->archive->fname); RETURN_THROWS(); } valid_alias: if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } if (phar_obj->archive->alias_len && NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), phar_obj->archive->alias, phar_obj->archive->alias_len))) { zend_hash_str_del(&(PHAR_G(phar_alias_map)), phar_obj->archive->alias, phar_obj->archive->alias_len); readd = 1; } oldalias = phar_obj->archive->alias; oldalias_len = phar_obj->archive->alias_len; old_temp = phar_obj->archive->is_temporary_alias; if (alias_len) { phar_obj->archive->alias = estrndup(alias, alias_len); } else { phar_obj->archive->alias = NULL; } phar_obj->archive->alias_len = alias_len; phar_obj->archive->is_temporary_alias = 0; phar_flush(phar_obj->archive, NULL, 0, 0, &error); if (error) { phar_obj->archive->alias = oldalias; phar_obj->archive->alias_len = oldalias_len; phar_obj->archive->is_temporary_alias = old_temp; zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); if (readd) { zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), oldalias, oldalias_len, phar_obj->archive); } efree(error); RETURN_THROWS(); } zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len, phar_obj->archive); if (oldalias) { efree(oldalias); } RETURN_TRUE; } /* }}} */ /* {{{ Return version info of Phar archive */ PHP_METHOD(Phar, getVersion) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); RETURN_STRING(phar_obj->archive->version); } /* }}} */ /* {{{ Do not flush a writeable phar (save its contents) until explicitly requested */ PHP_METHOD(Phar, startBuffering) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); phar_obj->archive->donotflush = 1; } /* }}} */ /* {{{ Returns whether write operations are flushing to disk immediately. */ PHP_METHOD(Phar, isBuffering) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); RETURN_BOOL(phar_obj->archive->donotflush); } /* }}} */ /* {{{ Saves the contents of a modified archive to disk. */ PHP_METHOD(Phar, stopBuffering) { char *error; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out phar archive, phar is read-only"); RETURN_THROWS(); } phar_obj->archive->donotflush = 0; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ Change the stub in a phar, phar.tar or phar.zip archive to something other * than the default. The stub *must* end with a call to __HALT_COMPILER(). */ PHP_METHOD(Phar, setStub) { zval *zstub; char *stub, *error; size_t stub_len; zend_long len = -1; php_stream *stream; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot change stub, phar is read-only"); RETURN_THROWS(); } if (phar_obj->archive->is_data) { if (phar_obj->archive->is_tar) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "A Phar stub cannot be set in a plain tar archive"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "A Phar stub cannot be set in a plain zip archive"); } RETURN_THROWS(); } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r|l", &zstub, &len) == SUCCESS) { if ((php_stream_from_zval_no_verify(stream, zstub)) != NULL) { if (len > 0) { len = -len; } else { len = -1; } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } phar_flush(phar_obj->archive, (char *) zstub, len, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot change stub, unable to read from input stream"); } } else if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &stub, &stub_len) == SUCCESS) { if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } phar_flush(phar_obj->archive, stub, stub_len, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } RETURN_TRUE; } RETURN_THROWS(); } /* }}} */ /* {{{ In a pure phar archive, sets a stub that can be used to run the archive * regardless of whether the phar extension is available. The first parameter * is the CLI startup filename, which defaults to "index.php". The second * parameter is the web startup filename and also defaults to "index.php" * (falling back to CLI behaviour). * Both parameters are optional. * In a phar.zip or phar.tar archive, the default stub is used only to * identify the archive to the extension as a Phar object. This allows the * extension to treat phar.zip and phar.tar types as honorary phars. Since * files cannot be loaded via this kind of stub, no parameters are accepted * when the Phar object is zip- or tar-based. */ PHP_METHOD(Phar, setDefaultStub) { char *index = NULL, *webindex = NULL, *error = NULL; zend_string *stub = NULL; size_t index_len = 0, webindex_len = 0; int created_stub = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!s!", &index, &index_len, &webindex, &webindex_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (phar_obj->archive->is_data) { if (phar_obj->archive->is_tar) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "A Phar stub cannot be set in a plain tar archive"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "A Phar stub cannot be set in a plain zip archive"); } RETURN_THROWS(); } if ((index || webindex) && (phar_obj->archive->is_tar || phar_obj->archive->is_zip)) { zend_argument_value_error(index ? 1 : 2, "must be null for a tar- or zip-based phar stub, string given"); RETURN_THROWS(); } if (PHAR_G(readonly)) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot change stub: phar.readonly=1"); RETURN_THROWS(); } if (!phar_obj->archive->is_tar && !phar_obj->archive->is_zip) { stub = phar_create_default_stub(index, webindex, &error); if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "%s", error); efree(error); if (stub) { zend_string_free(stub); } RETURN_THROWS(); } created_stub = 1; } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } phar_flush(phar_obj->archive, stub ? ZSTR_VAL(stub) : 0, stub ? ZSTR_LEN(stub) : 0, 1, &error); if (created_stub) { zend_string_free(stub); } if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } RETURN_TRUE; } /* }}} */ /* {{{ Sets the signature algorithm for a phar and applies it. The signature * algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, * Phar::SHA512, or Phar::OPENSSL. Note that zip- based phar archives * cannot support signatures. */ PHP_METHOD(Phar, setSignatureAlgorithm) { zend_long algo; char *error, *key = NULL; size_t key_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|s!", &algo, &key, &key_len) != SUCCESS) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot set signature algorithm, phar is read-only"); RETURN_THROWS(); } switch (algo) { case PHAR_SIG_SHA256: case PHAR_SIG_SHA512: case PHAR_SIG_MD5: case PHAR_SIG_SHA1: case PHAR_SIG_OPENSSL: if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } phar_obj->archive->sig_flags = (php_uint32)algo; phar_obj->archive->is_modified = 1; PHAR_G(openssl_privatekey) = key; PHAR_G(openssl_privatekey_len) = key_len; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } break; default: zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Unknown signature algorithm specified"); } } /* }}} */ /* {{{ Returns a hash signature, or FALSE if the archive is unsigned. */ PHP_METHOD(Phar, getSignature) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (phar_obj->archive->signature) { zend_string *unknown; array_init(return_value); add_assoc_stringl(return_value, "hash", phar_obj->archive->signature, phar_obj->archive->sig_len); switch(phar_obj->archive->sig_flags) { case PHAR_SIG_MD5: add_assoc_stringl(return_value, "hash_type", "MD5", 3); break; case PHAR_SIG_SHA1: add_assoc_stringl(return_value, "hash_type", "SHA-1", 5); break; case PHAR_SIG_SHA256: add_assoc_stringl(return_value, "hash_type", "SHA-256", 7); break; case PHAR_SIG_SHA512: add_assoc_stringl(return_value, "hash_type", "SHA-512", 7); break; case PHAR_SIG_OPENSSL: add_assoc_stringl(return_value, "hash_type", "OpenSSL", 7); break; default: unknown = strpprintf(0, "Unknown (%u)", phar_obj->archive->sig_flags); add_assoc_str(return_value, "hash_type", unknown); break; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ Return whether phar was modified */ PHP_METHOD(Phar, getModified) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); RETURN_BOOL(phar_obj->archive->is_modified); } /* }}} */ static int phar_set_compression(zval *zv, void *argument) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)Z_PTR_P(zv); uint32_t compress = *(uint32_t *)argument; if (entry->is_deleted) { return ZEND_HASH_APPLY_KEEP; } entry->old_flags = entry->flags; entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry->flags |= compress; entry->is_modified = 1; return ZEND_HASH_APPLY_KEEP; } /* }}} */ static int phar_test_compression(zval *zv, void *argument) /* {{{ */ { phar_entry_info *entry = (phar_entry_info *)Z_PTR_P(zv); if (entry->is_deleted) { return ZEND_HASH_APPLY_KEEP; } if (!PHAR_G(has_bz2)) { if (entry->flags & PHAR_ENT_COMPRESSED_BZ2) { *(int *) argument = 0; } } if (!PHAR_G(has_zlib)) { if (entry->flags & PHAR_ENT_COMPRESSED_GZ) { *(int *) argument = 0; } } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static void pharobj_set_compression(HashTable *manifest, uint32_t compress) /* {{{ */ { zend_hash_apply_with_argument(manifest, phar_set_compression, &compress); } /* }}} */ static int pharobj_cancompress(HashTable *manifest) /* {{{ */ { int test; test = 1; zend_hash_apply_with_argument(manifest, phar_test_compression, &test); return test; } /* }}} */ /* {{{ Compress a .tar, or .phar.tar with whole-file compression * The parameter can be one of Phar::GZ or Phar::BZ2 to specify * the kind of compression desired */ PHP_METHOD(Phar, compress) { zend_long method; char *ext = NULL; size_t ext_len = 0; uint32_t flags; zend_object *ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|s!", &method, &ext, &ext_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot compress phar archive, phar is read-only"); RETURN_THROWS(); } if (phar_obj->archive->is_zip) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot compress zip-based archives with whole-archive compression"); RETURN_THROWS(); } switch (method) { case 0: flags = PHAR_FILE_COMPRESSED_NONE; break; case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with gzip, enable ext/zlib in php.ini"); RETURN_THROWS(); } flags = PHAR_FILE_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress entire archive with bz2, enable ext/bz2 in php.ini"); return; } flags = PHAR_FILE_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); RETURN_THROWS(); } if (phar_obj->archive->is_tar) { ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_TAR, ext, flags); } else { ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_PHAR, ext, flags); } if (ret) { RETURN_OBJ(ret); } else { RETURN_NULL(); } } /* }}} */ /* {{{ Decompress a .tar, or .phar.tar with whole-file compression */ PHP_METHOD(Phar, decompress) { char *ext = NULL; size_t ext_len = 0; zend_object *ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!", &ext, &ext_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot decompress phar archive, phar is read-only"); RETURN_THROWS(); } if (phar_obj->archive->is_zip) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot decompress zip-based archives with whole-archive compression"); RETURN_THROWS(); } if (phar_obj->archive->is_tar) { ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_TAR, ext, PHAR_FILE_COMPRESSED_NONE); } else { ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_PHAR, ext, PHAR_FILE_COMPRESSED_NONE); } if (ret) { RETURN_OBJ(ret); } else { RETURN_NULL(); } } /* }}} */ /* {{{ Compress all files within a phar or zip archive using the specified compression * The parameter can be one of Phar::GZ or Phar::BZ2 to specify * the kind of compression desired */ PHP_METHOD(Phar, compressFiles) { char *error; uint32_t flags; zend_long method; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &method) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Phar is readonly, cannot change compression"); RETURN_THROWS(); } switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress files within archive with gzip, enable ext/zlib in php.ini"); RETURN_THROWS(); } flags = PHAR_ENT_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress files within archive with bz2, enable ext/bz2 in php.ini"); RETURN_THROWS(); } flags = PHAR_ENT_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2"); RETURN_THROWS(); } if (phar_obj->archive->is_tar) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress with Gzip compression, tar archives cannot compress individual files, use compress() to compress the whole archive"); RETURN_THROWS(); } if (!pharobj_cancompress(&phar_obj->archive->manifest)) { if (flags == PHAR_FILE_COMPRESSED_GZ) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress all files as Gzip, some are compressed as bzip2 and cannot be decompressed"); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress all files as Bzip2, some are compressed as gzip and cannot be decompressed"); } RETURN_THROWS(); } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } pharobj_set_compression(&phar_obj->archive->manifest, flags); phar_obj->archive->is_modified = 1; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ decompress every file */ PHP_METHOD(Phar, decompressFiles) { char *error; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Phar is readonly, cannot change compression"); RETURN_THROWS(); } if (!pharobj_cancompress(&phar_obj->archive->manifest)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot decompress all files, some are compressed as bzip2 or gzip and cannot be decompressed"); RETURN_THROWS(); } if (phar_obj->archive->is_tar) { RETURN_TRUE; } else { if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } pharobj_set_compression(&phar_obj->archive->manifest, PHAR_ENT_COMPRESSED_NONE); } phar_obj->archive->is_modified = 1; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ copy a file internal to the phar archive to another new file within the phar */ PHP_METHOD(Phar, copy) { char *oldfile, *newfile, *error; const char *pcr_error; size_t oldfile_len, newfile_len; phar_entry_info *oldentry, newentry = {0}, *temp; size_t tmp_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile); RETURN_THROWS(); } if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_THROWS(); } if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) { /* can't copy a meta file */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_THROWS(); } if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint32_t) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint32_t) oldfile_len)) || oldentry->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname); RETURN_THROWS(); } if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint32_t) newfile_len)) { if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint32_t) newfile_len)) || !temp->is_deleted) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname); RETURN_THROWS(); } } tmp_len = newfile_len; if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname); RETURN_THROWS(); } newfile_len = tmp_len; if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } /* re-populate with copied-on-write entry */ oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint32_t) oldfile_len); } memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info)); phar_metadata_tracker_clone(&newentry.metadata_tracker); newentry.filename = estrndup(newfile, newfile_len); newentry.filename_len = newfile_len; newentry.fp_refcount = 0; if (oldentry->fp_type != PHAR_FP) { if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) { efree(newentry.filename); php_stream_close(newentry.fp); zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } } zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info)); phar_obj->archive->is_modified = 1; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } /* }}} */ /* {{{ determines whether a file exists in the phar */ PHP_METHOD(Phar, offsetExists) { char *fname; size_t fname_len; phar_entry_info *entry; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint32_t) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint32_t) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_FALSE; } } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { /* none of these are real files, so they don't exist */ RETURN_FALSE; } RETURN_TRUE; } else { if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint32_t) fname_len)) { RETURN_TRUE; } RETURN_FALSE; } } /* }}} */ /* {{{ get a PharFileInfo object for a specific file */ PHP_METHOD(Phar, offsetGet) { char *fname, *error; size_t fname_len; zval zfname; phar_entry_info *entry; zend_string *sfname; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); /* security is 0 here so that we can get a better error message than "entry doesn't exist" */ if (!(entry = phar_get_entry_info_dir(phar_obj->archive, fname, fname_len, 1, &error, 0))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:""); } else { if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->archive->fname); RETURN_THROWS(); } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->archive->fname); RETURN_THROWS(); } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot directly get any files or directories in magic \".phar\" directory"); RETURN_THROWS(); } if (entry->is_temp_dir) { efree(entry->filename); efree(entry); } sfname = strpprintf(0, "phar://%s/%s", phar_obj->archive->fname, fname); ZVAL_NEW_STR(&zfname, sfname); spl_instantiate_arg_ex1(phar_obj->spl.info_class, return_value, &zfname); zval_ptr_dtor(&zfname); } } /* }}} */ /* {{{ add a file within the phar archive from a string or resource */ static void phar_add_file(phar_archive_data **pphar, char *filename, size_t filename_len, char *cont_str, size_t cont_len, zval *zresource) { size_t start_pos=0; char *error; size_t contents_len; phar_entry_data *data; php_stream *contents_file = NULL; php_stream_statbuf ssb; #ifdef PHP_WIN32 char *save_filename; ALLOCA_FLAG(filename_use_heap) #endif if (filename_len >= sizeof(".phar")-1) { start_pos = '/' == filename[0]; /* account for any leading slash: multiple-leads handled elsewhere */ if (!memcmp(&filename[start_pos], ".phar", sizeof(".phar")-1) && (filename[start_pos+5] == '/' || filename[start_pos+5] == '\\' || filename[start_pos+5] == '\0')) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create any files in magic \".phar\" directory"); return; } } #ifdef PHP_WIN32 save_filename = filename; if (memchr(filename, '\\', filename_len)) { filename = do_alloca(filename_len + 1, filename_use_heap); memcpy(filename, save_filename, filename_len); filename[filename_len] = '\0'; } #endif if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, filename, filename_len, "w+b", 0, &error, 1))) { if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be created: %s", filename, error); efree(error); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be created", filename); } goto finish; } else { if (error) { efree(error); } if (!data->internal_file->is_dir) { if (cont_str) { contents_len = php_stream_write(data->fp, cont_str, cont_len); if (contents_len != cont_len) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s could not be written to", filename); goto finish; } } else { if (!(php_stream_from_zval_no_verify(contents_file, zresource))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s could not be written to", filename); goto finish; } php_stream_copy_to_stream_ex(contents_file, data->fp, PHP_STREAM_COPY_ALL, &contents_len); } data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; } if (contents_file != NULL && php_stream_stat(contents_file, &ssb) != -1) { data->internal_file->flags = ssb.sb.st_mode & PHAR_ENT_PERM_MASK ; } else { #ifndef _WIN32 mode_t mask; mask = umask(0); umask(mask); data->internal_file->flags &= ~mask; #endif } /* check for copy-on-write */ if (pphar[0] != data->phar) { *pphar = data->phar; } phar_entry_delref(data); phar_flush(*pphar, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } finish: ; #ifdef PHP_WIN32 if (filename != save_filename) { free_alloca(filename, filename_use_heap); filename = save_filename; } #endif } /* }}} */ /* {{{ create a directory within the phar archive */ static void phar_mkdir(phar_archive_data **pphar, char *dirname, size_t dirname_len) { char *error; phar_entry_data *data; if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, dirname, dirname_len, "w+b", 2, &error, 1))) { if (error) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Directory %s does not exist and cannot be created: %s", dirname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Directory %s does not exist and cannot be created", dirname); } return; } else { if (error) { efree(error); } /* check for copy on write */ if (data->phar != *pphar) { *pphar = data->phar; } phar_entry_delref(data); phar_flush(*pphar, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } } /* }}} */ /* {{{ set the contents of an internal file to those of an external file */ PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; size_t fname_len, cont_len; zval *zresource; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "pr", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); RETURN_THROWS(); } if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname); RETURN_THROWS(); } if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname); RETURN_THROWS(); } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory"); RETURN_THROWS(); } phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource); } /* }}} */ /* {{{ remove a file from a phar */ PHP_METHOD(Phar, offsetUnset) { char *fname, *error; size_t fname_len; phar_entry_info *entry; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); RETURN_THROWS(); } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint32_t) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint32_t) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ return; } if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } /* re-populate entry after copy on write */ entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint32_t) fname_len); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ Adds an empty directory to the phar archive */ PHP_METHOD(Phar, addEmptyDir) { char *dirname; size_t dirname_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &dirname, &dirname_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create a directory in magic \".phar\" directory"); RETURN_THROWS(); } phar_mkdir(&phar_obj->archive, dirname, dirname_len); } /* }}} */ /* {{{ Adds a file to the archive using the filename, or the second parameter as the name within the archive */ PHP_METHOD(Phar, addFile) { char *fname, *localname = NULL; size_t fname_len, localname_len = 0; php_stream *resource; zval zresource; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s!", &fname, &fname_len, &localname, &localname_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (!strstr(fname, "://") && php_check_open_basedir(fname)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname); RETURN_THROWS(); } if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname); RETURN_THROWS(); } if (localname) { fname = localname; fname_len = localname_len; } php_stream_to_zval(resource, &zresource); phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource); zval_ptr_dtor(&zresource); } /* }}} */ /* {{{ Adds a file to the archive using its contents as a string */ PHP_METHOD(Phar, addFromString) { char *localname, *cont_str; size_t localname_len, cont_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL); } /* }}} */ /* {{{ Returns the stub at the head of a phar archive as a string. */ PHP_METHOD(Phar, getStub) { size_t len; zend_string *buf; php_stream *fp; php_stream_filter *filter = NULL; phar_entry_info *stub; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (phar_obj->archive->is_tar || phar_obj->archive->is_zip) { if (NULL != (stub = zend_hash_str_find_ptr(&(phar_obj->archive->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1))) { if (phar_obj->archive->fp && !phar_obj->archive->is_brandnew && !(stub->flags & PHAR_ENT_COMPRESSION_MASK)) { fp = phar_obj->archive->fp; } else { if (!(fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "phar error: unable to open phar \"%s\"", phar_obj->archive->fname); RETURN_THROWS(); } if (stub->flags & PHAR_ENT_COMPRESSION_MASK) { char *filter_name; if ((filter_name = phar_decompress_filter(stub, 0)) != NULL) { filter = php_stream_filter_create(filter_name, NULL, php_stream_is_persistent(fp)); } else { filter = NULL; } if (!filter) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "phar error: unable to read stub of phar \"%s\" (cannot create %s filter)", phar_obj->archive->fname, phar_decompress_filter(stub, 1)); RETURN_THROWS(); } php_stream_filter_append(&fp->readfilters, filter); } } if (!fp) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to read stub"); RETURN_THROWS(); } php_stream_seek(fp, stub->offset_abs, SEEK_SET); len = stub->uncompressed_filesize; goto carry_on; } else { RETURN_EMPTY_STRING(); } } len = phar_obj->archive->halt_offset; if (phar_obj->archive->fp && !phar_obj->archive->is_brandnew) { fp = phar_obj->archive->fp; } else { fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", 0, NULL); } if (!fp) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to read stub"); RETURN_THROWS(); } php_stream_rewind(fp); carry_on: buf = zend_string_alloc(len, 0); if (len != php_stream_read(fp, ZSTR_VAL(buf), len)) { if (fp != phar_obj->archive->fp) { php_stream_close(fp); } zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to read stub"); zend_string_release_ex(buf, 0); RETURN_THROWS(); } if (filter) { php_stream_filter_flush(filter, 1); php_stream_filter_remove(filter, 1); } if (fp != phar_obj->archive->fp) { php_stream_close(fp); } ZSTR_VAL(buf)[len] = '\0'; ZSTR_LEN(buf) = len; RETVAL_STR(buf); } /* }}}*/ /* {{{ Returns TRUE if the phar has global metadata, FALSE otherwise. */ PHP_METHOD(Phar, hasMetadata) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); RETURN_BOOL(phar_metadata_tracker_has_data(&phar_obj->archive->metadata_tracker, phar_obj->archive->is_persistent)); } /* }}} */ /* {{{ Returns the global metadata of the phar */ PHP_METHOD(Phar, getMetadata) { HashTable *unserialize_options = NULL; phar_metadata_tracker *tracker; ZEND_PARSE_PARAMETERS_START(0, 1) Z_PARAM_OPTIONAL Z_PARAM_ARRAY_HT(unserialize_options) ZEND_PARSE_PARAMETERS_END(); PHAR_ARCHIVE_OBJECT(); tracker = &phar_obj->archive->metadata_tracker; if (phar_metadata_tracker_has_data(tracker, phar_obj->archive->is_persistent)) { phar_metadata_tracker_unserialize_or_copy(tracker, return_value, phar_obj->archive->is_persistent, unserialize_options, "Phar::getMetadata"); } } /* }}} */ /* {{{ Modifies the phar metadata or throws */ static int serialize_metadata_or_throw(phar_metadata_tracker *tracker, int persistent, zval *metadata) { php_serialize_data_t metadata_hash; smart_str main_metadata_str = {0}; PHP_VAR_SERIALIZE_INIT(metadata_hash); php_var_serialize(&main_metadata_str, metadata, &metadata_hash); PHP_VAR_SERIALIZE_DESTROY(metadata_hash); if (EG(exception)) { /* Serialization can throw. Don't overwrite the original value or original string. */ return FAILURE; } phar_metadata_tracker_free(tracker, persistent); if (EG(exception)) { /* Destructor can throw. */ zend_string_release(main_metadata_str.s); return FAILURE; } if (tracker->str) { zend_throw_exception_ex(phar_ce_PharException, 0, "Metadata unexpectedly changed during setMetadata()"); zend_string_release(main_metadata_str.s); return FAILURE; } ZVAL_COPY(&tracker->val, metadata); tracker->str = main_metadata_str.s; return SUCCESS; } /* {{{ Sets the global metadata of the phar */ PHP_METHOD(Phar, setMetadata) { char *error; zval *metadata; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &metadata) == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); RETURN_THROWS(); } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); RETURN_THROWS(); } ZEND_ASSERT(!phar_obj->archive->is_persistent); /* Should no longer be persistent */ if (serialize_metadata_or_throw(&phar_obj->archive->metadata_tracker, phar_obj->archive->is_persistent, metadata) != SUCCESS) { RETURN_THROWS(); } phar_obj->archive->is_modified = 1; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ Deletes the global metadata of the phar */ PHP_METHOD(Phar, delMetadata) { char *error; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); RETURN_THROWS(); } if (!phar_metadata_tracker_has_data(&phar_obj->archive->metadata_tracker, phar_obj->archive->is_persistent)) { RETURN_TRUE; } phar_metadata_tracker_free(&phar_obj->archive->metadata_tracker, phar_obj->archive->is_persistent); phar_obj->archive->is_modified = 1; phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } else { RETURN_TRUE; } } /* }}} */ static int phar_extract_file(bool overwrite, phar_entry_info *entry, char *dest, size_t dest_len, char **error) /* {{{ */ { php_stream_statbuf ssb; size_t len; php_stream *fp; char *fullpath; const char *slash; mode_t mode; cwd_state new_state; char *filename; size_t filename_len; if (entry->is_mounted) { /* silently ignore mounted entries */ return SUCCESS; } if (entry->filename_len >= sizeof(".phar")-1 && !memcmp(entry->filename, ".phar", sizeof(".phar")-1)) { return SUCCESS; } /* strip .. from path and restrict it to be under dest directory */ new_state.cwd = (char*)emalloc(2); new_state.cwd[0] = DEFAULT_SLASH; new_state.cwd[1] = '\0'; new_state.cwd_length = 1; if (virtual_file_ex(&new_state, entry->filename, NULL, CWD_EXPAND) != 0 || new_state.cwd_length <= 1) { if (EINVAL == errno && entry->filename_len > 50) { char *tmp = estrndup(entry->filename, 50); spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, dest); efree(tmp); } else { spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename); } efree(new_state.cwd); return FAILURE; } filename = new_state.cwd + 1; filename_len = new_state.cwd_length - 1; #ifdef PHP_WIN32 /* unixify the path back, otherwise non zip formats might be broken */ { size_t cnt = 0; do { if ('\\' == filename[cnt]) { filename[cnt] = '/'; } } while (cnt++ < filename_len); } #endif len = spprintf(&fullpath, 0, "%s/%s", dest, filename); if (len >= MAXPATHLEN) { char *tmp; /* truncate for error message */ fullpath[50] = '\0'; if (entry->filename_len > 50) { tmp = estrndup(entry->filename, 50); spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, fullpath); efree(tmp); } else { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s...\", extracted filename is too long for filesystem", entry->filename, fullpath); } efree(fullpath); efree(new_state.cwd); return FAILURE; } if (!len) { spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename); efree(fullpath); efree(new_state.cwd); return FAILURE; } if (php_check_open_basedir(fullpath)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", openbasedir/safe mode restrictions in effect", entry->filename, fullpath); efree(fullpath); efree(new_state.cwd); return FAILURE; } /* let see if the path already exists */ if (!overwrite && SUCCESS == php_stream_stat_path(fullpath, &ssb)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", path already exists", entry->filename, fullpath); efree(fullpath); efree(new_state.cwd); return FAILURE; } /* perform dirname */ slash = zend_memrchr(filename, '/', filename_len); if (slash) { fullpath[dest_len + (slash - filename) + 1] = '\0'; } else { fullpath[dest_len] = '\0'; } if (FAILURE == php_stream_stat_path(fullpath, &ssb)) { if (entry->is_dir) { if (!php_stream_mkdir(fullpath, entry->flags & PHAR_ENT_PERM_MASK, PHP_STREAM_MKDIR_RECURSIVE, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath); efree(fullpath); efree(new_state.cwd); return FAILURE; } } else { if (!php_stream_mkdir(fullpath, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath); efree(fullpath); efree(new_state.cwd); return FAILURE; } } } if (slash) { fullpath[dest_len + (slash - filename) + 1] = '/'; } else { fullpath[dest_len] = '/'; } filename = NULL; efree(new_state.cwd); /* it is a standalone directory, job done */ if (entry->is_dir) { efree(fullpath); return SUCCESS; } fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS, NULL); if (!fp) { spprintf(error, 4096, "Cannot extract \"%s\", could not open for writing \"%s\"", entry->filename, fullpath); efree(fullpath); return FAILURE; } if (!phar_get_efp(entry, 0)) { if (FAILURE == phar_open_entry_fp(entry, error, 1)) { if (error) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer: %s", entry->filename, fullpath, *error); } else { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer", entry->filename, fullpath); } efree(fullpath); php_stream_close(fp); return FAILURE; } } if (FAILURE == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to seek internal file pointer", entry->filename, fullpath); efree(fullpath); php_stream_close(fp); return FAILURE; } if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0), fp, entry->uncompressed_filesize, NULL)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", copying contents failed", entry->filename, fullpath); efree(fullpath); php_stream_close(fp); return FAILURE; } php_stream_close(fp); mode = (mode_t) entry->flags & PHAR_ENT_PERM_MASK; if (FAILURE == VCWD_CHMOD(fullpath, mode)) { spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", setting file permissions failed", entry->filename, fullpath); efree(fullpath); return FAILURE; } efree(fullpath); return SUCCESS; } /* }}} */ static int extract_helper(phar_archive_data *archive, zend_string *search, char *pathto, size_t pathto_len, bool overwrite, char **error) { /* {{{ */ int extracted = 0; phar_entry_info *entry; if (!search) { /* nothing to match -- extract all files */ ZEND_HASH_FOREACH_PTR(&archive->manifest, entry) { if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, error)) return -1; extracted++; } ZEND_HASH_FOREACH_END(); } else if ('/' == ZSTR_VAL(search)[ZSTR_LEN(search) - 1]) { /* ends in "/" -- extract all entries having that prefix */ ZEND_HASH_FOREACH_PTR(&archive->manifest, entry) { if (0 != strncmp(ZSTR_VAL(search), entry->filename, ZSTR_LEN(search))) continue; if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, error)) return -1; extracted++; } ZEND_HASH_FOREACH_END(); } else { /* otherwise, looking for an exact match */ entry = zend_hash_find_ptr(&archive->manifest, search); if (NULL == entry) return 0; if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, error)) return -1; return 1; } return extracted; } /* }}} */ /* {{{ Extract one or more file from a phar archive, optionally overwriting existing files */ PHP_METHOD(Phar, extractTo) { php_stream *fp; php_stream_statbuf ssb; char *pathto; zend_string *filename = NULL; size_t pathto_len; int ret; zval *zval_file; HashTable *files_ht = NULL; bool overwrite = 0; char *error = NULL; ZEND_PARSE_PARAMETERS_START(1, 3) Z_PARAM_PATH(pathto, pathto_len) Z_PARAM_OPTIONAL Z_PARAM_ARRAY_HT_OR_STR_OR_NULL(files_ht, filename) Z_PARAM_BOOL(overwrite) ZEND_PARSE_PARAMETERS_END(); PHAR_ARCHIVE_OBJECT(); fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, NULL); if (!fp) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, %s cannot be found", phar_obj->archive->fname); RETURN_THROWS(); } php_stream_close(fp); if (pathto_len < 1) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, extraction path must be non-zero length"); RETURN_THROWS(); } if (pathto_len >= MAXPATHLEN) { char *tmp = estrndup(pathto, 50); /* truncate for error message */ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp); efree(tmp); RETURN_THROWS(); } if (php_stream_stat_path(pathto, &ssb) < 0) { ret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL); if (!ret) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to create path \"%s\" for extraction", pathto); RETURN_THROWS(); } } else if (!(ssb.sb.st_mode & S_IFDIR)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto); RETURN_THROWS(); } if (files_ht) { if (zend_hash_num_elements(files_ht) == 0) { RETURN_FALSE; } ZEND_HASH_FOREACH_VAL(files_ht, zval_file) { ZVAL_DEREF(zval_file); if (IS_STRING != Z_TYPE_P(zval_file)) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, array of filenames to extract contains non-string value"); RETURN_THROWS(); } switch (extract_helper(phar_obj->archive, Z_STR_P(zval_file), pathto, pathto_len, overwrite, &error)) { case -1: zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error); efree(error); RETURN_THROWS(); case 0: zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: attempted to extract non-existent file or directory \"%s\" from phar \"%s\"", ZSTR_VAL(Z_STR_P(zval_file)), phar_obj->archive->fname); RETURN_THROWS(); } } ZEND_HASH_FOREACH_END(); RETURN_TRUE; } ret = extract_helper(phar_obj->archive, filename, pathto, pathto_len, overwrite, &error); if (-1 == ret) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error); efree(error); } else if (0 == ret && NULL != filename) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: attempted to extract non-existent file or directory \"%s\" from phar \"%s\"", ZSTR_VAL(filename), phar_obj->archive->fname); } else { RETURN_TRUE; } } /* }}} */ /* {{{ Construct a Phar entry object */ PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; size_t arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = ZEND_THIS, arg1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { RETURN_THROWS(); } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); RETURN_THROWS(); } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); RETURN_THROWS(); } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } RETURN_THROWS(); } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); RETURN_THROWS(); } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_known_instance_method_with_1_params(spl_ce_SplFileInfo->constructor, Z_OBJ_P(zobj), NULL, &arg1); zval_ptr_dtor(&arg1); } /* }}} */ #define PHAR_ENTRY_OBJECT() \ zval *zobj = ZEND_THIS; \ phar_entry_object *entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); \ if (!entry_obj->entry) { \ zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Cannot call method on an uninitialized PharFileInfo object"); \ RETURN_THROWS(); \ } /* {{{ clean up directory-based entry objects */ PHP_METHOD(PharFileInfo, __destruct) { zval *zobj = ZEND_THIS; phar_entry_object *entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } if (entry_obj->entry && entry_obj->entry->is_temp_dir) { if (entry_obj->entry->filename) { efree(entry_obj->entry->filename); entry_obj->entry->filename = NULL; } efree(entry_obj->entry); entry_obj->entry = NULL; } } /* }}} */ /* {{{ Returns the compressed size */ PHP_METHOD(PharFileInfo, getCompressedSize) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); RETURN_LONG(entry_obj->entry->compressed_filesize); } /* }}} */ /* {{{ Returns whether the entry is compressed, and whether it is compressed with Phar::GZ or Phar::BZ2 if specified */ PHP_METHOD(PharFileInfo, isCompressed) { zend_long method; bool method_is_null = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &method, &method_is_null) == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); if (method_is_null) { RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK); } switch (method) { case 9021976: /* Retained for BC */ RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK); case PHAR_ENT_COMPRESSED_GZ: RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ); case PHAR_ENT_COMPRESSED_BZ2: RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2); default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Unknown compression type specified"); \ } } /* }}} */ /* {{{ Returns CRC32 code or throws an exception if not CRC checked */ PHP_METHOD(PharFileInfo, getCRC32) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); if (entry_obj->entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Phar entry is a directory, does not have a CRC"); \ RETURN_THROWS(); } if (entry_obj->entry->is_crc_checked) { RETURN_LONG(entry_obj->entry->crc32); } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Phar entry was not CRC checked"); \ } } /* }}} */ /* {{{ Returns whether file entry is CRC checked */ PHP_METHOD(PharFileInfo, isCRCChecked) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); RETURN_BOOL(entry_obj->entry->is_crc_checked); } /* }}} */ /* {{{ Returns the Phar file entry flags */ PHP_METHOD(PharFileInfo, getPharFlags) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); RETURN_LONG(entry_obj->entry->flags & ~(PHAR_ENT_PERM_MASK|PHAR_ENT_COMPRESSION_MASK)); } /* }}} */ /* {{{ set the file permissions for the Phar. This only allows setting execution bit, read/write */ PHP_METHOD(PharFileInfo, chmod) { char *error; zend_long perms; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &perms) == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); if (entry_obj->entry->is_temp_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Phar entry \"%s\" is a temporary directory (not an actual entry in the archive), cannot chmod", entry_obj->entry->filename); \ RETURN_THROWS(); } if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) { zend_throw_exception_ex(phar_ce_PharException, 0, "Cannot modify permissions for file \"%s\" in phar \"%s\", write operations are prohibited", entry_obj->entry->filename, entry_obj->entry->phar->fname); RETURN_THROWS(); } if (entry_obj->entry->is_persistent) { phar_archive_data *phar = entry_obj->entry->phar; if (FAILURE == phar_copy_on_write(&phar)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname); RETURN_THROWS(); } /* re-populate after copy-on-write */ entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len); } /* clear permissions */ entry_obj->entry->flags &= ~PHAR_ENT_PERM_MASK; perms &= 0777; entry_obj->entry->flags |= perms; entry_obj->entry->old_flags = entry_obj->entry->flags; entry_obj->entry->phar->is_modified = 1; entry_obj->entry->is_modified = 1; /* hackish cache in php_stat needs to be cleared */ /* if this code fails to work, check main/streams/streams.c, _php_stream_stat_path */ if (BG(CurrentLStatFile)) { efree(BG(CurrentLStatFile)); } if (BG(CurrentStatFile)) { efree(BG(CurrentStatFile)); } BG(CurrentLStatFile) = NULL; BG(CurrentStatFile) = NULL; phar_flush(entry_obj->entry->phar, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ Returns the metadata of the entry */ PHP_METHOD(PharFileInfo, hasMetadata) { if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); RETURN_BOOL(phar_metadata_tracker_has_data(&entry_obj->entry->metadata_tracker, entry_obj->entry->is_persistent)); } /* }}} */ /* {{{ Returns the metadata of the entry */ PHP_METHOD(PharFileInfo, getMetadata) { HashTable *unserialize_options = NULL; phar_metadata_tracker *tracker; ZEND_PARSE_PARAMETERS_START(0, 1) Z_PARAM_OPTIONAL Z_PARAM_ARRAY_HT(unserialize_options) ZEND_PARSE_PARAMETERS_END(); PHAR_ENTRY_OBJECT(); tracker = &entry_obj->entry->metadata_tracker; if (phar_metadata_tracker_has_data(tracker, entry_obj->entry->is_persistent)) { phar_metadata_tracker_unserialize_or_copy(tracker, return_value, entry_obj->entry->is_persistent, unserialize_options, "PharFileInfo::getMetadata"); } } /* }}} */ /* {{{ Sets the metadata of the entry */ PHP_METHOD(PharFileInfo, setMetadata) { char *error; zval *metadata; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &metadata) == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); RETURN_THROWS(); } if (entry_obj->entry->is_temp_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Phar entry is a temporary directory (not an actual entry in the archive), cannot set metadata"); \ RETURN_THROWS(); } if (entry_obj->entry->is_persistent) { phar_archive_data *phar = entry_obj->entry->phar; if (FAILURE == phar_copy_on_write(&phar)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname); RETURN_THROWS(); } /* re-populate after copy-on-write */ entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len); ZEND_ASSERT(!entry_obj->entry->is_persistent); /* Should no longer be persistent */ } if (serialize_metadata_or_throw(&entry_obj->entry->metadata_tracker, entry_obj->entry->is_persistent, metadata) != SUCCESS) { RETURN_THROWS(); } entry_obj->entry->is_modified = 1; entry_obj->entry->phar->is_modified = 1; phar_flush(entry_obj->entry->phar, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ Deletes the metadata of the entry */ PHP_METHOD(PharFileInfo, delMetadata) { char *error; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); RETURN_THROWS(); } if (entry_obj->entry->is_temp_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Phar entry is a temporary directory (not an actual entry in the archive), cannot delete metadata"); \ RETURN_THROWS(); } if (phar_metadata_tracker_has_data(&entry_obj->entry->metadata_tracker, entry_obj->entry->is_persistent)) { if (entry_obj->entry->is_persistent) { phar_archive_data *phar = entry_obj->entry->phar; if (FAILURE == phar_copy_on_write(&phar)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname); RETURN_THROWS(); } /* re-populate after copy-on-write */ entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len); } /* multiple values may reference the metadata */ phar_metadata_tracker_free(&entry_obj->entry->metadata_tracker, entry_obj->entry->is_persistent); entry_obj->entry->is_modified = 1; entry_obj->entry->phar->is_modified = 1; phar_flush(entry_obj->entry->phar, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } else { RETURN_TRUE; } } else { RETURN_TRUE; } } /* }}} */ /* {{{ return the complete file contents of the entry (like file_get_contents) */ PHP_METHOD(PharFileInfo, getContent) { char *error; php_stream *fp; phar_entry_info *link; zend_string *str; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); if (entry_obj->entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar error: Cannot retrieve contents, \"%s\" in phar \"%s\" is a directory", entry_obj->entry->filename, entry_obj->entry->phar->fname); RETURN_THROWS(); } link = phar_get_link_source(entry_obj->entry); if (!link) { link = entry_obj->entry; } if (SUCCESS != phar_open_entry_fp(link, &error, 0)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar error: Cannot retrieve contents, \"%s\" in phar \"%s\": %s", entry_obj->entry->filename, entry_obj->entry->phar->fname, error); efree(error); RETURN_THROWS(); } if (!(fp = phar_get_efp(link, 0))) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar error: Cannot retrieve contents of \"%s\" in phar \"%s\"", entry_obj->entry->filename, entry_obj->entry->phar->fname); RETURN_THROWS(); } phar_seek_efp(link, 0, SEEK_SET, 0, 0); str = php_stream_copy_to_mem(fp, link->uncompressed_filesize, 0); if (str) { RETURN_STR(str); } else { RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ Instructs the Phar class to compress the current file using zlib or bzip2 compression */ PHP_METHOD(PharFileInfo, compress) { zend_long method; char *error; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &method) == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); if (entry_obj->entry->is_tar) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress with Gzip compression, not possible with tar-based phar archives"); RETURN_THROWS(); } if (entry_obj->entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Phar entry is a directory, cannot set compression"); \ RETURN_THROWS(); } if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Phar is readonly, cannot change compression"); RETURN_THROWS(); } if (entry_obj->entry->is_deleted) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress deleted file"); RETURN_THROWS(); } if (entry_obj->entry->is_persistent) { phar_archive_data *phar = entry_obj->entry->phar; if (FAILURE == phar_copy_on_write(&phar)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname); RETURN_THROWS(); } /* re-populate after copy-on-write */ entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len); } switch (method) { case PHAR_ENT_COMPRESSED_GZ: if (entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ) { RETURN_TRUE; } if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0) { if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress with gzip compression, file is already compressed with bzip2 compression and bz2 extension is not enabled, cannot decompress"); RETURN_THROWS(); } /* decompress this file indirectly */ if (SUCCESS != phar_open_entry_fp(entry_obj->entry, &error, 1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar error: Cannot decompress bzip2-compressed file \"%s\" in phar \"%s\" in order to compress with gzip: %s", entry_obj->entry->filename, entry_obj->entry->phar->fname, error); efree(error); RETURN_THROWS(); } } if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress with gzip compression, zlib extension is not enabled"); RETURN_THROWS(); } entry_obj->entry->old_flags = entry_obj->entry->flags; entry_obj->entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry_obj->entry->flags |= PHAR_ENT_COMPRESSED_GZ; break; case PHAR_ENT_COMPRESSED_BZ2: if (entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2) { RETURN_TRUE; } if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0) { if (!PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress with bzip2 compression, file is already compressed with gzip compression and zlib extension is not enabled, cannot decompress"); RETURN_THROWS(); } /* decompress this file indirectly */ if (SUCCESS != phar_open_entry_fp(entry_obj->entry, &error, 1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar error: Cannot decompress gzip-compressed file \"%s\" in phar \"%s\" in order to compress with bzip2: %s", entry_obj->entry->filename, entry_obj->entry->phar->fname, error); efree(error); RETURN_THROWS(); } } if (!PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress with bzip2 compression, bz2 extension is not enabled"); RETURN_THROWS(); } entry_obj->entry->old_flags = entry_obj->entry->flags; entry_obj->entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry_obj->entry->flags |= PHAR_ENT_COMPRESSED_BZ2; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Unknown compression type specified"); \ } entry_obj->entry->phar->is_modified = 1; entry_obj->entry->is_modified = 1; phar_flush(entry_obj->entry->phar, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } RETURN_TRUE; } /* }}} */ /* {{{ Instructs the Phar class to decompress the current file */ PHP_METHOD(PharFileInfo, decompress) { char *error; char *compression_type; if (zend_parse_parameters_none() == FAILURE) { RETURN_THROWS(); } PHAR_ENTRY_OBJECT(); if (entry_obj->entry->is_dir) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \ "Phar entry is a directory, cannot set compression"); \ RETURN_THROWS(); } if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK) == 0) { RETURN_TRUE; } if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Phar is readonly, cannot decompress"); RETURN_THROWS(); } if (entry_obj->entry->is_deleted) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot compress deleted file"); RETURN_THROWS(); } if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0 && !PHAR_G(has_zlib)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot decompress Gzip-compressed file, zlib extension is not enabled"); RETURN_THROWS(); } if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0 && !PHAR_G(has_bz2)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot decompress Bzip2-compressed file, bz2 extension is not enabled"); RETURN_THROWS(); } if (entry_obj->entry->is_persistent) { phar_archive_data *phar = entry_obj->entry->phar; if (FAILURE == phar_copy_on_write(&phar)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname); RETURN_THROWS(); } /* re-populate after copy-on-write */ entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len); } switch (entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK) { case PHAR_ENT_COMPRESSED_GZ: compression_type = "gzip"; break; case PHAR_ENT_COMPRESSED_BZ2: compression_type = "bz2"; break; default: zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot decompress file compressed with unknown compression type"); RETURN_THROWS(); } /* decompress this file indirectly */ if (SUCCESS != phar_open_entry_fp(entry_obj->entry, &error, 1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Phar error: Cannot decompress %s-compressed file \"%s\" in phar \"%s\": %s", compression_type, entry_obj->entry->filename, entry_obj->entry->phar->fname, error); efree(error); return; } entry_obj->entry->old_flags = entry_obj->entry->flags; entry_obj->entry->flags &= ~PHAR_ENT_COMPRESSION_MASK; entry_obj->entry->phar->is_modified = 1; entry_obj->entry->is_modified = 1; phar_flush(entry_obj->entry->phar, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); RETURN_THROWS(); } RETURN_TRUE; } /* }}} */ /* {{{ phar methods */ #define REGISTER_PHAR_CLASS_CONST_LONG(class_name, const_name, value) \ zend_declare_class_constant_long(class_name, const_name, sizeof(const_name)-1, (zend_long)value); void phar_object_init(void) /* {{{ */ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "PharException", class_PharException_methods); phar_ce_PharException = zend_register_internal_class_ex(&ce, zend_ce_exception); INIT_CLASS_ENTRY(ce, "Phar", class_Phar_methods); phar_ce_archive = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator); zend_class_implements(phar_ce_archive, 2, zend_ce_countable, zend_ce_arrayaccess); INIT_CLASS_ENTRY(ce, "PharData", class_PharData_methods); phar_ce_data = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator); zend_class_implements(phar_ce_data, 2, zend_ce_countable, zend_ce_arrayaccess); INIT_CLASS_ENTRY(ce, "PharFileInfo", class_PharFileInfo_methods); phar_ce_entry = zend_register_internal_class_ex(&ce, spl_ce_SplFileInfo); REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "BZ2", PHAR_ENT_COMPRESSED_BZ2) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "GZ", PHAR_ENT_COMPRESSED_GZ) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "NONE", PHAR_ENT_COMPRESSED_NONE) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHAR", PHAR_FORMAT_PHAR) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "TAR", PHAR_FORMAT_TAR) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "ZIP", PHAR_FORMAT_ZIP) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "COMPRESSED", PHAR_ENT_COMPRESSION_MASK) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHP", PHAR_MIME_PHP) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHPS", PHAR_MIME_PHPS) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "MD5", PHAR_SIG_MD5) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "OPENSSL", PHAR_SIG_OPENSSL) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA1", PHAR_SIG_SHA1) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA256", PHAR_SIG_SHA256) REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA512", PHAR_SIG_SHA512) } /* }}} */
29.498728
226
0.692209
[ "object" ]
7fa2caceee74a7300f44742db3e57d011fef984f
12,307
h
C
include/CodeFormatServer/VSCode.h
CppCXY/EmmyLuaCodeStyle
ffd2205f59893e12ad07dc151edce26d1c599065
[ "MIT" ]
20
2021-11-01T10:22:12.000Z
2022-03-23T13:57:36.000Z
include/CodeFormatServer/VSCode.h
CppCXY/EmmyLuaCodeStyle
ffd2205f59893e12ad07dc151edce26d1c599065
[ "MIT" ]
30
2022-01-28T06:03:31.000Z
2022-03-26T04:33:44.000Z
include/CodeFormatServer/VSCode.h
CppCXY/EmmyLuaCodeStyle
ffd2205f59893e12ad07dc151edce26d1c599065
[ "MIT" ]
4
2021-11-01T10:22:16.000Z
2022-03-31T15:50:53.000Z
#pragma once #include <cstdint> #include <string> #include <vector> #include <type_traits> #include <nlohmann/json.hpp> #include <compare> #include <optional> // 命名风格和vscode一样 namespace vscode { class Serializable { public: virtual ~Serializable(); virtual nlohmann::json Serialize() { return nlohmann::json::object(); } virtual void Deserialize(nlohmann::json json) { }; template <class T> nlohmann::json SerializeArray(std::vector<T>& vec) { nlohmann::json array = nlohmann::json::array(); for (auto& v : vec) { if constexpr (std::is_base_of_v<Serializable, T>) { array.push_back(v.Serialize()); } else { array.push_back(v); } } return array; } }; class Position : public Serializable { public: Position(uint64_t _line = 0, uint64_t _character = 0); uint64_t line; uint64_t character; nlohmann::json Serialize() override; void Deserialize(nlohmann::json json) override; bool operator==(const Position& p) const { return line == p.line && character == p.character; } bool operator<(const Position& p) const { if (line != p.line) { return line < p.line; } else { return character < p.character; } } bool operator<=(const Position& p) const { return *this == p || *this < p; } bool operator>=(const Position& p) const { return *this == p || !(*this < p); } }; class Range : public Serializable { public: Range(Position _start = Position(0, 0), Position _end = Position(0, 0)); Position start; Position end; nlohmann::json Serialize() override; void Deserialize(nlohmann::json json) override; bool operator==(const Range& range) const { return start == range.start && end == range.end; } bool operator<(const Range& rhs) const { if (start != rhs.start) { return start < rhs.start; } else { return end < rhs.end; } } }; class Location : public Serializable { public: std::string uri; Range range; nlohmann::json Serialize() override; void Deserialize(nlohmann::json json) override; }; enum class DiagnosticSeverity { Error = 1, Warning = 2, Information = 3, Hint = 4 }; class Diagnostic : public Serializable { public: Diagnostic(); Range range; DiagnosticSeverity severity; std::string message; std::string code; std::string data; nlohmann::json Serialize() override; void Deserialize(nlohmann::json json) override; }; class TextDocument : public Serializable { public: std::string uri; nlohmann::json Serialize() override; void Deserialize(nlohmann::json json) override; }; class TextEdit : public Serializable { public: Range range; std::string newText; nlohmann::json Serialize() override; }; class PublishDiagnosticsParams : public Serializable { public: std::string uri; std::vector<Diagnostic> diagnostics; nlohmann::json Serialize() override; void Deserialize(nlohmann::json json) override; }; enum class TextDocumentSyncKind { None = 0, Full = 1, Incremental = 2 }; class TextDocumentSyncOptions : public Serializable { public: bool openClose = false; TextDocumentSyncKind change = TextDocumentSyncKind::None; bool willSave = false; bool willSaveWaitUntil = false; nlohmann::json Serialize() override; }; class DocumentOnTypeFormattingOptions : public Serializable { public: std::string firstTriggerCharacter; std::vector<std::string> moreTriggerCharacter; nlohmann::json Serialize() override; }; class ExecuteCommandOptions : public Serializable { public: std::vector<std::string> commands; nlohmann::json Serialize() override; }; class CompletionItemOptions : public Serializable { public: bool labelDetailsSupport = true; nlohmann::json Serialize() override; }; class CompletionOptions : public Serializable { public: bool supportCompletion = false; std::vector<std::string> triggerCharacters; bool resolveProvider; CompletionItemOptions completionItem; nlohmann::json Serialize() override; }; class DiagnosticOptions : public Serializable { public: std::string identifier; bool workspaceDiagnostics = false; bool interFileDependencies = false; nlohmann::json Serialize() override; }; class ServerCapabilities : public Serializable { public: TextDocumentSyncOptions textDocumentSync; bool documentFormattingProvider = false; bool documentRangeFormattingProvider = false; DocumentOnTypeFormattingOptions documentOnTypeFormattingProvider; bool codeActionProvider = false; ExecuteCommandOptions executeCommandProvider; CompletionOptions completionProvider; DiagnosticOptions diagnosticProvider; nlohmann::json Serialize() override; }; class ConfigSource; class VscodeSettings : public Serializable { public: bool lintCodeStyle = true; bool lintModule = true; // bool autoImport = true; bool spellEnable; std::vector<std::string> spellDict; void Deserialize(nlohmann::json json) override; }; class InitializationOptions : public Serializable { public: std::vector<std::string> workspaceFolders; std::vector<ConfigSource> editorConfigFiles; std::vector<ConfigSource> moduleConfigFiles; std::string localeRoot; std::string extensionChars; std::vector<std::string> dictionaryPath; VscodeSettings vscodeConfig; void Deserialize(nlohmann::json json) override; }; class InitializeParams : public Serializable { public: std::string rootUri; std::string rootPath; std::string locale; InitializationOptions initializationOptions; // 其他参数忽略 void Deserialize(nlohmann::json json) override; }; class InitializeResult : public Serializable { public: ServerCapabilities capabilities; nlohmann::json Serialize() override; void Deserialize(nlohmann::json json) override; }; class TextDocumentContentChangeEvent : public Serializable { public: std::optional<Range> range; std::string text; void Deserialize(nlohmann::json json) override; }; class DidChangeTextDocumentParams : public Serializable { public: TextDocument textDocument; std::vector<TextDocumentContentChangeEvent> contentChanges; void Deserialize(nlohmann::json json) override; }; class TextDocumentItem : public Serializable { public: std::string uri; std::string languageId; // int version; std::string text; void Deserialize(nlohmann::json json) override; }; class DidOpenTextDocumentParams : public Serializable { public: TextDocumentItem textDocument; void Deserialize(nlohmann::json json) override; }; class DocumentFormattingParams : public Serializable { public: TextDocument textDocument; void Deserialize(nlohmann::json json) override; }; // 该类并非language server protocol 接口 class DocumentFormattingResult : public Serializable { public: std::vector<TextEdit> edits; bool hasError = false; nlohmann::json Serialize() override; }; class DidCloseTextDocumentParams : public Serializable { public: TextDocument textDocument; void Deserialize(nlohmann::json json) override; }; enum class FileChangeType { Created = 1, Changed = 2, Delete = 3 }; class ConfigSource : public Serializable { public: std::string uri; std::string path; std::string workspace; void Deserialize(nlohmann::json json) override; }; class ConfigUpdateParams : public Serializable { public: FileChangeType type; ConfigSource source; void Deserialize(nlohmann::json json) override; }; class DocumentRangeFormattingParams : public Serializable { public: TextDocument textDocument; Range range; void Deserialize(nlohmann::json json) override; }; class TextDocumentPositionParams : public Serializable { public: TextDocument textDocument; Position position; void Deserialize(nlohmann::json json) override; }; class CodeActionContext : public Serializable { public: std::vector<Diagnostic> diagnostics; void Deserialize(nlohmann::json json) override; }; class CodeActionParams : public Serializable { public: TextDocument textDocument; Range range; CodeActionContext context; void Deserialize(nlohmann::json json) override; }; class Command : public Serializable { public: std::string title; std::string command; std::vector<nlohmann::json> arguments; nlohmann::json Serialize() override; }; class CodeActionKind { public: inline static std::string Empty = ""; inline static std::string QuickFix = "quickfix"; inline static std::string Refactor = "refactor"; }; class CodeAction : public Serializable { public: std::string title; Command command; std::string kind; nlohmann::json Serialize() override; }; class CodeActionResult : public Serializable { public: std::vector<CodeAction> actions; nlohmann::json Serialize() override; }; class ExecuteCommandParams : public Serializable { public: std::string command; std::vector<nlohmann::json> arguments; void Deserialize(nlohmann::json json) override; }; class OptionalVersionedTextDocumentIdentifier : public TextDocument { public: std::optional<int> version; nlohmann::json Serialize() override; }; class TextDocumentEdit : public Serializable { public: OptionalVersionedTextDocumentIdentifier textDocument; std::vector<TextEdit> edits; nlohmann::json Serialize() override; }; class WorkspaceEdit : public Serializable { public: // std::vector<TextDocumentEdit> documentChanges; std::map<std::string, std::vector<TextEdit>> changes; nlohmann::json Serialize() override; }; class ApplyWorkspaceEditParams : public Serializable { public: std::optional<std::string> label; WorkspaceEdit edit; nlohmann::json Serialize() override; }; class FileEvent : public Serializable { public: std::string uri; FileChangeType type; void Deserialize(nlohmann::json json) override; }; class DidChangeWatchedFilesParams : public Serializable { public: std::vector<FileEvent> changes; void Deserialize(nlohmann::json json) override; }; class CompletionParams : public Serializable { public: TextDocument textDocument; Position position; void Deserialize(nlohmann::json json) override; }; enum class CompletionItemKind { Text = 1, Method = 2, Function = 3, Constructor = 4, Field = 5, Variable = 6, Class = 7, Interface = 8, Module = 9, Property = 10, Unit = 11, Value = 12, Enum = 13, Keyword = 14, Snippet = 15, Color = 16, File = 17, Reference = 18, Folder = 19, EnumMember = 20, Constant = 21, Struct = 22, Event = 23, Operator = 24, TypeParameter = 25 }; class CompletionItemLabelDetails : public Serializable { public: std::string detail; std::optional<std::string> description; nlohmann::json Serialize() override; }; class CompletionItem : public Serializable { public: std::string label; CompletionItemKind kind; std::string detail; std::string documentation; std::string insertText; std::optional<CompletionItemLabelDetails> labelDetails; std::optional<std::string> sortText; std::optional<std::string> filterText; std::optional<Command> command; nlohmann::json Serialize() override; }; class CompletionList : public Serializable { public: bool isIncomplete; std::vector<CompletionItem> items; nlohmann::json Serialize() override; }; class DidChangeConfigurationParams : public Serializable { public: nlohmann::json settings; void Deserialize(nlohmann::json json) override; }; class DocumentDiagnosticParams : public Serializable { public: TextDocument textDocument; std::string identifier; std::string previousResultId; void Deserialize(nlohmann::json json) override; }; namespace DocumentDiagnosticReportKind { static constexpr std::string_view Full = "full"; static constexpr std::string_view Unchanged = "unchanged"; }; class DocumentDiagnosticReport : public Serializable { public: std::string kind; std::string resultId; std::vector<Diagnostic> items; nlohmann::json Serialize() override; }; class PreviousResultId : public Serializable { public: std::string uri; std::string value; void Deserialize(nlohmann::json json) override; }; class WorkspaceDiagnosticParams : public Serializable { public: std::string identifier; std::vector<PreviousResultId> previousResultIds; void Deserialize(nlohmann::json json) override; }; class WorkspaceDocumentDiagnosticReport : public DocumentDiagnosticReport { public: std::string uri; std::optional<int64_t> version; nlohmann::json Serialize() override; }; class WorkspaceDiagnosticReport : public Serializable { public: std::vector<WorkspaceDocumentDiagnosticReport> items; nlohmann::json Serialize() override; }; }
18.071953
73
0.749736
[ "object", "vector" ]
7fa5b6263bf774a9906928419964aab8fbdaacf4
974
h
C
src/utils/aggregation/FileSystemAggregator.h
akougkas/iris
ae8b077afa6cec7ce3ea845dc7caad9b5e105c9d
[ "Apache-2.0" ]
1
2019-04-06T08:43:15.000Z
2019-04-06T08:43:15.000Z
src/utils/aggregation/FileSystemAggregator.h
akougkas/iris
ae8b077afa6cec7ce3ea845dc7caad9b5e105c9d
[ "Apache-2.0" ]
1
2019-04-15T09:49:13.000Z
2019-04-15T09:49:13.000Z
src/utils/aggregation/FileSystemAggregator.h
akougkas/iris
ae8b077afa6cec7ce3ea845dc7caad9b5e105c9d
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * File FileSystemAggregator.h * * Goal: * * Created: December 10th, 2016 - Anthony Kougkas * Updated: * Illinois Institute of Technology - SCS Lab * (C) 2016 ******************************************************************************/ #ifndef IRIS_FILESYSTEMAGGREGATOR_H #define IRIS_FILESYSTEMAGGREGATOR_H /****************************************************************************** *include files ******************************************************************************/ #include <map> #include <vector> #include "../../config/constants.h" #include "AbstractAggregator.h" #include "../../config/Components.h" /****************************************************************************** *Class ******************************************************************************/ class FileSystemAggregator: public AbstractAggregator{ }; #endif //IRIS_FILESYSTEMAGGREGATOR_H
29.515152
80
0.382957
[ "vector" ]
7fa90bf74a560f1d45a706fddac01321aa5dc33c
23,145
c
C
release/src-rt-6.x.4708/linux/linux-2.6.36/arch/arm/kernel/setup.c
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
4
2017-05-17T11:27:04.000Z
2020-05-24T07:23:26.000Z
release/src-rt-6.x.4708/linux/linux-2.6.36/arch/arm/kernel/setup.c
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
1
2018-08-21T03:44:27.000Z
2018-08-21T03:44:27.000Z
release/src-rt-6.x.4708/linux/linux-2.6.36/arch/arm/kernel/setup.c
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
5
2017-10-11T08:09:11.000Z
2020-10-14T04:10:13.000Z
/* * linux/arch/arm/kernel/setup.c * * Copyright (C) 1995-2001 Russell King * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/stddef.h> #include <linux/ioport.h> #include <linux/delay.h> #include <linux/utsname.h> #include <linux/initrd.h> #include <linux/console.h> #include <linux/bootmem.h> #include <linux/seq_file.h> #include <linux/screen_info.h> #include <linux/init.h> #include <linux/kexec.h> #include <linux/crash_dump.h> #include <linux/root_dev.h> #include <linux/cpu.h> #include <linux/interrupt.h> #include <linux/smp.h> #include <linux/fs.h> #include <linux/proc_fs.h> #include <linux/memblock.h> #include <asm/unified.h> #include <asm/cpu.h> #include <asm/cputype.h> #include <asm/elf.h> #include <asm/procinfo.h> #include <asm/sections.h> #include <asm/setup.h> #include <asm/mach-types.h> #include <asm/cacheflush.h> #include <asm/cachetype.h> #include <asm/tlbflush.h> #include <asm/mach/arch.h> #include <asm/mach/irq.h> #include <asm/mach/time.h> #include <asm/traps.h> #include <asm/unwind.h> #if defined(CONFIG_DEPRECATED_PARAM_STRUCT) #include "compat.h" #endif #include "atags.h" #include "tcm.h" #ifndef MEM_SIZE #define MEM_SIZE (16*1024*1024) #endif #if defined(CONFIG_FPE_NWFPE) || defined(CONFIG_FPE_FASTFPE) char fpe_type[8]; static int __init fpe_setup(char *line) { memcpy(fpe_type, line, 8); return 1; } __setup("fpe=", fpe_setup); #endif extern void paging_init(struct machine_desc *desc); extern void reboot_setup(char *str); unsigned int processor_id; EXPORT_SYMBOL(processor_id); unsigned int __machine_arch_type; EXPORT_SYMBOL(__machine_arch_type); unsigned int cacheid; EXPORT_SYMBOL(cacheid); unsigned int __atags_pointer __initdata; unsigned int system_rev; EXPORT_SYMBOL(system_rev); unsigned int system_serial_low; EXPORT_SYMBOL(system_serial_low); unsigned int system_serial_high; EXPORT_SYMBOL(system_serial_high); unsigned int elf_hwcap; EXPORT_SYMBOL(elf_hwcap); #ifdef MULTI_CPU struct processor processor; #endif #ifdef MULTI_TLB struct cpu_tlb_fns cpu_tlb; #endif #ifdef MULTI_USER struct cpu_user_fns cpu_user; #endif #ifdef MULTI_CACHE struct cpu_cache_fns cpu_cache; #endif #ifdef CONFIG_OUTER_CACHE struct outer_cache_fns outer_cache; EXPORT_SYMBOL(outer_cache); #endif struct stack { u32 irq[3]; u32 abt[3]; u32 und[3]; } ____cacheline_aligned; static struct stack stacks[NR_CPUS]; char elf_platform[ELF_PLATFORM_SIZE]; EXPORT_SYMBOL(elf_platform); static const char *cpu_name; static const char *machine_name; static char __initdata cmd_line[COMMAND_LINE_SIZE]; static char default_command_line[COMMAND_LINE_SIZE] __initdata = CONFIG_CMDLINE; static union { char c[4]; unsigned long l; } endian_test __initdata = { { 'l', '?', '?', 'b' } }; #define ENDIANNESS ((char)endian_test.l) DEFINE_PER_CPU(struct cpuinfo_arm, cpu_data); /* * Standard memory resources */ static struct resource mem_res[] = { { .name = "Video RAM", .start = 0, .end = 0, .flags = IORESOURCE_MEM }, { .name = "Kernel text", .start = 0, .end = 0, .flags = IORESOURCE_MEM }, { .name = "Kernel data", .start = 0, .end = 0, .flags = IORESOURCE_MEM } }; #define video_ram mem_res[0] #define kernel_code mem_res[1] #define kernel_data mem_res[2] static struct resource io_res[] = { { .name = "reserved", .start = 0x3bc, .end = 0x3be, .flags = IORESOURCE_IO | IORESOURCE_BUSY }, { .name = "reserved", .start = 0x378, .end = 0x37f, .flags = IORESOURCE_IO | IORESOURCE_BUSY }, { .name = "reserved", .start = 0x278, .end = 0x27f, .flags = IORESOURCE_IO | IORESOURCE_BUSY } }; #define lp0 io_res[0] #define lp1 io_res[1] #define lp2 io_res[2] static const char *proc_arch[] = { "undefined/unknown", "3", "4", "4T", "5", "5T", "5TE", "5TEJ", "6TEJ", "7", "?(11)", "?(12)", "?(13)", "?(14)", "?(15)", "?(16)", "?(17)", }; int cpu_architecture(void) { int cpu_arch; if ((read_cpuid_id() & 0x0008f000) == 0) { cpu_arch = CPU_ARCH_UNKNOWN; } else if ((read_cpuid_id() & 0x0008f000) == 0x00007000) { cpu_arch = (read_cpuid_id() & (1 << 23)) ? CPU_ARCH_ARMv4T : CPU_ARCH_ARMv3; } else if ((read_cpuid_id() & 0x00080000) == 0x00000000) { cpu_arch = (read_cpuid_id() >> 16) & 7; if (cpu_arch) cpu_arch += CPU_ARCH_ARMv3; } else if ((read_cpuid_id() & 0x000f0000) == 0x000f0000) { unsigned int mmfr0; /* Revised CPUID format. Read the Memory Model Feature * Register 0 and check for VMSAv7 or PMSAv7 */ asm("mrc p15, 0, %0, c0, c1, 4" : "=r" (mmfr0)); if ((mmfr0 & 0x0000000f) == 0x00000003 || (mmfr0 & 0x000000f0) == 0x00000030) cpu_arch = CPU_ARCH_ARMv7; else if ((mmfr0 & 0x0000000f) == 0x00000002 || (mmfr0 & 0x000000f0) == 0x00000020) cpu_arch = CPU_ARCH_ARMv6; else cpu_arch = CPU_ARCH_UNKNOWN; } else cpu_arch = CPU_ARCH_UNKNOWN; return cpu_arch; } static void __init cacheid_init(void) { unsigned int cachetype = read_cpuid_cachetype(); unsigned int arch = cpu_architecture(); if (arch >= CPU_ARCH_ARMv6) { if ((cachetype & (7 << 29)) == 4 << 29) { /* ARMv7 register format */ cacheid = CACHEID_VIPT_NONALIASING; if ((cachetype & (3 << 14)) == 1 << 14) cacheid |= CACHEID_ASID_TAGGED; } else if (cachetype & (1 << 23)) cacheid = CACHEID_VIPT_ALIASING; else cacheid = CACHEID_VIPT_NONALIASING; } else { cacheid = CACHEID_VIVT; } printk("CPU: %s data cache, %s instruction cache\n", cache_is_vivt() ? "VIVT" : cache_is_vipt_aliasing() ? "VIPT aliasing" : cache_is_vipt_nonaliasing() ? "VIPT nonaliasing" : "unknown", cache_is_vivt() ? "VIVT" : icache_is_vivt_asid_tagged() ? "VIVT ASID tagged" : cache_is_vipt_aliasing() ? "VIPT aliasing" : cache_is_vipt_nonaliasing() ? "VIPT nonaliasing" : "unknown"); } /* * These functions re-use the assembly code in head.S, which * already provide the required functionality. */ extern struct proc_info_list *lookup_processor_type(unsigned int); extern struct machine_desc *lookup_machine_type(unsigned int); static void __init feat_v6_fixup(void) { int id = read_cpuid_id(); if ((id & 0xff0f0000) != 0x41070000) return; /* * HWCAP_TLS is available only on 1136 r1p0 and later, * see also kuser_get_tls_init. */ if ((((id >> 4) & 0xfff) == 0xb36) && (((id >> 20) & 3) == 0)) elf_hwcap &= ~HWCAP_TLS; } static void __init setup_processor(void) { struct proc_info_list *list; /* * locate processor in the list of supported processor * types. The linker builds this table for us from the * entries in arch/arm/mm/proc-*.S */ list = lookup_processor_type(read_cpuid_id()); if (!list) { printk("CPU configuration botched (ID %08x), unable " "to continue.\n", read_cpuid_id()); while (1); } cpu_name = list->cpu_name; #ifdef MULTI_CPU processor = *list->proc; #endif #ifdef MULTI_TLB cpu_tlb = *list->tlb; #endif #ifdef MULTI_USER cpu_user = *list->user; #endif #ifdef MULTI_CACHE cpu_cache = *list->cache; #endif printk("CPU: %s [%08x] revision %d (ARMv%s), cr=%08lx\n", cpu_name, read_cpuid_id(), read_cpuid_id() & 15, proc_arch[cpu_architecture()], cr_alignment); sprintf(init_utsname()->machine, "%s%c", list->arch_name, ENDIANNESS); sprintf(elf_platform, "%s%c", list->elf_name, ENDIANNESS); elf_hwcap = list->elf_hwcap; #ifndef CONFIG_ARM_THUMB elf_hwcap &= ~HWCAP_THUMB; #endif feat_v6_fixup(); cacheid_init(); cpu_proc_init(); } /* * cpu_init - initialise one CPU. * * cpu_init sets up the per-CPU stacks. */ void cpu_init(void) { unsigned int cpu = smp_processor_id(); struct stack *stk = &stacks[cpu]; if (cpu >= NR_CPUS) { printk(KERN_CRIT "CPU%u: bad primary CPU number\n", cpu); BUG(); } /* * Define the placement constraint for the inline asm directive below. * In Thumb-2, msr with an immediate value is not allowed. */ #ifdef CONFIG_THUMB2_KERNEL #define PLC "r" #else #define PLC "I" #endif /* * setup stacks for re-entrant exception handlers */ __asm__ ( "msr cpsr_c, %1\n\t" "add r14, %0, %2\n\t" "mov sp, r14\n\t" "msr cpsr_c, %3\n\t" "add r14, %0, %4\n\t" "mov sp, r14\n\t" "msr cpsr_c, %5\n\t" "add r14, %0, %6\n\t" "mov sp, r14\n\t" "msr cpsr_c, %7" : : "r" (stk), PLC (PSR_F_BIT | PSR_I_BIT | IRQ_MODE), "I" (offsetof(struct stack, irq[0])), PLC (PSR_F_BIT | PSR_I_BIT | ABT_MODE), "I" (offsetof(struct stack, abt[0])), PLC (PSR_F_BIT | PSR_I_BIT | UND_MODE), "I" (offsetof(struct stack, und[0])), PLC (PSR_F_BIT | PSR_I_BIT | SVC_MODE) : "r14"); } static struct machine_desc * __init setup_machine(unsigned int nr) { struct machine_desc *list; /* * locate machine in the list of supported machines. */ list = lookup_machine_type(nr); if (!list) { printk("Machine configuration botched (nr %d), unable " "to continue.\n", nr); while (1); } printk("Machine: %s\n", list->name); return list; } static int __init arm_add_memory(unsigned long start, unsigned long size) { struct membank *bank = &meminfo.bank[meminfo.nr_banks]; if (meminfo.nr_banks >= NR_BANKS) { printk(KERN_CRIT "NR_BANKS too low, " "ignoring memory at %#lx\n", start); return -EINVAL; } /* * Ensure that start/size are aligned to a page boundary. * Size is appropriately rounded down, start is rounded up. */ size -= start & ~PAGE_MASK; bank->start = PAGE_ALIGN(start); bank->size = size & PAGE_MASK; /* * Check whether this memory region has non-zero size or * invalid node number. */ if (bank->size == 0) return -EINVAL; meminfo.nr_banks++; return 0; } /* * Pick out the memory size. We look for mem=size@start, * where start and size are "size[KkMm]" */ static int __init early_mem(char *p) { static int usermem __initdata = 0; unsigned long size, start; char *endp; /* * If the user specifies memory size, we * blow away any automatically generated * size. */ if (usermem == 0) { usermem = 1; meminfo.nr_banks = 0; } start = PHYS_OFFSET; size = memparse(p, &endp); if (*endp == '@') start = memparse(endp + 1, NULL); arm_add_memory(start, size); return 0; } early_param("mem", early_mem); static void __init setup_ramdisk(int doload, int prompt, int image_start, unsigned int rd_sz) { #ifdef CONFIG_BLK_DEV_RAM extern int rd_size, rd_image_start, rd_prompt, rd_doload; rd_image_start = image_start; rd_prompt = prompt; rd_doload = doload; if (rd_sz) rd_size = rd_sz; #endif } static void __init request_standard_resources(struct meminfo *mi, struct machine_desc *mdesc) { struct resource *res; int i; kernel_code.start = virt_to_phys(_text); kernel_code.end = virt_to_phys(_etext - 1); kernel_data.start = virt_to_phys(_data); kernel_data.end = virt_to_phys(_end - 1); for (i = 0; i < mi->nr_banks; i++) { if (mi->bank[i].size == 0) continue; res = alloc_bootmem_low(sizeof(*res)); res->name = "System RAM"; res->start = mi->bank[i].start; res->end = mi->bank[i].start + mi->bank[i].size - 1; res->flags = IORESOURCE_MEM | IORESOURCE_BUSY; request_resource(&iomem_resource, res); if (kernel_code.start >= res->start && kernel_code.end <= res->end) request_resource(res, &kernel_code); if (kernel_data.start >= res->start && kernel_data.end <= res->end) request_resource(res, &kernel_data); } if (mdesc->video_start) { video_ram.start = mdesc->video_start; video_ram.end = mdesc->video_end; request_resource(&iomem_resource, &video_ram); } /* * Some machines don't have the possibility of ever * possessing lp0, lp1 or lp2 */ if (mdesc->reserve_lp0) request_resource(&ioport_resource, &lp0); if (mdesc->reserve_lp1) request_resource(&ioport_resource, &lp1); if (mdesc->reserve_lp2) request_resource(&ioport_resource, &lp2); } /* * Tag parsing. * * This is the new way of passing data to the kernel at boot time. Rather * than passing a fixed inflexible structure to the kernel, we pass a list * of variable-sized tags to the kernel. The first tag must be a ATAG_CORE * tag for the list to be recognised (to distinguish the tagged list from * a param_struct). The list is terminated with a zero-length tag (this tag * is not parsed in any way). */ static int __init parse_tag_core(const struct tag *tag) { if (tag->hdr.size > 2) { if ((tag->u.core.flags & 1) == 0) root_mountflags &= ~MS_RDONLY; ROOT_DEV = old_decode_dev(tag->u.core.rootdev); } return 0; } __tagtable(ATAG_CORE, parse_tag_core); static int __init parse_tag_mem32(const struct tag *tag) { return arm_add_memory(tag->u.mem.start, tag->u.mem.size); } __tagtable(ATAG_MEM, parse_tag_mem32); #if defined(CONFIG_VGA_CONSOLE) || defined(CONFIG_DUMMY_CONSOLE) struct screen_info screen_info = { .orig_video_lines = 30, .orig_video_cols = 80, .orig_video_mode = 0, .orig_video_ega_bx = 0, .orig_video_isVGA = 1, .orig_video_points = 8 }; static int __init parse_tag_videotext(const struct tag *tag) { screen_info.orig_x = tag->u.videotext.x; screen_info.orig_y = tag->u.videotext.y; screen_info.orig_video_page = tag->u.videotext.video_page; screen_info.orig_video_mode = tag->u.videotext.video_mode; screen_info.orig_video_cols = tag->u.videotext.video_cols; screen_info.orig_video_ega_bx = tag->u.videotext.video_ega_bx; screen_info.orig_video_lines = tag->u.videotext.video_lines; screen_info.orig_video_isVGA = tag->u.videotext.video_isvga; screen_info.orig_video_points = tag->u.videotext.video_points; return 0; } __tagtable(ATAG_VIDEOTEXT, parse_tag_videotext); #endif static int __init parse_tag_ramdisk(const struct tag *tag) { setup_ramdisk((tag->u.ramdisk.flags & 1) == 0, (tag->u.ramdisk.flags & 2) == 0, tag->u.ramdisk.start, tag->u.ramdisk.size); return 0; } __tagtable(ATAG_RAMDISK, parse_tag_ramdisk); static int __init parse_tag_serialnr(const struct tag *tag) { system_serial_low = tag->u.serialnr.low; system_serial_high = tag->u.serialnr.high; return 0; } __tagtable(ATAG_SERIAL, parse_tag_serialnr); static int __init parse_tag_revision(const struct tag *tag) { system_rev = tag->u.revision.rev; return 0; } __tagtable(ATAG_REVISION, parse_tag_revision); #ifndef CONFIG_CMDLINE_FORCE static int __init parse_tag_cmdline(const struct tag *tag) { strlcpy(default_command_line, tag->u.cmdline.cmdline, COMMAND_LINE_SIZE); return 0; } __tagtable(ATAG_CMDLINE, parse_tag_cmdline); #endif /* CONFIG_CMDLINE_FORCE */ /* * Scan the tag table for this tag, and call its parse function. * The tag table is built by the linker from all the __tagtable * declarations. */ static int __init parse_tag(const struct tag *tag) { extern struct tagtable __tagtable_begin, __tagtable_end; struct tagtable *t; for (t = &__tagtable_begin; t < &__tagtable_end; t++) if (tag->hdr.tag == t->tag) { t->parse(tag); break; } return t < &__tagtable_end; } /* * Parse all tags in the list, checking both the global and architecture * specific tag tables. */ static void __init parse_tags(const struct tag *t) { for (; t->hdr.size; t = tag_next(t)) if (!parse_tag(t)) printk(KERN_WARNING "Ignoring unrecognised tag 0x%08x\n", t->hdr.tag); } /* * This holds our defaults. */ static struct init_tags { struct tag_header hdr1; struct tag_core core; struct tag_header hdr2; struct tag_mem32 mem; struct tag_header hdr3; } init_tags __initdata = { { tag_size(tag_core), ATAG_CORE }, { 1, PAGE_SIZE, 0xff }, { tag_size(tag_mem32), ATAG_MEM }, { MEM_SIZE, PHYS_OFFSET }, { 0, ATAG_NONE } }; static void (*init_machine)(void) __initdata; static int __init customize_machine(void) { /* customizes platform devices, or adds new ones */ if (init_machine) init_machine(); return 0; } arch_initcall(customize_machine); #ifdef CONFIG_KEXEC static inline unsigned long long get_total_mem(void) { unsigned long total; total = max_low_pfn - min_low_pfn; return total << PAGE_SHIFT; } /** * reserve_crashkernel() - reserves memory are for crash kernel * * This function reserves memory area given in "crashkernel=" kernel command * line parameter. The memory reserved is used by a dump capture kernel when * primary kernel is crashing. */ static void __init reserve_crashkernel(void) { unsigned long long crash_size, crash_base; unsigned long long total_mem; int ret; total_mem = get_total_mem(); ret = parse_crashkernel(boot_command_line, total_mem, &crash_size, &crash_base); if (ret) return; ret = reserve_bootmem(crash_base, crash_size, BOOTMEM_EXCLUSIVE); if (ret < 0) { printk(KERN_WARNING "crashkernel reservation failed - " "memory is in use (0x%lx)\n", (unsigned long)crash_base); return; } printk(KERN_INFO "Reserving %ldMB of memory at %ldMB " "for crashkernel (System RAM: %ldMB)\n", (unsigned long)(crash_size >> 20), (unsigned long)(crash_base >> 20), (unsigned long)(total_mem >> 20)); crashk_res.start = crash_base; crashk_res.end = crash_base + crash_size - 1; insert_resource(&iomem_resource, &crashk_res); } #else static inline void reserve_crashkernel(void) {} #endif /* CONFIG_KEXEC */ /* * Note: elfcorehdr_addr is not just limited to vmcore. It is also used by * is_kdump_kernel() to determine if we are booting after a panic. Hence * ifdef it under CONFIG_CRASH_DUMP and not CONFIG_PROC_VMCORE. */ #ifdef CONFIG_CRASH_DUMP /* * elfcorehdr= specifies the location of elf core header stored by the crashed * kernel. This option will be passed by kexec loader to the capture kernel. */ static int __init setup_elfcorehdr(char *arg) { char *end; if (!arg) return -EINVAL; elfcorehdr_addr = memparse(arg, &end); return end > arg ? 0 : -EINVAL; } early_param("elfcorehdr", setup_elfcorehdr); #endif /* CONFIG_CRASH_DUMP */ static void __init squash_mem_tags(struct tag *tag) { for (; tag->hdr.size; tag = tag_next(tag)) if (tag->hdr.tag == ATAG_MEM) tag->hdr.tag = ATAG_NONE; } void __init setup_arch(char **cmdline_p) { struct tag *tags = (struct tag *)&init_tags; struct machine_desc *mdesc; char *from = default_command_line; unwind_init(); setup_processor(); mdesc = setup_machine(machine_arch_type); machine_name = mdesc->name; if (mdesc->soft_reboot) reboot_setup("s"); if (__atags_pointer) tags = phys_to_virt(__atags_pointer); else if (mdesc->boot_params) tags = phys_to_virt(mdesc->boot_params); #if defined(CONFIG_DEPRECATED_PARAM_STRUCT) /* * If we have the old style parameters, convert them to * a tag list. */ if (tags->hdr.tag != ATAG_CORE) convert_to_tag_list(tags); #endif if (tags->hdr.tag != ATAG_CORE) tags = (struct tag *)&init_tags; if (mdesc->fixup) mdesc->fixup(mdesc, tags, &from, &meminfo); if (tags->hdr.tag == ATAG_CORE) { if (meminfo.nr_banks != 0) squash_mem_tags(tags); save_atags(tags); parse_tags(tags); } init_mm.start_code = (unsigned long) _text; init_mm.end_code = (unsigned long) _etext; init_mm.end_data = (unsigned long) _edata; init_mm.brk = (unsigned long) _end; /* parse_early_param needs a boot_command_line */ strlcpy(boot_command_line, from, COMMAND_LINE_SIZE); /* populate cmd_line too for later use, preserving boot_command_line */ strlcpy(cmd_line, boot_command_line, COMMAND_LINE_SIZE); *cmdline_p = cmd_line; parse_early_param(); arm_memblock_init(&meminfo, mdesc); paging_init(mdesc); #ifdef CONFIG_DUMP_PREV_OOPS_MSG if( reserve_bootmem(0x0, 0x2000, BOOTMEM_EXCLUSIVE) < 0 ) printk("**** reserve bootmem fail ****\n"); #endif request_standard_resources(&meminfo, mdesc); #ifdef CONFIG_SMP smp_init_cpus(); #endif reserve_crashkernel(); cpu_init(); tcm_init(); /* * Set up various architecture-specific pointers */ arch_nr_irqs = mdesc->nr_irqs; init_arch_irq = mdesc->init_irq; system_timer = mdesc->timer; init_machine = mdesc->init_machine; #ifdef CONFIG_VT #if defined(CONFIG_VGA_CONSOLE) conswitchp = &vga_con; #elif defined(CONFIG_DUMMY_CONSOLE) conswitchp = &dummy_con; #endif #endif early_trap_init(); } static int __init topology_init(void) { int cpu; for_each_possible_cpu(cpu) { struct cpuinfo_arm *cpuinfo = &per_cpu(cpu_data, cpu); cpuinfo->cpu.hotpluggable = 1; register_cpu(&cpuinfo->cpu, cpu); } return 0; } subsys_initcall(topology_init); #ifdef CONFIG_HAVE_PROC_CPU static int __init proc_cpu_init(void) { struct proc_dir_entry *res; res = proc_mkdir("cpu", NULL); if (!res) return -ENOMEM; return 0; } fs_initcall(proc_cpu_init); #endif static const char *hwcap_str[] = { "swp", "half", "thumb", "26bit", "fastmult", "fpa", "vfp", "edsp", "java", "iwmmxt", "crunch", "thumbee", "neon", "vfpv3", "vfpv3d16", NULL }; static int c_show(struct seq_file *m, void *v) { int i; seq_printf(m, "Processor\t: %s rev %d (%s)\n", cpu_name, read_cpuid_id() & 15, elf_platform); #if defined(CONFIG_SMP) for_each_online_cpu(i) { /* * glibc reads /proc/cpuinfo to determine the number of * online processors, looking for lines beginning with * "processor". Give glibc what it expects. */ seq_printf(m, "processor\t: %d\n", i); seq_printf(m, "BogoMIPS\t: %lu.%02lu\n\n", per_cpu(cpu_data, i).loops_per_jiffy / (500000UL/HZ), (per_cpu(cpu_data, i).loops_per_jiffy / (5000UL/HZ)) % 100); } #else /* CONFIG_SMP */ seq_printf(m, "BogoMIPS\t: %lu.%02lu\n", loops_per_jiffy / (500000/HZ), (loops_per_jiffy / (5000/HZ)) % 100); #endif /* dump out the processor features */ seq_puts(m, "Features\t: "); for (i = 0; hwcap_str[i]; i++) if (elf_hwcap & (1 << i)) seq_printf(m, "%s ", hwcap_str[i]); seq_printf(m, "\nCPU implementer\t: 0x%02x\n", read_cpuid_id() >> 24); seq_printf(m, "CPU architecture: %s\n", proc_arch[cpu_architecture()]); if ((read_cpuid_id() & 0x0008f000) == 0x00000000) { /* pre-ARM7 */ seq_printf(m, "CPU part\t: %07x\n", read_cpuid_id() >> 4); } else { if ((read_cpuid_id() & 0x0008f000) == 0x00007000) { /* ARM7 */ seq_printf(m, "CPU variant\t: 0x%02x\n", (read_cpuid_id() >> 16) & 127); } else { /* post-ARM7 */ seq_printf(m, "CPU variant\t: 0x%x\n", (read_cpuid_id() >> 20) & 15); } seq_printf(m, "CPU part\t: 0x%03x\n", (read_cpuid_id() >> 4) & 0xfff); } seq_printf(m, "CPU revision\t: %d\n", read_cpuid_id() & 15); seq_puts(m, "\n"); seq_printf(m, "Hardware\t: %s\n", machine_name); seq_printf(m, "Revision\t: %04x\n", system_rev); seq_printf(m, "Serial\t\t: %08x%08x\n", system_serial_high, system_serial_low); return 0; } static void *c_start(struct seq_file *m, loff_t *pos) { return *pos < 1 ? (void *)1 : NULL; } static void *c_next(struct seq_file *m, void *v, loff_t *pos) { ++*pos; return NULL; } static void c_stop(struct seq_file *m, void *v) { } const struct seq_operations cpuinfo_op = { .start = c_start, .next = c_next, .stop = c_stop, .show = c_show };
23.378788
97
0.691208
[ "model" ]
7fa9827f9e38ce8a7e523af496ba82cc50753abf
4,838
h
C
dlib/memory_manager/memory_manager_kernel_abstract.h
oms1226/dlib-19.13
0bb55d112324edb700a42a3e6baca09c03967754
[ "MIT" ]
null
null
null
dlib/memory_manager/memory_manager_kernel_abstract.h
oms1226/dlib-19.13
0bb55d112324edb700a42a3e6baca09c03967754
[ "MIT" ]
null
null
null
dlib/memory_manager/memory_manager_kernel_abstract.h
oms1226/dlib-19.13
0bb55d112324edb700a42a3e6baca09c03967754
[ "MIT" ]
null
null
null
// Copyright (C) 2004 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_MEMORY_MANAGER_KERNEl_ABSTRACT_ #ifdef DLIB_MEMORY_MANAGER_KERNEl_ABSTRACT_ #include "../algs.h" namespace dlib { template < typename T > class memory_manager { /*! REQUIREMENTS ON T T must have a default constructor. INITIAL VALUE get_number_of_allocations() == 0 WHAT THIS OBJECT REPRESENTS This object represents some kind of memory manager or memory pool. !*/ public: typedef T type; template <typename U> struct rebind { typedef memory_manager<U> other; }; memory_manager( ); /*! ensures - #*this is properly initialized throws - std::bad_alloc !*/ virtual ~memory_manager( ); /*! ensures - if (get_number_of_allocations() == 0) then - all resources associated with *this have been released. - else - The memory still allocated will not be deleted and this causes a memory leak. !*/ size_t get_number_of_allocations ( ) const; /*! ensures - returns the current number of outstanding allocations !*/ T* allocate ( ); /*! ensures - allocates a new object of type T and returns a pointer to it. - #get_number_of_allocations() == get_number_of_allocations() + 1 throws - std::bad_alloc or any exception thrown by T's constructor. If this exception is thrown then the call to allocate() has no effect on #*this. !*/ void deallocate ( T* item ); /*! requires - item == is a pointer to memory that was obtained from a call to this->allocate(). (i.e. you can't deallocate a pointer you got from a different memory_manager instance.) - the memory pointed to by item hasn't already been deallocated. ensures - deallocates the object pointed to by item - #get_number_of_allocations() == get_number_of_allocations() - 1 !*/ T* allocate_array ( size_t size ); /*! ensures - allocates a new array of size objects of type T and returns a pointer to it. - #get_number_of_allocations() == get_number_of_allocations() + 1 throws - std::bad_alloc or any exception thrown by T's constructor. If this exception is thrown then the call to allocate() has no effect on #*this. !*/ void deallocate_array ( T* item ); /*! requires - item == is a pointer to memory that was obtained from a call to this->allocate_array(). (i.e. you can't deallocate a pointer you got from a different memory_manager instance and it must be an array.) - the memory pointed to by item hasn't already been deallocated. ensures - deallocates the array pointed to by item - #get_number_of_allocations() == get_number_of_allocations() - 1 !*/ void swap ( memory_manager& item ); /*! ensures - swaps *this and item !*/ private: // restricted functions memory_manager(memory_manager&); // copy constructor memory_manager& operator=(memory_manager&); // assignment operator }; template < typename T > inline void swap ( memory_manager<T>& a, memory_manager<T>& b ) { a.swap(b); } /*! provides a global swap function !*/ } #endif // DLIB_MEMORY_MANAGER_KERNEl_ABSTRACT_
32.911565
87
0.459074
[ "object" ]
7faa19526c8d35d68226f566743a812b0d6a2798
3,242
h
C
src/video/x11/SDL_x11dyn.h
ARPGLTD/SDL
f3fd1ffb99e44adde00a1c07acfa67a55e2e689e
[ "Zlib" ]
3
2021-08-16T23:38:22.000Z
2022-02-09T16:10:55.000Z
src/video/x11/SDL_x11dyn.h
ARPGLTD/SDL
f3fd1ffb99e44adde00a1c07acfa67a55e2e689e
[ "Zlib" ]
1
2022-03-04T17:14:16.000Z
2022-03-04T17:14:16.000Z
src/video/x11/SDL_x11dyn.h
ARPGLTD/SDL
f3fd1ffb99e44adde00a1c07acfa67a55e2e689e
[ "Zlib" ]
3
2021-04-25T08:16:53.000Z
2021-07-25T05:43:31.000Z
/* Simple DirectMedia Layer Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org> 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. */ #include "../../SDL_internal.h" #ifndef SDL_x11dyn_h_ #define SDL_x11dyn_h_ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM #include <X11/XKBlib.h> #endif /* Apparently some X11 systems can't include this multiple times... */ #ifndef SDL_INCLUDED_XLIBINT_H #define SDL_INCLUDED_XLIBINT_H 1 #include <X11/Xlibint.h> #endif #include <X11/Xproto.h> #include <X11/extensions/Xext.h> #ifndef NO_SHARED_MEMORY #include <sys/ipc.h> #include <sys/shm.h> #include <X11/extensions/XShm.h> #endif #if SDL_VIDEO_DRIVER_X11_XCURSOR #include <X11/Xcursor/Xcursor.h> #endif #if SDL_VIDEO_DRIVER_X11_XDBE #include <X11/extensions/Xdbe.h> #endif #if SDL_VIDEO_DRIVER_X11_XINERAMA #include <X11/extensions/Xinerama.h> #endif #if SDL_VIDEO_DRIVER_X11_XINPUT2 #include <X11/extensions/XInput2.h> #endif #if SDL_VIDEO_DRIVER_X11_XRANDR #include <X11/extensions/Xrandr.h> #endif #if SDL_VIDEO_DRIVER_X11_XSCRNSAVER #include <X11/extensions/scrnsaver.h> #endif #if SDL_VIDEO_DRIVER_X11_XSHAPE #include <X11/extensions/shape.h> #endif #if SDL_VIDEO_DRIVER_X11_XVIDMODE #include <X11/extensions/xf86vmode.h> #endif #ifdef __cplusplus extern "C" { #endif /* evil function signatures... */ typedef Bool(*SDL_X11_XESetWireToEventRetType) (Display *, XEvent *, xEvent *); typedef int (*SDL_X11_XSynchronizeRetType) (Display *); typedef Status(*SDL_X11_XESetEventToWireRetType) (Display *, XEvent *, xEvent *); int SDL_X11_LoadSymbols(void); void SDL_X11_UnloadSymbols(void); /* Declare all the function pointers and wrappers... */ #define SDL_X11_SYM(rc,fn,params,args,ret) \ typedef rc (*SDL_DYNX11FN_##fn) params; \ extern SDL_DYNX11FN_##fn X11_##fn; #include "SDL_x11sym.h" /* Annoying varargs entry point... */ #ifdef X_HAVE_UTF8_STRING typedef XIC(*SDL_DYNX11FN_XCreateIC) (XIM,...); typedef char *(*SDL_DYNX11FN_XGetICValues) (XIC, ...); extern SDL_DYNX11FN_XCreateIC X11_XCreateIC; extern SDL_DYNX11FN_XGetICValues X11_XGetICValues; #endif /* These SDL_X11_HAVE_* flags are here whether you have dynamic X11 or not. */ #define SDL_X11_MODULE(modname) extern int SDL_X11_HAVE_##modname; #include "SDL_x11sym.h" #ifdef __cplusplus } #endif #endif /* !defined SDL_x11dyn_h_ */ /* vi: set ts=4 sw=4 expandtab: */
29.207207
81
0.765268
[ "shape" ]
7fac8edbfa02861ba53bca849ec557aee61d0b27
2,314
h
C
state.h
xdbob/cpuid
42b9cea93b5d9f453c273e475e1e4ce4dd32b5bc
[ "0BSD" ]
null
null
null
state.h
xdbob/cpuid
42b9cea93b5d9f453c273e475e1e4ce4dd32b5bc
[ "0BSD" ]
null
null
null
state.h
xdbob/cpuid
42b9cea93b5d9f453c273e475e1e4ce4dd32b5bc
[ "0BSD" ]
null
null
null
/* * CPUID * * A simple and small tool to dump/decode CPUID information. * * Copyright (c) 2010-2018, Steven Noonan <steven@uplinklabs.net> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef __state_h #define __state_h #include "cpuid.h" #include "threads.h" #include "vendor.h" struct cpu_signature_t { unsigned stepping:4; unsigned model:4; unsigned family:4; unsigned type:2; unsigned reserved1:2; unsigned extmodel:4; unsigned extfamily:8; unsigned reserved2:4; }; struct cpuid_leaf_t { struct cpu_regs_t input; struct cpu_regs_t output; }; struct cpuid_state_t { thread_init_handler_t thread_init; thread_bind_handler_t thread_bind; thread_count_handler_t thread_count; cpuid_call_handler_t cpuid_call; cpuid_print_handler_t cpuid_print; /* These two are stubs for thread_bind/thread_count. */ uint32_t cpu_bound_index; uint32_t cpu_logical_count; struct cpuid_leaf_t **cpuid_leaves; struct cpu_regs_t last_leaf; union { struct cpu_signature_t sig; uint32_t sig_int; }; uint16_t vendor; uint32_t curmax; char procname[48]; }; #define INIT_CPUID_STATE(x) { \ memset((x), 0, sizeof(struct cpuid_state_t)); \ (x)->cpuid_print = cpuid_dump_normal; \ (x)->cpuid_call = cpuid_native; \ (x)->thread_init = thread_init_native; \ (x)->thread_bind = thread_bind_native; \ (x)->thread_count = thread_count_native; \ } #define FREE_CPUID_STATE(x) { \ if ((x)->cpuid_leaves) { \ uint32_t i; \ for (i = 0; i < (x)->cpu_logical_count; i++) { \ free((x)->cpuid_leaves[i]); \ } \ free((x)->cpuid_leaves); \ } \ } #endif /* vim: set ts=4 sts=4 sw=4 noet: */
25.711111
75
0.732498
[ "model" ]
7fad3653d2aedbdd8673d67519496c9d0ecd335d
714
h
C
ios/BoomMeeting.framework/Versions/A/Headers/BMUserModel.h
lutaohua/BoomMeeting
b88f231313d98844f594b38eac37deabc4deae9b
[ "MIT" ]
null
null
null
ios/BoomMeeting.framework/Versions/A/Headers/BMUserModel.h
lutaohua/BoomMeeting
b88f231313d98844f594b38eac37deabc4deae9b
[ "MIT" ]
null
null
null
ios/BoomMeeting.framework/Versions/A/Headers/BMUserModel.h
lutaohua/BoomMeeting
b88f231313d98844f594b38eac37deabc4deae9b
[ "MIT" ]
null
null
null
// // BMUserModel.h // BoomMeeting // // Created by zhaozhidan on 2020/11/26. // #import <Foundation/Foundation.h> #import "BMConstants.h" @class BMStreamModel; NS_ASSUME_NONNULL_BEGIN @interface BMUserModel : NSObject @property (nonatomic, copy) NSString *userId; @property (nonatomic, copy) NSString *nickname; @property (nonatomic, copy) NSString *streamId; @property (nonatomic, assign) BMWindowType windowType; @property (nonatomic, assign) BOOL *audioEnable; @property (nonatomic, assign) BOOL *videoEnable; ///// 大窗或正常窗口的 model //@property (nonatomic, strong) BMStreamModel *streamModel; ///// 小窗的 model //@property (nonatomic, strong) BMStreamModel *smallStreamModel; @end NS_ASSUME_NONNULL_END
22.3125
64
0.756303
[ "model" ]
7fb6950614bd4a6761235a203bac8f28fa3313c2
22,605
c
C
Middlewares/ST/STM32_Key_Management_Services/Core/kms_platf_objects.c
thierry13790/LoRa_Motion_Sensor_LetterBox
12bb6202ffaaf0b47e5b242667088273a25affc8
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Middlewares/ST/STM32_Key_Management_Services/Core/kms_platf_objects.c
thierry13790/LoRa_Motion_Sensor_LetterBox
12bb6202ffaaf0b47e5b242667088273a25affc8
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Middlewares/ST/STM32_Key_Management_Services/Core/kms_platf_objects.c
thierry13790/LoRa_Motion_Sensor_LetterBox
12bb6202ffaaf0b47e5b242667088273a25affc8
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/** ****************************************************************************** * @file kms_platf_objects.c * @author MCD Application Team * @brief This file contains definitions for Key Management Services (KMS) * module platform objects management ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "kms.h" /* PKCS11 definitions */ #if defined(KMS_ENABLED) #include "kms_init.h" /* KMS session services */ #include "kms_platf_objects.h" /* KMS platform objects services */ #include "kms_nvm_storage.h" /* KMS NVM storage services */ #include "kms_vm_storage.h" /* KMS VM storage services */ #define KMS_PLATF_OBJECTS_C #include "kms_platf_objects_config.h" /* KMS embedded objects definitions */ /* * Key ranges verification */ #if (KMS_INDEX_MIN_EMBEDDED_OBJECTS > KMS_INDEX_MAX_EMBEDDED_OBJECTS) #error "Embedded objects index min and max are not well ordered" #endif /* KMS_INDEX_MIN_EMBEDDED_OBJECTS > KMS_INDEX_MAX_EMBEDDED_OBJECTS */ #ifdef KMS_NVM_ENABLED #if (KMS_INDEX_MIN_NVM_STATIC_OBJECTS > KMS_INDEX_MAX_NVM_STATIC_OBJECTS) #error "NVM static ID objects index min and max are not well ordered" #endif /* KMS_INDEX_MIN_NVM_STATIC_OBJECTS > KMS_INDEX_MAX_NVM_STATIC_OBJECTS */ #if (KMS_INDEX_MAX_EMBEDDED_OBJECTS >= KMS_INDEX_MIN_NVM_STATIC_OBJECTS) #error "NVM static IDs & Embedded ranges are overlapping" #endif /* KMS_INDEX_MAX_EMBEDDED_OBJECTS >= KMS_INDEX_MIN_NVM_STATIC_OBJECTS */ #if (KMS_NVM_SLOT_NUMBERS < (KMS_INDEX_MAX_NVM_STATIC_OBJECTS-KMS_INDEX_MIN_NVM_STATIC_OBJECTS+1)) #error "Not enough slot declared in KMS_NVM_SLOT_NUMBERS to store all allowed NVM Static IDs objects" #endif /* KMS_NVM_SLOT_NUMBERS < (KMS_INDEX_MAX_NVM_STATIC_OBJECTS-KMS_INDEX_MIN_NVM_STATIC_OBJECTS+1) */ #ifdef KMS_NVM_DYNAMIC_ENABLED #if (KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS > KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS) #error "NVM dynamic ID objects index min and max are not well ordered" #endif /* KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS > KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS */ #if (KMS_INDEX_MAX_NVM_STATIC_OBJECTS >= KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS) #error "NVM static IDs & Dynamic IDs ranges are overlapping" #endif /* KMS_INDEX_MAX_NVM_STATIC_OBJECTS >= KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS */ #if (KMS_NVM_SLOT_NUMBERS < (KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS-KMS_INDEX_MIN_NVM_STATIC_OBJECTS+1)) #error "Not enough slot declared in KMS_NVM_SLOT_NUMBERS to store all allowed NVM Static & dynamic IDs objects" #endif /* KMS_NVM_SLOT_NUMBERS < (KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS-KMS_INDEX_MIN_NVM_STATIC_OBJECTS+1) */ #endif /* KMS_NVM_DYNAMIC_ENABLED */ #endif /* KMS_NVM_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED #if (KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS > KMS_INDEX_MAX_VM_DYNAMIC_OBJECTS) #error "VM dynamic ID objects index min and max are not well ordered" #endif /* KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS > KMS_INDEX_MAX_VM_DYNAMIC_OBJECTS */ #if defined(KMS_NVM_ENABLED) #if (KMS_INDEX_MAX_NVM_STATIC_OBJECTS >= KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS) #error "NVM static IDs & VM Dynamic IDs ranges are overlapping" #endif /* KMS_INDEX_MAX_NVM_STATIC_OBJECTS >= KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS */ #else /* KMS_NVM_DYNAMIC_ENABLED */ #if (KMS_INDEX_MAX_EMBEDDED_OBJECTS >= KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS) #error "Embedded IDs & VM Dynamic IDs ranges are overlapping" #endif /* KMS_INDEX_MAX_EMBEDDED_OBJECTS >= KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS */ #endif /* KMS_NVM_DYNAMIC_ENABLED */ #endif /* KMS_VM_DYNAMIC_ENABLED */ /** @addtogroup Key_Management_Services Key Management Services (KMS) * @{ */ /** @addtogroup KMS_PLATF Platform Objects * @{ */ /* Private types -------------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @addtogroup KMS_PLATF_Private_Variables Private Variables * @{ */ #ifdef KMS_NVM_ENABLED /** * @brief NVM initialization status */ static uint32_t kms_platf_nvm_initialisation_done = 0UL; /** * @brief NVM static objects access variables * @note This "cache" table is used to speed up access to NVM static objects */ static kms_obj_keyhead_t *KMS_PlatfObjects_NvmStaticList[KMS_INDEX_MAX_NVM_STATIC_OBJECTS - KMS_INDEX_MIN_NVM_STATIC_OBJECTS + 1]; #ifdef KMS_NVM_DYNAMIC_ENABLED /** * @brief NVM dynamic objects access variables * @note This "cache" table is used to speed up access to NVM dynamic objects */ static kms_obj_keyhead_t *KMS_PlatfObjects_NvmDynamicList[KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS - KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS + 1]; #endif /* KMS_NVM_DYNAMIC_ENABLED */ #endif /* KMS_NVM_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED /** * @brief VM initialization status */ static uint32_t kms_platf_vm_initialisation_done = 0UL; /** * @brief VM dynamic objects access variables * @note This "cache" table is used to speed up access to VM dynamic objects */ static kms_obj_keyhead_t *KMS_PlatfObjects_VmDynamicList[KMS_INDEX_MAX_VM_DYNAMIC_OBJECTS - KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS + 1]; #endif /* KMS_VM_DYNAMIC_ENABLED */ /** * @} */ /* Private function prototypes -----------------------------------------------*/ #ifdef KMS_NVM_ENABLED static void KMS_PlatfObjects_NvmStaticObjectList(void); #endif /* KMS_NVM_ENABLED */ #ifdef KMS_NVM_DYNAMIC_ENABLED static void KMS_PlatfObjects_NvmDynamicObjectList(void); #endif /* KMS_NVM_DYNAMIC_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED static void KMS_PlatfObjects_VmDynamicObjectList(void); #endif /* KMS_VM_DYNAMIC_ENABLED */ /* Private function ----------------------------------------------------------*/ /** @addtogroup KMS_PLATF_Private_Functions Private Functions * @{ */ #ifdef KMS_NVM_ENABLED /** * @brief Update @ref KMS_PlatfObjects_NvmStaticList with NVM contents * @retval None */ static void KMS_PlatfObjects_NvmStaticObjectList(void) { nvms_error_t nvms_rv; size_t nvms_data_size; kms_obj_keyhead_t *p_nvms_data; /* Load the KMS_PlatfObjects_NvmStaticList[], used to store buffer to NVM */ /* This should save processing time */ for (uint32_t i = KMS_INDEX_MIN_NVM_STATIC_OBJECTS; i < KMS_INDEX_MAX_NVM_STATIC_OBJECTS; i++) { /* Read values from NVM */ nvms_rv = NVMS_GET_DATA(i - KMS_INDEX_MIN_NVM_STATIC_OBJECTS, &nvms_data_size, (uint8_t **)(uint32_t)&p_nvms_data); if ((nvms_data_size != 0UL) && (nvms_rv == NVMS_NOERROR)) { KMS_PlatfObjects_NvmStaticList[i - KMS_INDEX_MIN_NVM_STATIC_OBJECTS] = p_nvms_data; } else { KMS_PlatfObjects_NvmStaticList[i - KMS_INDEX_MIN_NVM_STATIC_OBJECTS] = NULL; } } } #endif /* KMS_NVM_ENABLED */ #ifdef KMS_NVM_DYNAMIC_ENABLED /** * @brief Update @ref KMS_PlatfObjects_NvmDynamicList with NVM contents * @retval None */ static void KMS_PlatfObjects_NvmDynamicObjectList(void) { nvms_error_t nvms_rv; size_t nvms_data_size; kms_obj_keyhead_t *p_nvms_data; /* Load the KMS_PlatfObjects_NvmDynamicList[], used to store buffer to NVM */ /* This should save processing time */ for (uint32_t i = KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS; i <= KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS; i++) { /* Read values from NVM */ nvms_rv = NVMS_GET_DATA(i - KMS_INDEX_MIN_NVM_STATIC_OBJECTS, &nvms_data_size, (uint8_t **)(uint32_t)&p_nvms_data); if ((nvms_data_size != 0UL) && (nvms_rv == NVMS_NOERROR)) { KMS_PlatfObjects_NvmDynamicList[i - KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS] = p_nvms_data; } else { KMS_PlatfObjects_NvmDynamicList[i - KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS] = NULL; } } } #endif /* KMS_NVM_DYNAMIC_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED /** * @brief Update @ref KMS_PlatfObjects_VmDynamicList with VM contents * @retval None */ static void KMS_PlatfObjects_VmDynamicObjectList(void) { vms_error_t vms_rv; size_t vms_data_size; kms_obj_keyhead_t *p_vms_data; /* Load the KMS_PlatfObjects_VmDynamicList[], used to store buffer to VM */ /* This should save processing time */ for (uint32_t i = KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS; i <= KMS_INDEX_MAX_VM_DYNAMIC_OBJECTS; i++) { /* Read values from VM */ vms_rv = VMS_GET_DATA(i - KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS, &vms_data_size, (uint8_t **)(uint32_t)&p_vms_data); if ((vms_data_size != 0UL) && (vms_rv == VMS_NOERROR)) { KMS_PlatfObjects_VmDynamicList[i - KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS] = p_vms_data; } else { KMS_PlatfObjects_VmDynamicList[i - KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS] = NULL; } } } #endif /* KMS_VM_DYNAMIC_ENABLED */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup KMS_PLATF_Exported_Functions Exported Functions * @{ */ /** * @brief Returns range of embedded objects * @param pMin Embedded objects min ID * @param pMax Embedded objects max ID * @retval None */ void KMS_PlatfObjects_EmbeddedRange(uint32_t *pMin, uint32_t *pMax) { *pMin = KMS_INDEX_MIN_EMBEDDED_OBJECTS; *pMax = KMS_INDEX_MAX_EMBEDDED_OBJECTS; } /** * @brief Returns embedded object corresponding to given key handle * @param hKey key handle * @retval Corresponding object */ kms_obj_keyhead_t *KMS_PlatfObjects_EmbeddedObject(uint32_t hKey) { return (kms_obj_keyhead_t *)(uint32_t)KMS_PlatfObjects_EmbeddedList[hKey - KMS_INDEX_MIN_EMBEDDED_OBJECTS]; } #ifdef KMS_NVM_ENABLED /** * @brief Returns range of NVM static objects * @param pMin NVM static objects min ID * @param pMax NVM static objects max ID * @retval None */ void KMS_PlatfObjects_NvmStaticRange(uint32_t *pMin, uint32_t *pMax) { *pMin = KMS_INDEX_MIN_NVM_STATIC_OBJECTS; *pMax = KMS_INDEX_MAX_NVM_STATIC_OBJECTS; } #endif /* KMS_NVM_ENABLED */ #ifdef KMS_NVM_ENABLED /** * @brief Returns NVM static object corresponding to given key handle * @param hKey key handle * @retval Corresponding object */ kms_obj_keyhead_t *KMS_PlatfObjects_NvmStaticObject(uint32_t hKey) { return KMS_PlatfObjects_NvmStaticList[hKey - KMS_INDEX_MIN_NVM_STATIC_OBJECTS]; } #endif /* KMS_NVM_ENABLED */ #ifdef KMS_NVM_DYNAMIC_ENABLED /** * @brief Returns range of NVM dynamic objects * @param pMin NVM dynamic objects min ID * @param pMax NVM dynamic objects max ID * @retval None */ void KMS_PlatfObjects_NvmDynamicRange(uint32_t *pMin, uint32_t *pMax) { *pMin = KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS; *pMax = KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS; } #endif /* KMS_NVM_DYNAMIC_ENABLED */ #ifdef KMS_NVM_DYNAMIC_ENABLED /** * @brief Returns NVM dynamic object corresponding to given key handle * @param hKey key handle * @retval Corresponding object */ kms_obj_keyhead_t *KMS_PlatfObjects_NvmDynamicObject(uint32_t hKey) { return KMS_PlatfObjects_NvmDynamicList[hKey - KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS]; } #endif /* KMS_NVM_DYNAMIC_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED /** * @brief Returns range of VM dynamic objects * @param pMin VM dynamic objects min ID * @param pMax VM dynamic objects max ID * @retval None */ void KMS_PlatfObjects_VmDynamicRange(uint32_t *pMin, uint32_t *pMax) { *pMin = KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS; *pMax = KMS_INDEX_MAX_VM_DYNAMIC_OBJECTS; } #endif /* KMS_VM_DYNAMIC_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED /** * @brief Returns VM dynamic object corresponding to given key handle * @param hKey key handle * @retval Corresponding object */ kms_obj_keyhead_t *KMS_PlatfObjects_VmDynamicObject(uint32_t hKey) { return KMS_PlatfObjects_VmDynamicList[hKey - KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS]; } #endif /* KMS_VM_DYNAMIC_ENABLED */ #if defined(KMS_NVM_DYNAMIC_ENABLED) || defined(KMS_VM_DYNAMIC_ENABLED) /** * @brief Search an available NVM / VM dynamic ID to store blob object * @param pBlob Blob object to store * @param pObjId NVM / VM dynamic ID * @retval CKR_OK * CKR_ARGUMENTS_BAD * CKR_DEVICE_MEMORY * @ref KMS_PlatfObjects_NvmStoreObject returned values * @ref KMS_PlatfObjects_VmStoreObject returned values */ CK_RV KMS_PlatfObjects_AllocateAndStore(kms_obj_keyhead_no_blob_t *pBlob, CK_OBJECT_HANDLE_PTR pObjId) { CK_OBJECT_HANDLE Index; CK_RV e_ret_status; if ((pObjId == NULL_PTR) || (pBlob == NULL_PTR)) { e_ret_status = CKR_ARGUMENTS_BAD; } else { *pObjId = KMS_HANDLE_KEY_NOT_KNOWN; #ifdef KMS_NVM_DYNAMIC_ENABLED /* Find a Free place in nvm dynamic table */ for (Index = 0; Index <= (KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS - KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS); Index++) { if (KMS_PlatfObjects_NvmDynamicList[Index] == NULL) { *pObjId = Index + KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS; break; } } #endif /* KMS_NVM_DYNAMIC_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED /* Find a Free place in vm dynamic table */ for (Index = 0; Index <= (KMS_INDEX_MAX_VM_DYNAMIC_OBJECTS - KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS); Index++) { if (KMS_PlatfObjects_VmDynamicList[Index] == NULL) { *pObjId = Index + KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS; break; } } #endif /* KMS_VM_DYNAMIC_ENABLED */ if (*pObjId == KMS_HANDLE_KEY_NOT_KNOWN) { /* No place found in Dynamic List */ e_ret_status = CKR_DEVICE_MEMORY; } else { /* Update object ID */ pBlob->object_id = *pObjId; #ifdef KMS_NVM_DYNAMIC_ENABLED /* Store in NVM storage */ e_ret_status = KMS_PlatfObjects_NvmStoreObject(*pObjId, (uint8_t *)pBlob, pBlob->blobs_size + sizeof(kms_obj_keyhead_no_blob_t)); #endif /* KMS_NVM_DYNAMIC_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED /* Store in VM storage */ e_ret_status = KMS_PlatfObjects_VmStoreObject(*pObjId, (uint8_t *)pBlob, pBlob->blobs_size + sizeof(kms_obj_keyhead_no_blob_t)); #endif /* KMS_VM_DYNAMIC_ENABLED */ /* A Garbage collection generate a WARNING ==> Not an error */ if (e_ret_status != CKR_OK) { *pObjId = KMS_HANDLE_KEY_NOT_KNOWN; } } } return e_ret_status; } #endif /* KMS_NVM_DYNAMIC_ENABLED || KMS_NVM_DYNAMIC_ENABLED */ #ifdef KMS_EXT_TOKEN_ENABLED /** * @brief Returns range of External token static objects * @param pMin External token static objects min ID * @param pMax External token static objects max ID * @retval None */ void KMS_PlatfObjects_ExtTokenStaticRange(uint32_t *pMin, uint32_t *pMax) { *pMin = KMS_INDEX_MIN_EXT_TOKEN_STATIC_OBJECTS; *pMax = KMS_INDEX_MAX_EXT_TOKEN_STATIC_OBJECTS; } /** * @brief Returns range of External token dynamic objects * @param pMin External token dynamic objects min ID * @param pMax External token dynamic objects max ID * @retval None */ void KMS_PlatfObjects_ExtTokenDynamicRange(uint32_t *pMin, uint32_t *pMax) { *pMin = KMS_INDEX_MIN_EXT_TOKEN_DYNAMIC_OBJECTS; *pMax = KMS_INDEX_MAX_EXT_TOKEN_DYNAMIC_OBJECTS; } #endif /* KMS_EXT_TOKEN_ENABLED */ /** * @brief Initialize platform objects * @note Initialize NVM / VM storage and fill "cache" buffers * @retval None */ void KMS_PlatfObjects_Init(void) { #ifdef KMS_NVM_ENABLED /* The NVMS_Init should be done only once */ if (kms_platf_nvm_initialisation_done == 0UL) { /* Initialize the NVMS */ (void)NVMS_Init(); kms_platf_nvm_initialisation_done = 1UL; } KMS_PlatfObjects_NvmStaticObjectList(); #ifdef KMS_NVM_DYNAMIC_ENABLED KMS_PlatfObjects_NvmDynamicObjectList(); #endif /* KMS_NVM_DYNAMIC_ENABLED */ #endif /* KMS_NVM_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED /* The VMS_Init should be done only once */ if (kms_platf_vm_initialisation_done == 0UL) { /* Initialize the VMS */ (void)VMS_Init(); kms_platf_vm_initialisation_done = 1UL; } KMS_PlatfObjects_VmDynamicObjectList(); #endif /* KMS_VM_DYNAMIC_ENABLED */ } /** * @brief De-Initialize platform objects * @retval None */ void KMS_PlatfObjects_Finalize(void) { #ifdef KMS_NVM_ENABLED /* Finalize the NVMS */ NVMS_Deinit(); /* We must re-allow the call to NVMS_Init() */ kms_platf_nvm_initialisation_done = 0UL; #endif /* KMS_NVM_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED /* Finalize the VMS */ VMS_Deinit(); /* We must re-allow the call to VMS_Init() */ kms_platf_vm_initialisation_done = 0UL; #endif /* KMS_VM_DYNAMIC_ENABLED */ } #ifdef KMS_NVM_ENABLED /** * @brief Store object in NVM storage * @note Either static or dynamic objects * @param ObjectId Object ID * @param pObjectToAdd Object to add * @param ObjectSize Object size * @retval CKR_OK if storage is successful * CKR_DEVICE_MEMORY otherwise */ CK_RV KMS_PlatfObjects_NvmStoreObject(uint32_t ObjectId, uint8_t *pObjectToAdd, uint32_t ObjectSize) { nvms_error_t rv; CK_RV e_ret_status; /* It's a NVM STATIC object */ if ((ObjectId >= KMS_INDEX_MIN_NVM_STATIC_OBJECTS) && (ObjectId <= KMS_INDEX_MAX_NVM_STATIC_OBJECTS)) { rv = NVMS_WRITE_DATA(ObjectId - KMS_INDEX_MIN_NVM_STATIC_OBJECTS, ObjectSize, (const uint8_t *)pObjectToAdd); } else { #ifdef KMS_NVM_DYNAMIC_ENABLED /* It's a NVM DYNAMIC object */ if ((ObjectId >= KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS) && (ObjectId <= KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS)) { rv = NVMS_WRITE_DATA(ObjectId - KMS_INDEX_MIN_NVM_STATIC_OBJECTS, ObjectSize, (const uint8_t *)pObjectToAdd); } else { rv = NVMS_SLOT_INVALID; } #else /* KMS_NVM_DYNAMIC_ENABLED */ rv = NVMS_SLOT_INVALID; #endif /* KMS_NVM_DYNAMIC_ENABLED */ } /* A Garbage collection generate a WARNING ==> Not an error */ if ((rv == NVMS_NOERROR) || (rv == NVMS_WARNING)) { e_ret_status = CKR_OK; } else { e_ret_status = CKR_DEVICE_MEMORY; } /* Refresh NVM lists */ KMS_PlatfObjects_NvmStaticObjectList(); #ifdef KMS_NVM_DYNAMIC_ENABLED KMS_PlatfObjects_NvmDynamicObjectList(); #endif /* KMS_NVM_DYNAMIC_ENABLED */ return e_ret_status; } #ifdef KMS_NVM_DYNAMIC_ENABLED /** * @brief Remove object from NVM storage * @note Only dynamic objects * @param ObjectId Object ID * @retval CKR_OK if removal is successful * CKR_DEVICE_MEMORY otherwise */ CK_RV KMS_PlatfObjects_NvmRemoveObject(uint32_t ObjectId) { nvms_error_t rv = NVMS_DATA_NOT_FOUND; CK_RV e_ret_status; /* Check that the ObjectID is in dynamic range */ if ((ObjectId >= KMS_INDEX_MIN_NVM_DYNAMIC_OBJECTS) && (ObjectId <= KMS_INDEX_MAX_NVM_DYNAMIC_OBJECTS)) { rv = NVMS_EraseData(ObjectId - KMS_INDEX_MIN_NVM_STATIC_OBJECTS); } /* A Garbage collection generate a WARNING ==> Not an error */ if ((rv == NVMS_NOERROR) || (rv == NVMS_WARNING)) { e_ret_status = CKR_OK; } else { e_ret_status = CKR_DEVICE_MEMORY; } /* Refresh NVM lists */ KMS_PlatfObjects_NvmStaticObjectList(); #ifdef KMS_NVM_DYNAMIC_ENABLED KMS_PlatfObjects_NvmDynamicObjectList(); #endif /* KMS_NVM_DYNAMIC_ENABLED */ return e_ret_status; } #endif /* KMS_NVM_DYNAMIC_ENABLED */ #if defined(KMS_IMPORT_BLOB) /** * @brief Returns Blob import verification key handle * @retval Key handle */ CK_ULONG KMS_PlatfObjects_GetBlobVerifyKey(void) { return (CK_ULONG)KMS_INDEX_BLOBIMPORT_VERIFY; } #endif /* KMS_IMPORT_BLOB */ #if defined(KMS_IMPORT_BLOB) /** * @brief Returns Blob import decryption key handle * @retval Key handle */ CK_ULONG KMS_PlatfObjects_GetBlobDecryptKey(void) { return (CK_ULONG)KMS_INDEX_BLOBIMPORT_DECRYPT; } #endif /* KMS_IMPORT_BLOB */ #endif /* KMS_NVM_ENABLED */ #ifdef KMS_VM_DYNAMIC_ENABLED /** * @brief Store object in VM storage * @note Either static or dynamic objects * @param ObjectId Object ID * @param pObjectToAdd Object to add * @param ObjectSize Object size * @retval CKR_OK if storage is successful * CKR_DEVICE_MEMORY otherwise */ CK_RV KMS_PlatfObjects_VmStoreObject(uint32_t ObjectId, uint8_t *pObjectToAdd, uint32_t ObjectSize) { vms_error_t rv; CK_RV e_ret_status; /* It's a VM DYNAMIC object */ if ((ObjectId >= KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS) && (ObjectId <= KMS_INDEX_MAX_VM_DYNAMIC_OBJECTS)) { rv = VMS_WRITE_DATA(ObjectId - KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS, ObjectSize, (const uint8_t *)pObjectToAdd); } else { rv = VMS_SLOT_INVALID; } /* A WARNING was generated ==> Not an error */ if ((rv == VMS_NOERROR) || (rv == VMS_WARNING)) { e_ret_status = CKR_OK; } else { e_ret_status = CKR_DEVICE_MEMORY; } KMS_PlatfObjects_VmDynamicObjectList(); return e_ret_status; } /** * @brief Remove object from VM storage * @note Only dynamic objects * @param ObjectId Object ID * @retval CKR_OK if removal is successful * CKR_DEVICE_MEMORY otherwise */ CK_RV KMS_PlatfObjects_VmRemoveObject(uint32_t ObjectId) { vms_error_t rv = VMS_DATA_NOT_FOUND; CK_RV e_ret_status; /* Check that the ObjectID is in dynamic range */ if ((ObjectId >= KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS) && (ObjectId <= KMS_INDEX_MAX_VM_DYNAMIC_OBJECTS)) { rv = VMS_EraseData(ObjectId - KMS_INDEX_MIN_VM_DYNAMIC_OBJECTS); } /* A WARNING was generated ==> Not an error */ if ((rv == VMS_NOERROR) || (rv == VMS_WARNING)) { e_ret_status = CKR_OK; } else { e_ret_status = CKR_DEVICE_MEMORY; } KMS_PlatfObjects_VmDynamicObjectList(); return e_ret_status; } #endif /* KMS_VM_DYNAMIC_ENABLED */ /** * @} */ /** * @} */ /** * @} */ #endif /* KMS_ENABLED */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
31.927966
119
0.698474
[ "object" ]
7fbab979befb31d66759966af17a88ac332c7635
2,275
h
C
content/common/content_param_traits_macros.h
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/common/content_param_traits_macros.h
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/common/content_param_traits_macros.h
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Singly or Multiply-included shared traits file depending on circumstances. // This allows the use of IPC serialization macros in more than one IPC message // file. #ifndef CONTENT_COMMON_CONTENT_PARAM_TRAITS_MACROS_H_ #define CONTENT_COMMON_CONTENT_PARAM_TRAITS_MACROS_H_ #include "components/viz/common/quads/selection.h" #include "content/common/content_export.h" #include "content/common/content_param_traits.h" #include "content/public/common/page_visibility_state.h" #include "ipc/ipc_message_macros.h" #include "services/network/public/mojom/content_security_policy.mojom.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h" #include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/gfx/gpu_memory_buffer.h" #include "ui/gfx/ipc/geometry/gfx_param_traits.h" #include "ui/gfx/ipc/gfx_param_traits.h" #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::RequestContextType, blink::mojom::RequestContextType::kMaxValue) IPC_ENUM_TRAITS_MAX_VALUE(blink::mojom::ResourceType, blink::mojom::ResourceType::kMaxValue) IPC_ENUM_TRAITS_MAX_VALUE( network::mojom::ContentSecurityPolicySource, network::mojom::ContentSecurityPolicySource::kMaxValue) IPC_ENUM_TRAITS_MAX_VALUE(network::mojom::ContentSecurityPolicyType, network::mojom::ContentSecurityPolicyType::kMaxValue) IPC_ENUM_TRAITS_MIN_MAX_VALUE(ui::mojom::CursorType, ui::mojom::CursorType::kNull, ui::mojom::CursorType::kMaxValue) IPC_ENUM_TRAITS_MAX_VALUE(content::PageVisibilityState, content::PageVisibilityState::kMaxValue) IPC_STRUCT_TRAITS_BEGIN(viz::Selection<gfx::SelectionBound>) IPC_STRUCT_TRAITS_MEMBER(start) IPC_STRUCT_TRAITS_MEMBER(end) IPC_STRUCT_TRAITS_END() #endif // CONTENT_COMMON_CONTENT_PARAM_TRAITS_MACROS_H_
46.428571
79
0.770989
[ "geometry" ]
7fbb962d951d710f105022af6076b1986e11dcdf
142
h
C
GalavantUnreal/Source/GalavantUnreal/Utilities/ConversionHelpers.h
makuto/galavant-unreal
08b761953f686695c730efca28f85acfb40693fd
[ "MIT" ]
7
2016-07-04T01:15:38.000Z
2021-05-14T16:27:49.000Z
GalavantUnreal/Source/GalavantUnreal/Utilities/ConversionHelpers.h
makuto/galavant-unreal
08b761953f686695c730efca28f85acfb40693fd
[ "MIT" ]
null
null
null
GalavantUnreal/Source/GalavantUnreal/Utilities/ConversionHelpers.h
makuto/galavant-unreal
08b761953f686695c730efca28f85acfb40693fd
[ "MIT" ]
2
2016-10-20T10:18:33.000Z
2020-07-05T20:50:24.000Z
#pragma once #include "world/Position.hpp" gv::Position ToPosition(const FVector& vector); FVector ToFVector(const gv::Position& position);
20.285714
48
0.774648
[ "vector" ]
7fbf163f24eeac7df912438dba3c91969a44781a
6,265
h
C
src/Outputs.h
dillonhuff/Halide-to-Hardware
16aa65bb147adf5a7aabdc19f96f5fda288a122d
[ "MIT" ]
null
null
null
src/Outputs.h
dillonhuff/Halide-to-Hardware
16aa65bb147adf5a7aabdc19f96f5fda288a122d
[ "MIT" ]
null
null
null
src/Outputs.h
dillonhuff/Halide-to-Hardware
16aa65bb147adf5a7aabdc19f96f5fda288a122d
[ "MIT" ]
1
2019-11-14T04:57:53.000Z
2019-11-14T04:57:53.000Z
#ifndef HALIDE_OUTPUTS_H #define HALIDE_OUTPUTS_H /** \file * * Provides output functions to enable writing out various build * objects from Halide Module objects. */ #include <string> namespace Halide { /** A struct specifying a collection of outputs. Used as an argument * to Pipeline::compile_to and Func::compile_to and Module::compile. */ struct Outputs { /** The name of the emitted object file. Empty if no object file * output is desired. */ std::string object_name; /** The name of the emitted text assembly file. Empty if no * assembly file output is desired. */ std::string assembly_name; /** The name of the emitted llvm bitcode. Empty if no llvm bitcode * output is desired. */ std::string bitcode_name; /** The name of the emitted llvm assembly. Empty if no llvm assembly * output is desired. */ std::string llvm_assembly_name; /** The name of the emitted C header file. Empty if no C header file * output is desired. */ std::string c_header_name; /** The name of the emitted C source file. Empty if no C source file * output is desired. */ std::string c_source_name; /** The name of the emitted CoreIR source file. Empty if no CoreIR source file * output is desired. */ std::string coreir_source_name; /** The name of the emitted Vivado HLS source file. Empty if no Vivado HLS source file * output is desired. */ std::string vhls_source_name; /** The name of the emitted stmt file. Empty if no stmt file * output is desired. */ std::string stmt_name; /** The name of the emitted stmt.html file. Empty if no stmt.html file * output is desired. */ std::string stmt_html_name; /** The name of the emitted static library file. Empty if no static library * output is desired. */ std::string static_library_name; /** The name of the emitted Python extension glue C source file. Empty if no * Python glue output is desired. */ std::string python_extension_name; /** The name of the emitted auto-schedule output file. Empty if no auto-schedule * output is desired. */ std::string schedule_name; /** Make a new Outputs struct that emits everything this one does * and also an object file with the given name. */ Outputs object(const std::string &object_name) const { Outputs updated = *this; updated.object_name = object_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also an assembly file with the given name. */ Outputs assembly(const std::string &assembly_name) const { Outputs updated = *this; updated.assembly_name = assembly_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also an llvm bitcode file with the given name. */ Outputs bitcode(const std::string &bitcode_name) const { Outputs updated = *this; updated.bitcode_name = bitcode_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also an llvm assembly file with the given name. */ Outputs llvm_assembly(const std::string &llvm_assembly_name) const { Outputs updated = *this; updated.llvm_assembly_name = llvm_assembly_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also a C header file with the given name. */ Outputs c_header(const std::string &c_header_name) const { Outputs updated = *this; updated.c_header_name = c_header_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also a C source file with the given name. */ Outputs c_source(const std::string &c_source_name) const { Outputs updated = *this; updated.c_source_name = c_source_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also a CoreIR source file with the given name. */ Outputs coreir_source(const std::string &coreir_source_name) { Outputs updated = *this; updated.coreir_source_name = coreir_source_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also a Vivado HLS source file with the given name. */ Outputs vhls_source(const std::string &vhls_source_name) { Outputs updated = *this; updated.vhls_source_name = vhls_source_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also a stmt file with the given name. */ Outputs stmt(const std::string &stmt_name) const { Outputs updated = *this; updated.stmt_name = stmt_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also a stmt.html file with the given name. */ Outputs stmt_html(const std::string &stmt_html_name) const { Outputs updated = *this; updated.stmt_html_name = stmt_html_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also a static library file with the given name. */ Outputs static_library(const std::string &static_library_name) const { Outputs updated = *this; updated.static_library_name = static_library_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also a Python extension glue C source with the given name. */ Outputs python_extension(const std::string &python_extension_name) const { Outputs updated = *this; updated.python_extension_name = python_extension_name; return updated; } /** Make a new Outputs struct that emits everything this one does * and also an auto-schedule output file with the given name. */ Outputs schedule(const std::string &schedule_name) const { Outputs updated = *this; updated.schedule_name = schedule_name; return updated; } }; } // namespace Halide #endif
35.39548
90
0.671668
[ "object" ]
7fc35d792ed32f8f3fbd8615217a669a87771361
14,577
h
C
Extensions/Editor/Scintilla/include/Platform.h
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
52
2018-09-11T17:18:35.000Z
2022-03-13T15:28:21.000Z
Extensions/Editor/Scintilla/include/Platform.h
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
1,409
2018-09-19T18:03:43.000Z
2021-06-09T08:33:33.000Z
Extensions/Editor/Scintilla/include/Platform.h
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
26
2018-09-11T17:16:32.000Z
2021-11-22T06:21:19.000Z
// Scintilla source code edit control /** @file Platform.h ** Interface to platform facilities. Also includes some basic utilities. ** Implemented in PlatGTK.cxx for GTK+/Linux, PlatWin.cxx for Windows, and PlatWX.cxx for wxWindows. **/ // Copyright 1998-2009 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #ifndef PLATFORM_H #define PLATFORM_H // PLAT_GTK = GTK+ on Linux or Win32 // PLAT_GTK_WIN32 is defined additionally when running PLAT_GTK under Win32 // PLAT_WIN = Win32 API on Win32 OS // PLAT_WX is wxWindows on any supported platform #define PLAT_GTK 0 #define PLAT_GTK_WIN32 0 #define PLAT_GTK_MACOSX 0 #define PLAT_MACOSX 0 #define PLAT_WIN 0 #define PLAT_WX 0 #define PLAT_FOX 0 //Zero is a custom platform since we do not use //any OS features #define PLAT_ZERO 1 #define SCI_NAMESPACE /* All removed #if defined(FOX) #undef PLAT_FOX #define PLAT_FOX 1 #elif defined(__WX__) #undef PLAT_WX #define PLAT_WX 1 #elif defined(GTK) #undef PLAT_GTK #define PLAT_GTK 1 #if defined(__WIN32__) || defined(_MSC_VER) #undef PLAT_GTK_WIN32 #define PLAT_GTK_WIN32 1 #endif #if defined(__APPLE__) #undef PLAT_GTK_MACOSX #define PLAT_GTK_MACOSX 1 #endif #elif defined(__APPLE__) #undef PLAT_MACOSX #define PLAT_MACOSX 1 #else #undef PLAT_WIN #define PLAT_WIN 1 #endif */ #ifdef SCI_NAMESPACE namespace Scintilla { #endif typedef float XYPOSITION; typedef double XYACCUMULATOR; //#define XYPOSITION int // Underlying the implementation of the platform classes are platform specific types. // Sometimes these need to be passed around by client code so they are defined here typedef void *FontID; typedef void *SurfaceID; typedef void *WindowID; typedef void *MenuID; typedef void *TickerID; typedef void *Function; typedef void *IdlerID; /** * A geometric point class. * Point is exactly the same as the Win32 POINT and GTK+ GdkPoint so can be used interchangeably. */ class Point { public: XYPOSITION x; XYPOSITION y; explicit Point(XYPOSITION x_=0, XYPOSITION y_=0) : x(x_), y(y_) { } // Other automatically defined methods (assignment, copy constructor, destructor) are fine static Point FromLong(long lpoint); }; /** * A geometric rectangle class. * PRectangle is exactly the same as the Win32 RECT so can be used interchangeably. * PRectangles contain their top and left sides, but not their right and bottom sides. */ class PRectangle { public: XYPOSITION left; XYPOSITION top; XYPOSITION right; XYPOSITION bottom; PRectangle(XYPOSITION left_=0, XYPOSITION top_=0, XYPOSITION right_=0, XYPOSITION bottom_ = 0) : left(left_), top(top_), right(right_), bottom(bottom_) { } // Other automatically defined methods (assignment, copy constructor, destructor) are fine bool operator==(PRectangle &rc) { return (rc.left == left) && (rc.right == right) && (rc.top == top) && (rc.bottom == bottom); } bool Contains(Point pt) { return (pt.x >= left) && (pt.x <= right) && (pt.y >= top) && (pt.y <= bottom); } bool Contains(PRectangle rc) { return (rc.left >= left) && (rc.right <= right) && (rc.top >= top) && (rc.bottom <= bottom); } bool Intersects(PRectangle other) { return (right > other.left) && (left < other.right) && (bottom > other.top) && (top < other.bottom); } void Move(XYPOSITION xDelta, XYPOSITION yDelta) { left += xDelta; top += yDelta; right += xDelta; bottom += yDelta; } XYPOSITION Width() { return right - left; } XYPOSITION Height() { return bottom - top; } bool Empty() { return (Height() <= 0) || (Width() <= 0); } }; /** * Holds a desired RGB colour. */ class ColourDesired { long co; public: ColourDesired(long lcol=0) { co = lcol; } ColourDesired(unsigned int red, unsigned int green, unsigned int blue) { Set(red, green, blue); } bool operator==(const ColourDesired &other) const { return co == other.co; } void Set(long lcol) { co = lcol; } void Set(unsigned int red, unsigned int green, unsigned int blue) { co = red | (green << 8) | (blue << 16); } static inline unsigned int ValueOfHex(const char ch) { if (ch >= '0' && ch <= '9') return ch - '0'; else if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10; else if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; else return 0; } void Set(const char *val) { if (*val == '#') { val++; } unsigned int r = ValueOfHex(val[0]) * 16 + ValueOfHex(val[1]); unsigned int g = ValueOfHex(val[2]) * 16 + ValueOfHex(val[3]); unsigned int b = ValueOfHex(val[4]) * 16 + ValueOfHex(val[5]); Set(r, g, b); } long AsLong() const { return co; } unsigned int GetRed() { return co & 0xff; } unsigned int GetGreen() { return (co >> 8) & 0xff; } unsigned int GetBlue() { return (co >> 16) & 0xff; } }; /** * Font management. */ struct FontParameters { const char *faceName; float size; int weight; bool italic; int extraFontFlag; int technology; int characterSet; FontParameters( const char *faceName_, float size_=10, int weight_=400, bool italic_=false, int extraFontFlag_=0, int technology_=0, int characterSet_=0) : faceName(faceName_), size(size_), weight(weight_), italic(italic_), extraFontFlag(extraFontFlag_), technology(technology_), characterSet(characterSet_) { } }; class Font { protected: FontID fid; #if PLAT_WX int ascent; #endif // Private so Font objects can not be copied Font(const Font &); Font &operator=(const Font &); public: Font(); virtual ~Font(); virtual void Create(const FontParameters &fp); virtual void Release(); FontID GetID() { return fid; } // Alias another font - caller guarantees not to Release void SetID(FontID fid_) { fid = fid_; } #if PLAT_WX void SetAscent(int ascent_) { ascent = ascent_; } #endif friend class Surface; friend class SurfaceImpl; }; /** * A surface abstracts a place to draw. */ class Surface { private: // Private so Surface objects can not be copied Surface(const Surface &) {} Surface &operator=(const Surface &) { return *this; } public: Surface() {} virtual ~Surface() {} static Surface *Allocate(int technology); virtual void Init(WindowID wid)=0; virtual void Init(SurfaceID sid, WindowID wid)=0; virtual void InitPixMap(int width, int height, Surface *surface_, WindowID wid)=0; virtual void Release()=0; virtual bool Initialised()=0; virtual void PenColour(ColourDesired fore)=0; virtual int LogPixelsY()=0; virtual int DeviceHeightFont(int points)=0; virtual void MoveTo(int x_, int y_)=0; virtual void LineTo(int x_, int y_)=0; virtual void Polygon(Point *pts, int npts, ColourDesired fore, ColourDesired back)=0; virtual void RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back)=0; virtual void FillRectangle(PRectangle rc, ColourDesired back)=0; virtual void FillRectangle(PRectangle rc, Surface &surfacePattern)=0; virtual void RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back)=0; virtual void AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill, ColourDesired outline, int alphaOutline, int flags)=0; virtual void DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage) = 0; virtual void Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back)=0; virtual void Copy(PRectangle rc, Point from, Surface &surfaceSource)=0; virtual void DrawTextNoClip(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired fore, ColourDesired back)=0; virtual void DrawTextClipped(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired fore, ColourDesired back)=0; virtual void DrawTextTransparent(PRectangle rc, Font &font_, XYPOSITION ybase, const char *s, int len, ColourDesired fore)=0; virtual void MeasureWidths(Font &font_, const char *s, int len, XYPOSITION *positions)=0; virtual XYPOSITION WidthText(Font &font_, const char *s, int len)=0; virtual XYPOSITION WidthChar(Font &font_, char ch)=0; virtual XYPOSITION Ascent(Font &font_)=0; virtual XYPOSITION Descent(Font &font_)=0; virtual XYPOSITION InternalLeading(Font &font_)=0; virtual XYPOSITION ExternalLeading(Font &font_)=0; virtual XYPOSITION Height(Font &font_)=0; virtual XYPOSITION AverageCharWidth(Font &font_)=0; virtual void SetClip(PRectangle rc)=0; virtual void FlushCachedState()=0; virtual void SetUnicodeMode(bool unicodeMode_)=0; virtual void SetDBCSMode(int codePage)=0; }; /** * A simple callback action passing one piece of untyped user data. */ typedef void (*CallBackAction)(void*); /** * Class to hide the details of window manipulation. * Does not own the window which will normally have a longer life than this object. */ class Window { protected: WindowID wid; #if PLAT_MACOSX void *windowRef; void *control; #endif public: Window() : wid(0), cursorLast(cursorInvalid) { #if PLAT_MACOSX windowRef = 0; control = 0; #endif } Window(const Window &source) : wid(source.wid), cursorLast(cursorInvalid) { #if PLAT_MACOSX windowRef = 0; control = 0; #endif } virtual ~Window(); Window &operator=(WindowID wid_) { wid = wid_; return *this; } WindowID GetID() const { return wid; } bool Created() const { return wid != 0; } void Destroy(); bool HasFocus(); PRectangle GetPosition(); void SetPosition(PRectangle rc); void SetPositionRelative(PRectangle rc, Window relativeTo); PRectangle GetClientPosition(); void Show(bool show=true); void InvalidateAll(); void InvalidateRectangle(PRectangle rc); virtual void SetFont(Font &font); enum Cursor { cursorInvalid, cursorText, cursorArrow, cursorUp, cursorWait, cursorHoriz, cursorVert, cursorReverseArrow, cursorHand }; void SetCursor(Cursor curs); void SetTitle(const char *s); PRectangle GetMonitorRect(Point pt); #if PLAT_MACOSX void SetWindow(void *ref) { windowRef = ref; } void SetControl(void *_control) { control = _control; } #endif private: Cursor cursorLast; }; /** * Listbox management. */ class ListBox : public Window { public: ListBox(); virtual ~ListBox(); static ListBox *Allocate(); virtual void SetFont(Font &font)=0; virtual void Create(Window &parent, int ctrlID, Point location, int lineHeight_, bool unicodeMode_, int technology_)=0; virtual void SetAverageCharWidth(int width)=0; virtual void SetVisibleRows(int rows)=0; virtual int GetVisibleRows() const=0; virtual PRectangle GetDesiredRect()=0; virtual int CaretFromEdge()=0; virtual void Clear()=0; virtual void Append(char *s, int type = -1)=0; virtual int Length()=0; virtual void Select(int n)=0; virtual int GetSelection()=0; virtual int Find(const char *prefix)=0; virtual void GetValue(int n, char *value, int len)=0; virtual void RegisterImage(int type, const char *xpm_data)=0; virtual void RegisterRGBAImage(int type, int width, int height, const unsigned char *pixelsImage) = 0; virtual void ClearRegisteredImages()=0; virtual void SetDoubleClickAction(CallBackAction, void *)=0; virtual void SetList(const char* list, char separator, char typesep)=0; }; /** * Menu management. */ class Menu { MenuID mid; public: Menu(); MenuID GetID() { return mid; } void CreatePopUp(); void Destroy(); void Show(Point pt, Window &w); }; class ElapsedTime { long bigBit; long littleBit; public: ElapsedTime(); double Duration(bool reset=false); }; /** * Dynamic Library (DLL/SO/...) loading */ class DynamicLibrary { public: virtual ~DynamicLibrary() {} /// @return Pointer to function "name", or NULL on failure. virtual Function FindFunction(const char *name) = 0; /// @return true if the library was loaded successfully. virtual bool IsValid() = 0; /// @return An instance of a DynamicLibrary subclass with "modulePath" loaded. static DynamicLibrary *Load(const char *modulePath); }; /** * Platform class used to retrieve system wide parameters such as double click speed * and chrome colour. Not a creatable object, more of a module with several functions. */ class Platform { // Private so Platform objects can not be copied Platform(const Platform &) {} Platform &operator=(const Platform &) { return *this; } public: // Should be private because no new Platforms are ever created // but gcc warns about this Platform() {} ~Platform() {} static ColourDesired Chrome(); static ColourDesired ChromeHighlight(); static const char *DefaultFont(); static int DefaultFontSize(); static unsigned int DoubleClickTime(); static bool MouseButtonBounce(); static void DebugDisplay(const char *s); static bool IsKeyDown(int key); static long SendScintilla( WindowID w, unsigned int msg, unsigned long wParam=0, long lParam=0); static long SendScintillaPointer( WindowID w, unsigned int msg, unsigned long wParam=0, void *lParam=0); static bool IsDBCSLeadByte(int codePage, char ch); static int DBCSCharLength(int codePage, const char *s); static int DBCSCharMaxLength(); // These are utility functions not really tied to a platform static int Minimum(int a, int b); static int Maximum(int a, int b); // Next three assume 16 bit shorts and 32 bit longs static long LongFromTwoShorts(short a,short b) { return (a) | ((b) << 16); } static short HighShortFromLong(long x) { return static_cast<short>(x >> 16); } static short LowShortFromLong(long x) { return static_cast<short>(x & 0xffff); } static void DebugPrintf(const char *format, ...); static bool ShowAssertionPopUps(bool assertionPopUps_); static void Assertion(const char *c, const char *file, int line); static int Clamp(int val, int minVal, int maxVal); }; #ifdef NDEBUG #define PLATFORM_ASSERT(c) ((void)0) #else #ifdef SCI_NAMESPACE #define PLATFORM_ASSERT(c) ((c) ? (void)(0) : Scintilla::Platform::Assertion(#c, __FILE__, __LINE__)) #else #define PLATFORM_ASSERT(c) ((c) ? (void)(0) : Platform::Assertion(#c, __FILE__, __LINE__)) #endif #endif #ifdef SCI_NAMESPACE } #endif // Shut up annoying Visual C++ warnings: #ifdef _MSC_VER #pragma warning(disable: 4244 4309 4514 4710) #endif #endif
27.925287
143
0.69445
[ "object" ]
7fc3d689981136418c2f2620f471e1488f8c8e85
6,731
c
C
src/other/ext/stepcode/src/express/schema.c
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
83
2021-03-10T05:54:52.000Z
2022-03-31T16:33:46.000Z
src/other/ext/stepcode/src/express/schema.c
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
13
2021-06-24T17:07:48.000Z
2022-03-31T15:31:33.000Z
src/other/ext/stepcode/src/express/schema.c
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
54
2021-03-10T07:57:06.000Z
2022-03-28T23:20:37.000Z
/** ********************************************************************** ** Module: Schema \file schema.c ** This module implements the Schema abstraction, which ** basically amounts to a named symbol table. ** Constants: ** SCHEMA_NULL - the null schema ** ************************************************************************/ /* * This code was developed with the support of the United States Government, * and is not subject to copyright. * * $Log: schema.c,v $ * Revision 1.13 1997/01/21 19:19:51 dar * made C++ compatible * * Revision 1.12 1995/06/08 22:59:59 clark * bug fixes * * Revision 1.11 1995/04/05 13:55:40 clark * CADDETC preval * * Revision 1.10 1994/11/10 19:20:03 clark * Update to IS * * Revision 1.9 1993/10/15 18:48:48 libes * CADDETC certified * * Revision 1.8 1993/02/22 21:48:53 libes * removed old ifdeffed code * * Revision 1.7 1993/01/19 22:16:43 libes * *** empty log message *** * * Revision 1.6 1992/08/27 23:42:20 libes * *** empty log message *** * * Revision 1.5 1992/08/18 17:13:43 libes * rm'd extraneous error messages * * Revision 1.4 1992/06/08 18:06:57 libes * prettied up interface to print_objects_when_running */ #include "express/expbasic.h" #include "express/schema.h" #include "express/object.h" #include "express/resolve.h" int __SCOPE_search_id = 0; /** Initialize the Schema module. */ void SCHEMAinitialize(void) { } /** SCHEMAget_name ** \param schema schema to examine ** \return schema name ** Retrieve the name of a schema. ** \note This function is implemented as a macro in schema.h */ #if 0 /** \fn SCHEMAdump ** \param schema schema to dump ** \param file file to dump to ** Dump a schema to a file. ** \note This function is provided for debugging purposes. */ void SCHEMAdump(Schema schema, FILE *file) { fprintf(file, "SCHEMA %s:\n", SCHEMAget_name(schema)); SCOPEdump(schema, file); fprintf(file, "END SCHEMA %s\n\n", SCHEMAget_name(schema)); } #endif #if 0 SYMBOLprint(Symbol *s) { fprintf(stderr, "%s (r:%d #:%d f:%s)\n", s->name, s->resolved, s->line, s->filename); } #endif void SCHEMAadd_reference(Schema cur_schema, Symbol *ref_schema, Symbol *old, Symbol *snnew) { Rename *r = REN_new(); r->schema_sym = ref_schema; r->old = old; r->nnew = snnew; r->rename_type = ref; if(!cur_schema->u.schema->reflist) { cur_schema->u.schema->reflist = LISTcreate(); } LISTadd_last(cur_schema->u.schema->reflist, r); } void SCHEMAadd_use(Schema cur_schema, Symbol *ref_schema, Symbol *old, Symbol *snnew) { Rename *r = REN_new(); r->schema_sym = ref_schema; r->old = old; r->nnew = snnew; r->rename_type = use; if(!cur_schema->u.schema->uselist) { cur_schema->u.schema->uselist = LISTcreate(); } LISTadd_last(cur_schema->u.schema->uselist, r); } void SCHEMAdefine_reference(Schema schema, Rename *r) { Rename *old = 0; char *name = (r->nnew ? r->nnew : r->old)->name; if(!schema->u.schema->refdict) { schema->u.schema->refdict = DICTcreate(20); } else { old = (Rename *)DICTlookup(schema->u.schema->refdict, name); } if(!old || (DICT_type != OBJ_RENAME) || (old->object != r->object)) { DICTdefine(schema->u.schema->refdict, name, r, r->old, OBJ_RENAME); } } void SCHEMAdefine_use(Schema schema, Rename *r) { Rename *old = 0; char *name = (r->nnew ? r->nnew : r->old)->name; if(!schema->u.schema->usedict) { schema->u.schema->usedict = DICTcreate(20); } else { old = (Rename *)DICTlookup(schema->u.schema->usedict, name); } if(!old || (DICT_type != OBJ_RENAME) || (old->object != r->object)) { DICTdefine(schema->u.schema->usedict, name, r, r->old, OBJ_RENAME); } } static void SCHEMA_get_entities_use(Scope scope, Linked_List result) { DictionaryEntry de; Rename *rename; if(scope->search_id == __SCOPE_search_id) { return; } scope->search_id = __SCOPE_search_id; /* fully USE'd schema */ LISTdo(scope->u.schema->use_schemas, schema, Schema) SCOPE_get_entities(schema, result); SCHEMA_get_entities_use(schema, result); LISTod /* partially USE'd schema */ if(scope->u.schema->usedict) { DICTdo_init(scope->u.schema->usedict, &de); while(0 != (rename = (Rename *)DICTdo(&de))) { LISTadd_last(result, rename->object); } } } /** return use'd entities */ Linked_List SCHEMAget_entities_use(Scope scope) { Linked_List result = LISTcreate(); __SCOPE_search_id++; ENTITY_MARK++; SCHEMA_get_entities_use(scope, result); return(result); } /** return ref'd entities */ void SCHEMA_get_entities_ref(Scope scope, Linked_List result) { Rename *rename; DictionaryEntry de; if(scope->search_id == __SCOPE_search_id) { return; } scope->search_id = __SCOPE_search_id; ENTITY_MARK++; /* fully REF'd schema */ LISTdo(scope->u.schema->ref_schemas, schema, Schema) SCOPE_get_entities(schema, result); /* don't go down remote schema's ref_schemas */ LISTod /* partially REF'd schema */ DICTdo_init(scope->u.schema->refdict, &de); while(0 != (rename = (Rename *)DICTdo(&de))) { if(DICT_type == OBJ_ENTITY) { LISTadd_last(result, rename->object); } } } /** return ref'd entities */ Linked_List SCHEMAget_entities_ref(Scope scope) { Linked_List result = LISTcreate(); __SCOPE_search_id++; ENTITY_MARK++; SCHEMA_get_entities_ref(scope, result); return(result); } /** * look up an attribute reference * if strict false, anything can be returned, not just attributes */ Variable VARfind(Scope scope, char *name, int strict) { Variable result; /* first look up locally */ switch(scope->type) { case OBJ_ENTITY: result = ENTITYfind_inherited_attribute(scope, name, 0); if(result) { if(strict && (DICT_type != OBJ_VARIABLE)) { fprintf(stderr, "ERROR: strict && ( DICT_type != OBJ_VARIABLE )\n"); } return result; } break; case OBJ_INCREMENT: case OBJ_QUERY: case OBJ_ALIAS: result = (Variable)DICTlookup(scope->symbol_table, name); if(result) { if(strict && (DICT_type != OBJ_VARIABLE)) { fprintf(stderr, "ERROR: strict && ( DICT_type != OBJ_VARIABLE )\n"); } return result; } return(VARfind(scope->superscope, name, strict)); } return 0; }
25.69084
91
0.604516
[ "object" ]
7fcbb79067ab2fb84fe66f9af862e28f745dfb6d
6,833
h
C
firestore/src/ios/query_ios.h
bibinsyamnath/firebase-cpp-sdk
c3c8807659504460dcdf361bba30278d4971b6a6
[ "Apache-2.0" ]
null
null
null
firestore/src/ios/query_ios.h
bibinsyamnath/firebase-cpp-sdk
c3c8807659504460dcdf361bba30278d4971b6a6
[ "Apache-2.0" ]
null
null
null
firestore/src/ios/query_ios.h
bibinsyamnath/firebase-cpp-sdk
c3c8807659504460dcdf361bba30278d4971b6a6
[ "Apache-2.0" ]
null
null
null
#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_QUERY_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_QUERY_IOS_H_ #include <cstdint> #include <vector> #include "Firestore/core/src/api/query_core.h" #include "Firestore/core/src/core/bound.h" #include "Firestore/core/src/core/order_by.h" #include "Firestore/core/src/core/query.h" #include "firestore/src/include/firebase/firestore/field_path.h" #include "firestore/src/include/firebase/firestore/query.h" #include "firestore/src/ios/firestore_ios.h" #include "firestore/src/ios/promise_factory_ios.h" #include "firestore/src/ios/user_data_converter_ios.h" namespace firebase { namespace firestore { class Firestore; class QueryInternal { public: explicit QueryInternal(api::Query&& query); virtual ~QueryInternal() = default; Firestore* firestore(); FirestoreInternal* firestore_internal(); const FirestoreInternal* firestore_internal() const; Query OrderBy(const FieldPath& field, Query::Direction direction) const; Query Limit(int32_t limit) const; Query LimitToLast(int32_t limit) const; virtual Future<QuerySnapshot> Get(Source source); ListenerRegistration AddSnapshotListener( MetadataChanges metadata_changes, EventListener<QuerySnapshot>* listener); ListenerRegistration AddSnapshotListener( MetadataChanges metadata_changes, std::function<void(const QuerySnapshot&, Error, const std::string&)> callback); // Delegating methods Query WhereEqualTo(const FieldPath& field, const FieldValue& value) const { return Where(field, Operator::Equal, value); } Query WhereNotEqualTo(const FieldPath& field, const FieldValue& value) const { return Where(field, Operator::NotEqual, value); } Query WhereLessThan(const FieldPath& field, const FieldValue& value) const { return Where(field, Operator::LessThan, value); } Query WhereLessThanOrEqualTo(const FieldPath& field, const FieldValue& value) const { return Where(field, Operator::LessThanOrEqual, value); } Query WhereGreaterThan(const FieldPath& field, const FieldValue& value) const { return Where(field, Operator::GreaterThan, value); } Query WhereGreaterThanOrEqualTo(const FieldPath& field, const FieldValue& value) const { return Where(field, Operator::GreaterThanOrEqual, value); } Query WhereArrayContains(const FieldPath& field, const FieldValue& value) const { return Where(field, Operator::ArrayContains, value); } Query WhereArrayContainsAny(const FieldPath& field, const std::vector<FieldValue>& values) const { return Where(field, Operator::ArrayContainsAny, values); } Query WhereIn(const FieldPath& field, const std::vector<FieldValue>& values) const { return Where(field, Operator::In, values); } Query WhereNotIn(const FieldPath& field, const std::vector<FieldValue>& values) const { return Where(field, Operator::NotIn, values); } Query StartAt(const DocumentSnapshot& snapshot) const { return WithBound(BoundPosition::kStartAt, snapshot); } Query StartAt(const std::vector<FieldValue>& values) const { return WithBound(BoundPosition::kStartAt, values); } Query StartAfter(const DocumentSnapshot& snapshot) const { return WithBound(BoundPosition::kStartAfter, snapshot); } Query StartAfter(const std::vector<FieldValue>& values) const { return WithBound(BoundPosition::kStartAfter, values); } Query EndBefore(const DocumentSnapshot& snapshot) const { return WithBound(BoundPosition::kEndBefore, snapshot); } Query EndBefore(const std::vector<FieldValue>& values) const { return WithBound(BoundPosition::kEndBefore, values); } Query EndAt(const DocumentSnapshot& snapshot) const { return WithBound(BoundPosition::kEndAt, snapshot); } Query EndAt(const std::vector<FieldValue>& values) const { return WithBound(BoundPosition::kEndAt, values); } friend bool operator==(const QueryInternal& lhs, const QueryInternal& rhs); protected: enum class AsyncApis { kGet, // Important: `Query` and `CollectionReference` use the same // `PromiseFactory`. That is because the most natural thing to register and // unregister objects in a `FutureManager` (contained within the // `PromiseFactory`) is using the `this` pointer; however, due to // inheritance, `Query` and `CollectionReference` are pretty much guaranteed // to have the same `this` pointer. Consequently, if both were to have their // own `PromiseFactory`, they would either clash when registering, leading // to incorrect behavior, or have to come up with some other kind of // a handle unique to each object. // // `Query`, being the base object, is created before the // `CollectionReference` part, and destroyed after the `CollectionReference` // part; therefore, the `PromiseFactory` is guaranteed to be alive as long // as a `CollectionReference` is alive. kCollectionReferenceAdd, kCount, }; const api::Query& query_core_api() const { return query_; } const UserDataConverter& converter() const { return user_data_converter_; } PromiseFactory<AsyncApis>& promise_factory() { return promise_factory_; } private: enum class BoundPosition { kStartAt, kStartAfter, kEndBefore, kEndAt, }; using Operator = core::Filter::Operator; Query Where(const FieldPath& field, Operator op, const FieldValue& value) const; Query Where(const FieldPath& field, Operator op, const std::vector<FieldValue>& values) const; Query WithBound(BoundPosition bound_pos, const DocumentSnapshot& snapshot) const; Query WithBound(BoundPosition bound_pos, const std::vector<FieldValue>& values) const; model::FieldValue ConvertDocumentId(const model::FieldValue& from, const core::Query& internal_query) const; static bool IsBefore(BoundPosition bound_pos); core::Bound ToBound(BoundPosition bound_pos, const DocumentSnapshot& public_snapshot) const; core::Bound ToBound(BoundPosition bound_pos, const std::vector<FieldValue>& field_values) const; api::Query CreateQueryWithBound(BoundPosition bound_pos, core::Bound&& bound) const; api::Query query_; PromiseFactory<AsyncApis> promise_factory_; UserDataConverter user_data_converter_; }; inline bool operator!=(const QueryInternal& lhs, const QueryInternal& rhs) { return !(lhs == rhs); } } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_QUERY_IOS_H_
34.510101
80
0.711693
[ "object", "vector", "model" ]
7fcbbe16988f1aadef861a67a88d804901c64311
2,018
h
C
FundamentalStructures/DoublyLinkedListQueue.h
pdvnny/DataStructures-Algorithms
9c1adbb77126011274129715c1ba589317d4479c
[ "Apache-2.0" ]
null
null
null
FundamentalStructures/DoublyLinkedListQueue.h
pdvnny/DataStructures-Algorithms
9c1adbb77126011274129715c1ba589317d4479c
[ "Apache-2.0" ]
null
null
null
FundamentalStructures/DoublyLinkedListQueue.h
pdvnny/DataStructures-Algorithms
9c1adbb77126011274129715c1ba589317d4479c
[ "Apache-2.0" ]
null
null
null
/*********************************************** Parker Dunn Related to EC 504 - SW HW 4 Created April 6th, 2022 ***********************************************/ // How to use typedef struct --> https://www.educative.io/edpresso/how-to-use-the-typedef-struct-in-c template <class Data> class Node { public: // int key; // could be current position of the node in the LL (probably inefficient to deal with) Node* next; Node* prev; Data* data_structure; }; template <class Data> class myQueue { private: Node<Data>* head; Node<Data>* tail; int size; public: Data* front() { return head->data_structure; }; int getSize() { return size; }; bool empty() { return (size < 1); }; myQueue() { this->size = 0; this->head = nullptr; this->tail = nullptr; }; ~myQueue() { /// Delete any remaining elements in the queue if it is not empty if (size > 0) { while (this->head) { Node<Data>* toDel = this->head; this->head = this->head->next; delete toDel; } } }; void push(Data* newData) { /// Create new node Node<Data>* newNode = new Node<Data>; newNode->next = nullptr; newNode->prev = nullptr; newNode->data_structure = newData; if (this->size <= 0) { /// need to do some initial stuff on first push this->head = newNode; this->tail = newNode; } else { // not empty queue ... do normal push // add to end and update size and tail of class this->tail->next = newNode; newNode->prev = this->tail; this->tail = newNode; } this->size++; }; void pop() { Node<Data>* toDel = this->head; /// update head this->head = this->head->next; this->size--; if (this->head) this->head->prev = nullptr; // updating new head's "prev" pointer to point to null /// don't think I need any special considerations for deleting last node /// delete the removed node delete toDel; } /**** OTHER OPTIONS **** void pop_back(); Node* find(int key - would have to be in the data object); ************************/ };
21.020833
101
0.59217
[ "object" ]
7fcc5f477a665128c01e1ff77b05ea2a948c8a15
16,406
h
C
src/include/utils/plancache.h
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
null
null
null
src/include/utils/plancache.h
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
null
null
null
src/include/utils/plancache.h
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
null
null
null
/* ------------------------------------------------------------------------- * * plancache.h * Plan cache definitions. * * See plancache.c for comments. * * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/utils/plancache.h * * ------------------------------------------------------------------------- */ #ifndef PLANCACHE_H #define PLANCACHE_H #include "access/tupdesc.h" #include "nodes/params.h" #include "utils/atomic.h" #ifdef PGXC #include "pgxc/locator.h" #include "nodes/plannodes.h" #endif #ifdef ENABLE_MOT // forward declaration for MOT JitContext namespace JitExec { struct JitContext; } #endif #define CACHEDPLANSOURCE_MAGIC 195726186 #define CACHEDPLAN_MAGIC 953717834 #ifdef ENABLE_MOT /* different storage engine types that might be used by a query */ typedef enum { SE_TYPE_UNSPECIFIED = 0, /* unspecified storage engine */ SE_TYPE_MOT, /* MOT storage engine */ SE_TYPE_PAGE_BASED, /* Page Based storage engine */ SE_TYPE_MIXED /* Mixed (MOT & Page Based) storage engines */ } StorageEngineType; #endif /* possible values for plan_cache_mode */ typedef enum { PLAN_CACHE_MODE_AUTO, PLAN_CACHE_MODE_FORCE_GENERIC_PLAN, PLAN_CACHE_MODE_FORCE_CUSTOM_PLAN } PlanCacheMode; typedef enum { GPC_PRIVATE, GPC_SHARED, GPC_CPLAN, // generate cplan GPC_UNSHARED, // not satisfied share condition, like stream plan } GPCSourceKind; typedef enum { GPC_SHARE_IN_LOCAL_SAVE_PLAN_LIST, GPC_SHARE_IN_LOCAL_UNGPC_PLAN_LIST, // contains GPC_PRIVATE, GPC_UNSHARED and GPC_CPLAN plancache GPC_SHARE_IN_PREPARE_STATEMENT, GPC_SHARE_IN_SHARE_TABLE, GPC_SHARE_IN_SHARE_TABLE_INVALID_LIST, } GPCSourceSharedLoc; typedef enum { GPC_VALID, GPC_INVALID, } GPCSourceSharedStatus; class GPCPlanStatus { public: GPCPlanStatus() { m_kind = GPC_PRIVATE; m_location = GPC_SHARE_IN_PREPARE_STATEMENT; m_status = GPC_VALID; m_refcount = 0; } inline void ShareInit() { m_kind = GPC_SHARED; m_location = GPC_SHARE_IN_PREPARE_STATEMENT; m_status = GPC_VALID; m_refcount = 0; } // NOTE: can not reset to GPC_PRIVATE inline void SetKind(GPCSourceKind kind) { Assert(kind != GPC_PRIVATE); pg_memory_barrier(); m_kind = kind; } inline void SetLoc(GPCSourceSharedLoc location) { pg_memory_barrier(); m_location = location; } inline void SetStatus(GPCSourceSharedStatus status) { pg_memory_barrier(); m_status = status; } inline bool IsPrivatePlan() { pg_memory_barrier(); return m_kind == GPC_PRIVATE; } inline bool IsSharePlan() { pg_memory_barrier(); return m_kind == GPC_SHARED; } inline bool IsUnSharedPlan() { pg_memory_barrier(); return m_kind == GPC_UNSHARED; } inline bool IsUnShareCplan() { pg_memory_barrier(); return m_kind == GPC_CPLAN; } inline bool InSavePlanList(GPCSourceKind kind) { pg_memory_barrier(); return m_kind == kind && m_location == GPC_SHARE_IN_LOCAL_SAVE_PLAN_LIST; } inline bool InUngpcPlanList() { pg_memory_barrier(); return (m_kind != GPC_SHARED) && m_location == GPC_SHARE_IN_LOCAL_UNGPC_PLAN_LIST; } inline bool InPrepareStmt() { pg_memory_barrier(); return m_location == GPC_SHARE_IN_PREPARE_STATEMENT; } inline bool InShareTable() { pg_memory_barrier(); return m_kind == GPC_SHARED && (m_location == GPC_SHARE_IN_SHARE_TABLE || m_location == GPC_SHARE_IN_SHARE_TABLE_INVALID_LIST); } inline bool InShareTableInvalidList() { pg_memory_barrier(); return (m_kind == GPC_SHARED && m_location == GPC_SHARE_IN_SHARE_TABLE_INVALID_LIST); } inline bool IsValid() { pg_memory_barrier(); return m_status == GPC_VALID; } inline bool NeedDropSharedGPC() { Assert (m_kind == GPC_SHARED); pg_memory_barrier(); return m_location == GPC_SHARE_IN_SHARE_TABLE && m_status == GPC_INVALID; } inline void AddRefcount() { pg_atomic_fetch_add_u32((volatile uint32*)&m_refcount, 1); } inline void SubRefCount() { pg_atomic_fetch_sub_u32((volatile uint32*)&m_refcount, 1); } /* this check function can only be used to change gpc table when has write lock */ inline bool RefCountZero() { /* if is same as 0 then set 0 and return true, if is different then do nothing and return false */ uint32 expect = 0; return pg_atomic_compare_exchange_u32((volatile uint32*)&m_refcount, &expect, 0); } inline int GetRefCount() { return m_refcount; } private: volatile GPCSourceKind m_kind; volatile GPCSourceSharedLoc m_location; volatile GPCSourceSharedStatus m_status; volatile int m_refcount; }; typedef struct GPCSource { GPCPlanStatus status; struct GPCKey* key; //remember when we generate the plan. } GPCSource; typedef struct SPISign { uint32 spi_key; /* hash value of PLpgSQL_function's fn_hashkey */ Oid func_oid; uint32 spi_id; /* spi idx to PLpgSQL_expr, same as plansource's spi_id */ int plansource_id; /* plansource idx in spiplan's plancache_list */ } SPISign; /* * CachedPlanSource (which might better have been called CachedQuery) * represents a SQL query that we expect to use multiple times. It stores * the query source text, the raw parse tree, and the analyzed-and-rewritten * query tree, as well as adjunct data. Cache invalidation can happen as a * result of DDL affecting objects used by the query. In that case we discard * the analyzed-and-rewritten query tree, and rebuild it when next needed. * * An actual execution plan, represented by CachedPlan, is derived from the * CachedPlanSource when we need to execute the query. The plan could be * either generic (usable with any set of plan parameters) or custom (for a * specific set of parameters). plancache.c contains the logic that decides * which way to do it for any particular execution. If we are using a generic * cached plan then it is meant to be re-used across multiple executions, so * callers must always treat CachedPlans as read-only. * * Once successfully built and "saved", CachedPlanSources typically live * for the life of the backend, although they can be dropped explicitly. * CachedPlans are reference-counted and go away automatically when the last * reference is dropped. A CachedPlan can outlive the CachedPlanSource it * was created from. * * An "unsaved" CachedPlanSource can be used for generating plans, but it * lives in transient storage and will not be updated in response to sinval * events. * * CachedPlans made from saved CachedPlanSources are likewise in permanent * storage, so to avoid memory leaks, the reference-counted references to them * must be held in permanent data structures or ResourceOwners. CachedPlans * made from unsaved CachedPlanSources are in children of the caller's * memory context, so references to them should not be longer-lived than * that context. (Reference counting is somewhat pro forma in that case, * though it may be useful if the CachedPlan can be discarded early.) * * A CachedPlanSource has two associated memory contexts: one that holds the * struct itself, the query source text and the raw parse tree, and another * context that holds the rewritten query tree and associated data. This * allows the query tree to be discarded easily when it is invalidated. * * Some callers wish to use the CachedPlan API even with one-shot queries * that have no reason to be saved at all. We therefore support a "oneshot" * variant that does no data copying or invalidation checking. In this case * there are no separate memory contexts: the CachedPlanSource struct and * all subsidiary data live in the caller's CurrentMemoryContext, and there * is no way to free memory short of clearing that entire context. A oneshot * plan is always treated as unsaved. * * Note: the string referenced by commandTag is not subsidiary storage; * it is assumed to be a compile-time-constant string. As with portals, * commandTag shall be NULL if and only if the original query string (before * rewriting) was an empty string. */ typedef struct CachedPlanSource { int magic; /* should equal CACHEDPLANSOURCE_MAGIC */ Node* raw_parse_tree; /* output of raw_parser() */ const char* query_string; /* source text of query */ const char* commandTag; /* command tag (a constant!), or NULL */ Oid* param_types; /* array of parameter type OIDs, or NULL */ int num_params; /* length of param_types array */ ParserSetupHook parserSetup; /* alternative parameter spec method */ void* parserSetupArg; int cursor_options; /* cursor options used for planning */ Oid rewriteRoleId; /* Role ID we did rewriting for */ bool dependsOnRole; /* is rewritten query specific to role? */ bool fixed_result; /* disallow change in result tupdesc? */ TupleDesc resultDesc; /* result type; NULL = doesn't return tuples */ MemoryContext context; /* memory context holding all above */ /* These fields describe the current analyzed-and-rewritten query tree: */ List* query_list; /* list of Query nodes, or NIL if not valid */ /* * Notice: be careful to use relationOids as it may contain non-table OID * in some scenarios, e.g. assignment of relationOids in fix_expr_common. */ List* relationOids; /* contain OIDs of relations the queries depend on */ List* invalItems; /* other dependencies, as PlanInvalItems */ struct OverrideSearchPath* search_path; /* search_path used for * parsing and planning */ MemoryContext query_context; /* context holding the above, or NULL */ /* If we have a generic plan, this is a reference-counted link to it: */ struct CachedPlan* gplan; /* generic plan, or NULL if not valid */ /* Some state flags: */ bool is_complete; /* has CompleteCachedPlan been done? */ bool is_saved; /* has CachedPlanSource been "saved"? */ bool is_valid; /* is the query_list currently valid? */ bool is_oneshot; /* is it a "oneshot" plan? */ #ifdef ENABLE_MOT StorageEngineType storageEngineType; /* which storage engine is used*/ JitExec::JitContext* mot_jit_context; /* MOT JIT context required for executing LLVM jitted code */ #endif int generation; /* increments each time we create a plan */ /* If CachedPlanSource has been saved, it is a member of a global list */ struct CachedPlanSource* next_saved; /* list link, if so */ /* State kept to help decide whether to use custom or generic plans: */ double generic_cost; /* cost of generic plan, or -1 if not known */ double total_custom_cost; /* total cost of custom plans so far */ int num_custom_plans; /* number of plans included in total */ GPCSource gpc; /* share plan cache */ SPISign spi_signature; bool is_support_gplan; /* true if generate gplan */ #ifdef PGXC char* stmt_name; /* If set, this is a copy of prepared stmt name */ bool stream_enabled; /* true if the plan is made with stream operator enabled */ struct CachedPlan* cplan; /* custom plan, or NULL if not valid */ ExecNodes* single_exec_node; bool is_read_only; void* lightProxyObj; /* light cn object */ void* opFusionObj; /* operator fusion object */ bool is_checked_opfusion; bool gplan_is_fqs; /* if gplan is a fqs plan, use generic plan if so when enable_pbe_optimization is on */ bool force_custom_plan; /* force to use custom plan */ bool single_shard_stmt; /* single shard stmt? */ #endif } CachedPlanSource; /* * CachedPlan represents an execution plan derived from a CachedPlanSource. * The reference count includes both the link from the parent CachedPlanSource * (if any), and any active plan executions, so the plan can be discarded * exactly when refcount goes to zero. Both the struct itself and the * subsidiary data live in the context denoted by the context field. * This makes it easy to free a no-longer-needed cached plan. (However, * if is_oneshot is true, the context does not belong solely to the CachedPlan * so no freeing is possible.) */ typedef struct CachedPlan { int magic; /* should equal CACHEDPLAN_MAGIC */ List* stmt_list; /* list of statement nodes (PlannedStmts and * bare utility statements) */ bool is_saved; /* is CachedPlan in a long-lived context? */ bool is_valid; /* is the stmt_list currently valid? */ bool is_oneshot; /* is it a "oneshot" plan? */ #ifdef ENABLE_MOT StorageEngineType storageEngineType; /* which storage engine is used*/ JitExec::JitContext* mot_jit_context; /* MOT JIT context required for executing LLVM jitted code */ #endif bool dependsOnRole; /* is plan specific to that role? */ Oid planRoleId; /* Role ID the plan was created for */ TransactionId saved_xmin; /* if valid, replan when TransactionXmin * changes from this value */ int generation; /* parent's generation number for this plan */ int refcount; /* count of live references to this struct */ bool single_shard_stmt; /* single shard stmt? */ MemoryContext context; /* context containing this CachedPlan */ volatile int global_refcount; volatile bool is_share; /* is it gpc share plan? */ int dn_stmt_num; /* datanode statment num */ inline bool isShared() { pg_memory_barrier(); return is_share; } } CachedPlan; extern void InitPlanCache(void); extern void ResetPlanCache(void); extern CachedPlanSource* CreateCachedPlan(Node* raw_parse_tree, const char* query_string, #ifdef PGXC const char* stmt_name, #endif const char* commandTag, bool enable_spi_gpc = false); extern CachedPlanSource* CreateOneShotCachedPlan( Node* raw_parse_tree, const char* query_string, const char* commandTag); extern void CompleteCachedPlan(CachedPlanSource* plansource, List* querytree_list, MemoryContext querytree_context, Oid* param_types, int num_params, ParserSetupHook parserSetup, void* parserSetupArg, int cursor_options, bool fixed_result, const char* stmt_name, ExecNodes* single_exec_node = NULL, bool is_read_only = false); extern void SaveCachedPlan(CachedPlanSource* plansource); extern void DropCachedPlan(CachedPlanSource* plansource); extern void CachedPlanSetParentContext(CachedPlanSource* plansource, MemoryContext newcontext); extern CachedPlanSource *CopyCachedPlan(CachedPlanSource *plansource, bool is_share); extern bool CachedPlanIsValid(CachedPlanSource* plansource); extern List* CachedPlanGetTargetList(CachedPlanSource* plansource); extern CachedPlan* GetCachedPlan(CachedPlanSource* plansource, ParamListInfo boundParams, bool useResOwner); extern void ReleaseCachedPlan(CachedPlan* plan, bool useResOwner); extern void DropCachedPlanInternal(CachedPlanSource* plansource); extern List* RevalidateCachedQuery(CachedPlanSource* plansource, bool has_lp = false); extern void CheckRelDependency(CachedPlanSource *plansource, Oid relid); extern void CheckInvalItemDependency(CachedPlanSource *plansource, int cacheid, uint32 hashvalue); extern void ResetPlanCache(CachedPlanSource *plansource); extern void PlanCacheRelCallback(Datum arg, Oid relid); extern void PlanCacheFuncCallback(Datum arg, int cacheid, uint32 hashvalue); extern void PlanCacheSysCallback(Datum arg, int cacheid, uint32 hashvalue); extern bool IsStreamSupport(); extern void AcquirePlannerLocks(List* stmt_list, bool acquire); extern void AcquireExecutorLocks(List* stmt_list, bool acquire); #endif /* PLANCACHE_H */
38.876777
135
0.69566
[ "object" ]
7fd100e838b7402eadcd97600950e80efa159388
4,915
c
C
src/phocountmodule.c
leofang/csxtools
eb3ab7f33f230b3d09c428c7bcca94d4d8f844a5
[ "BSD-3-Clause" ]
4
2016-02-13T22:01:30.000Z
2020-11-08T14:25:29.000Z
src/phocountmodule.c
leofang/csxtools
eb3ab7f33f230b3d09c428c7bcca94d4d8f844a5
[ "BSD-3-Clause" ]
62
2015-08-21T19:14:07.000Z
2022-01-19T22:06:53.000Z
src/phocountmodule.c
leofang/csxtools
eb3ab7f33f230b3d09c428c7bcca94d4d8f844a5
[ "BSD-3-Clause" ]
13
2015-08-20T15:29:41.000Z
2020-02-10T22:52:10.000Z
/* * Copyright (c) 2014, Brookhaven Science Associates, Brookhaven * National Laboratory. 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 Brookhaven Science Associates, Brookhaven * National Laboratory 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 OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <stdio.h> #include <Python.h> /* Include python and numpy header files */ #include <math.h> #define NPY_NO_DEPRECATED_API NPY_1_9_API_VERSION #include <numpy/ndarraytypes.h> #include <numpy/ndarrayobject.h> #include "phocount.h" static PyObject* phocount_count(PyObject *self, PyObject *args){ PyObject *_input = NULL; PyArrayObject *input = NULL; PyArrayObject *stddev = NULL; PyArrayObject *out = NULL; npy_intp *dims; int ndims; float thresh[2], sum_filter[2], std_filter[2]; int sum_max; int nan = 0; if(!PyArg_ParseTuple(args, "O(ff)(ff)(ff)i|p", &_input, &thresh[0], &thresh[1], &sum_filter[0], &sum_filter[1], &std_filter[0], &std_filter[1], &sum_max, &nan)){ return NULL; } if(sum_max <= 0 || sum_max > 9){ PyErr_SetString(PyExc_ValueError, "Maximum sum value must be between 0 and 9"); goto error; } input = (PyArrayObject*)PyArray_FROMANY(_input, NPY_FLOAT, 3, 0,NPY_ARRAY_IN_ARRAY); if(!input){ goto error; } ndims = PyArray_NDIM(input); dims = PyArray_DIMS(input); out = (PyArrayObject*)PyArray_SimpleNew(ndims, dims, NPY_FLOAT); if(!out){ goto error; } stddev = (PyArrayObject*)PyArray_SimpleNew(ndims, dims, NPY_FLOAT); if(!stddev){ goto error; } data_t *input_p = (data_t*)PyArray_DATA(input); data_t *out_p = (data_t*)PyArray_DATA(out); data_t *stddev_p = (data_t*)PyArray_DATA(stddev); // Ok now we don't touch Python Object ... Release the GIL Py_BEGIN_ALLOW_THREADS count(input_p, out_p, stddev_p, ndims, dims, thresh, sum_filter, std_filter, sum_max, nan); Py_END_ALLOW_THREADS Py_XDECREF(input); return Py_BuildValue("(NN)", out, stddev); error: Py_XDECREF(input); Py_XDECREF(out); Py_XDECREF(stddev); return NULL; } static PyMethodDef phocountMethods[] = { { "count", phocount_count, METH_VARARGS, "Identify and count photons in CCD image"}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef phocountmodule = { PyModuleDef_HEAD_INIT, "phocount", /* name of module */ NULL, /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ phocountMethods }; PyMODINIT_FUNC PyInit_phocount(void) { PyObject *m; m = PyModule_Create(&phocountmodule); if(m == NULL){ return NULL; } import_array(); return m; }
35.875912
86
0.596745
[ "object" ]
7fd5fc0b168a6ecbadffca3d175d49624b871bfd
91,922
h
C
Source/GeneratedServices/CloudResourceManager/GTLRCloudResourceManagerQuery.h
goodjobs-page/google-api-objectivec-client-for-rest
fced61e08b89159eca7138e67210c2b0ac645ba7
[ "Apache-2.0" ]
null
null
null
Source/GeneratedServices/CloudResourceManager/GTLRCloudResourceManagerQuery.h
goodjobs-page/google-api-objectivec-client-for-rest
fced61e08b89159eca7138e67210c2b0ac645ba7
[ "Apache-2.0" ]
null
null
null
Source/GeneratedServices/CloudResourceManager/GTLRCloudResourceManagerQuery.h
goodjobs-page/google-api-objectivec-client-for-rest
fced61e08b89159eca7138e67210c2b0ac645ba7
[ "Apache-2.0" ]
null
null
null
// NOTE: This file was generated by the ServiceGenerator. // ---------------------------------------------------------------------------- // API: // Cloud Resource Manager API (cloudresourcemanager/v3) // Description: // Creates, reads, and updates metadata for Google Cloud Platform resource // containers. // Documentation: // https://cloud.google.com/resource-manager #if SWIFT_PACKAGE || GTLR_USE_MODULAR_IMPORT @import GoogleAPIClientForRESTCore; #elif GTLR_BUILT_AS_FRAMEWORK #import "GTLR/GTLRQuery.h" #else #import "GTLRQuery.h" #endif #if GTLR_RUNTIME_VERSION != 3000 #error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source. #endif @class GTLRCloudResourceManager_Folder; @class GTLRCloudResourceManager_GetIamPolicyRequest; @class GTLRCloudResourceManager_Lien; @class GTLRCloudResourceManager_MoveFolderRequest; @class GTLRCloudResourceManager_MoveProjectRequest; @class GTLRCloudResourceManager_Project; @class GTLRCloudResourceManager_SetIamPolicyRequest; @class GTLRCloudResourceManager_TagBinding; @class GTLRCloudResourceManager_TagKey; @class GTLRCloudResourceManager_TagValue; @class GTLRCloudResourceManager_TestIamPermissionsRequest; @class GTLRCloudResourceManager_UndeleteFolderRequest; @class GTLRCloudResourceManager_UndeleteProjectRequest; // Generated comments include content from the discovery document; avoid them // causing warnings since clang's checks are some what arbitrary. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" NS_ASSUME_NONNULL_BEGIN /** * Parent class for other Cloud Resource Manager query classes. */ @interface GTLRCloudResourceManagerQuery : GTLRQuery /** Selector specifying which fields to include in a partial response. */ @property(nonatomic, copy, nullable) NSString *fields; @end /** * Creates a folder in the resource hierarchy. Returns an `Operation` which can * be used to track the progress of the folder creation workflow. Upon success, * the `Operation.response` field will be populated with the created Folder. In * order to succeed, the addition of this new folder must not violate the * folder naming, height, or fanout constraints. + The folder's `display_name` * must be distinct from all other folders that share its parent. + The * addition of the folder must not cause the active folder hierarchy to exceed * a height of 10. Note, the full active + deleted folder hierarchy is allowed * to reach a height of 20; this provides additional headroom when moving * folders that contain deleted folders. + The addition of the folder must not * cause the total number of folders under its parent to exceed 300. If the * operation fails due to a folder constraint violation, some errors may be * returned by the `CreateFolder` request, with status code * `FAILED_PRECONDITION` and an error description. Other folder constraint * violations will be communicated in the `Operation`, with the specific * `PreconditionFailure` returned in the details list in the `Operation.error` * field. The caller must have `resourcemanager.folders.create` permission on * the identified parent. * * Method: cloudresourcemanager.folders.create * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_FoldersCreate : GTLRCloudResourceManagerQuery /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Creates a folder in the resource hierarchy. Returns an `Operation` which can * be used to track the progress of the folder creation workflow. Upon success, * the `Operation.response` field will be populated with the created Folder. In * order to succeed, the addition of this new folder must not violate the * folder naming, height, or fanout constraints. + The folder's `display_name` * must be distinct from all other folders that share its parent. + The * addition of the folder must not cause the active folder hierarchy to exceed * a height of 10. Note, the full active + deleted folder hierarchy is allowed * to reach a height of 20; this provides additional headroom when moving * folders that contain deleted folders. + The addition of the folder must not * cause the total number of folders under its parent to exceed 300. If the * operation fails due to a folder constraint violation, some errors may be * returned by the `CreateFolder` request, with status code * `FAILED_PRECONDITION` and an error description. Other folder constraint * violations will be communicated in the `Operation`, with the specific * `PreconditionFailure` returned in the details list in the `Operation.error` * field. The caller must have `resourcemanager.folders.create` permission on * the identified parent. * * @param object The @c GTLRCloudResourceManager_Folder to include in the * query. * * @return GTLRCloudResourceManagerQuery_FoldersCreate */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_Folder *)object; @end /** * Requests deletion of a folder. The folder is moved into the DELETE_REQUESTED * state immediately, and is deleted approximately 30 days later. This method * may only be called on an empty folder, where a folder is empty if it doesn't * contain any folders or projects in the ACTIVE state. If called on a folder * in DELETE_REQUESTED state the operation will result in a no-op success. The * caller must have `resourcemanager.folders.delete` permission on the * identified folder. * * Method: cloudresourcemanager.folders.delete * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_FoldersDelete : GTLRCloudResourceManagerQuery /** * Required. The resource name of the folder to be deleted. Must be of the form * `folders/{folder_id}`. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Requests deletion of a folder. The folder is moved into the DELETE_REQUESTED * state immediately, and is deleted approximately 30 days later. This method * may only be called on an empty folder, where a folder is empty if it doesn't * contain any folders or projects in the ACTIVE state. If called on a folder * in DELETE_REQUESTED state the operation will result in a no-op success. The * caller must have `resourcemanager.folders.delete` permission on the * identified folder. * * @param name Required. The resource name of the folder to be deleted. Must be * of the form `folders/{folder_id}`. * * @return GTLRCloudResourceManagerQuery_FoldersDelete */ + (instancetype)queryWithName:(NSString *)name; @end /** * Retrieves a folder identified by the supplied resource name. Valid folder * resource names have the format `folders/{folder_id}` (for example, * `folders/1234`). The caller must have `resourcemanager.folders.get` * permission on the identified folder. * * Method: cloudresourcemanager.folders.get * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_FoldersGet : GTLRCloudResourceManagerQuery /** * Required. The resource name of the folder to retrieve. Must be of the form * `folders/{folder_id}`. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Folder. * * Retrieves a folder identified by the supplied resource name. Valid folder * resource names have the format `folders/{folder_id}` (for example, * `folders/1234`). The caller must have `resourcemanager.folders.get` * permission on the identified folder. * * @param name Required. The resource name of the folder to retrieve. Must be * of the form `folders/{folder_id}`. * * @return GTLRCloudResourceManagerQuery_FoldersGet */ + (instancetype)queryWithName:(NSString *)name; @end /** * Gets the access control policy for a folder. The returned policy may be * empty if no such policy or resource exists. The `resource` field should be * the folder's resource name, for example: "folders/1234". The caller must * have `resourcemanager.folders.getIamPolicy` permission on the identified * folder. * * Method: cloudresourcemanager.folders.getIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_FoldersGetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being requested. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Gets the access control policy for a folder. The returned policy may be * empty if no such policy or resource exists. The `resource` field should be * the folder's resource name, for example: "folders/1234". The caller must * have `resourcemanager.folders.getIamPolicy` permission on the identified * folder. * * @param object The @c GTLRCloudResourceManager_GetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_FoldersGetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_GetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Lists the folders that are direct descendants of supplied parent resource. * `list()` provides a strongly consistent view of the folders underneath the * specified parent resource. `list()` returns folders sorted based upon the * (ascending) lexical ordering of their display_name. The caller must have * `resourcemanager.folders.list` permission on the identified parent. * * Method: cloudresourcemanager.folders.list * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_FoldersList : GTLRCloudResourceManagerQuery /** * Optional. The maximum number of folders to return in the response. The * server can return fewer folders than requested. If unspecified, server picks * an appropriate default. */ @property(nonatomic, assign) NSInteger pageSize; /** * Optional. A pagination token returned from a previous call to `ListFolders` * that indicates where this listing should continue from. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Required. The resource name of the organization or folder whose folders are * being listed. Must be of the form `folders/{folder_id}` or * `organizations/{org_id}`. Access to this method is controlled by checking * the `resourcemanager.folders.list` permission on the `parent`. */ @property(nonatomic, copy, nullable) NSString *parent; /** * Optional. Controls whether folders in the DELETE_REQUESTED state should be * returned. Defaults to false. */ @property(nonatomic, assign) BOOL showDeleted; /** * Fetches a @c GTLRCloudResourceManager_ListFoldersResponse. * * Lists the folders that are direct descendants of supplied parent resource. * `list()` provides a strongly consistent view of the folders underneath the * specified parent resource. `list()` returns folders sorted based upon the * (ascending) lexical ordering of their display_name. The caller must have * `resourcemanager.folders.list` permission on the identified parent. * * @return GTLRCloudResourceManagerQuery_FoldersList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)query; @end /** * Moves a folder under a new resource parent. Returns an `Operation` which can * be used to track the progress of the folder move workflow. Upon success, the * `Operation.response` field will be populated with the moved folder. Upon * failure, a `FolderOperationError` categorizing the failure cause will be * returned - if the failure occurs synchronously then the * `FolderOperationError` will be returned in the `Status.details` field. If it * occurs asynchronously, then the FolderOperation will be returned in the * `Operation.error` field. In addition, the `Operation.metadata` field will be * populated with a `FolderOperation` message as an aid to stateless clients. * Folder moves will be rejected if they violate either the naming, height, or * fanout constraints described in the CreateFolder documentation. The caller * must have `resourcemanager.folders.move` permission on the folder's current * and proposed new parent. * * Method: cloudresourcemanager.folders.move * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_FoldersMove : GTLRCloudResourceManagerQuery /** * Required. The resource name of the Folder to move. Must be of the form * folders/{folder_id} */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Moves a folder under a new resource parent. Returns an `Operation` which can * be used to track the progress of the folder move workflow. Upon success, the * `Operation.response` field will be populated with the moved folder. Upon * failure, a `FolderOperationError` categorizing the failure cause will be * returned - if the failure occurs synchronously then the * `FolderOperationError` will be returned in the `Status.details` field. If it * occurs asynchronously, then the FolderOperation will be returned in the * `Operation.error` field. In addition, the `Operation.metadata` field will be * populated with a `FolderOperation` message as an aid to stateless clients. * Folder moves will be rejected if they violate either the naming, height, or * fanout constraints described in the CreateFolder documentation. The caller * must have `resourcemanager.folders.move` permission on the folder's current * and proposed new parent. * * @param object The @c GTLRCloudResourceManager_MoveFolderRequest to include * in the query. * @param name Required. The resource name of the Folder to move. Must be of * the form folders/{folder_id} * * @return GTLRCloudResourceManagerQuery_FoldersMove */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_MoveFolderRequest *)object name:(NSString *)name; @end /** * Updates a folder, changing its `display_name`. Changes to the folder * `display_name` will be rejected if they violate either the `display_name` * formatting rules or the naming constraints described in the CreateFolder * documentation. The folder's `display_name` must start and end with a letter * or digit, may contain letters, digits, spaces, hyphens and underscores and * can be between 3 and 30 characters. This is captured by the regular * expression: `\\p{L}\\p{N}{1,28}[\\p{L}\\p{N}]`. The caller must have * `resourcemanager.folders.update` permission on the identified folder. If the * update fails due to the unique name constraint then a `PreconditionFailure` * explaining this violation will be returned in the Status.details field. * * Method: cloudresourcemanager.folders.patch * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_FoldersPatch : GTLRCloudResourceManagerQuery /** * Output only. The resource name of the folder. Its format is * `folders/{folder_id}`, for example: "folders/1234". */ @property(nonatomic, copy, nullable) NSString *name; /** * Required. Fields to be updated. Only the `display_name` can be updated. * * String format is a comma-separated list of fields. */ @property(nonatomic, copy, nullable) NSString *updateMask; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Updates a folder, changing its `display_name`. Changes to the folder * `display_name` will be rejected if they violate either the `display_name` * formatting rules or the naming constraints described in the CreateFolder * documentation. The folder's `display_name` must start and end with a letter * or digit, may contain letters, digits, spaces, hyphens and underscores and * can be between 3 and 30 characters. This is captured by the regular * expression: `\\p{L}\\p{N}{1,28}[\\p{L}\\p{N}]`. The caller must have * `resourcemanager.folders.update` permission on the identified folder. If the * update fails due to the unique name constraint then a `PreconditionFailure` * explaining this violation will be returned in the Status.details field. * * @param object The @c GTLRCloudResourceManager_Folder to include in the * query. * @param name Output only. The resource name of the folder. Its format is * `folders/{folder_id}`, for example: "folders/1234". * * @return GTLRCloudResourceManagerQuery_FoldersPatch */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_Folder *)object name:(NSString *)name; @end /** * Search for folders that match specific filter criteria. `search()` provides * an eventually consistent view of the folders a user has access to which meet * the specified filter criteria. This will only return folders on which the * caller has the permission `resourcemanager.folders.get`. * * Method: cloudresourcemanager.folders.search * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_FoldersSearch : GTLRCloudResourceManagerQuery /** * Optional. The maximum number of folders to return in the response. The * server can return fewer folders than requested. If unspecified, server picks * an appropriate default. */ @property(nonatomic, assign) NSInteger pageSize; /** * Optional. A pagination token returned from a previous call to * `SearchFolders` that indicates from where search should continue. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Optional. Search criteria used to select the folders to return. If no search * criteria is specified then all accessible folders will be returned. Query * expressions can be used to restrict results based upon displayName, state * and parent, where the operators `=` (`:`) `NOT`, `AND` and `OR` can be used * along with the suffix wildcard symbol `*`. The `displayName` field in a * query expression should use escaped quotes for values that include * whitespace to prevent unexpected behavior. | Field | Description | * |-------------------------|----------------------------------------| | * displayName | Filters by displayName. | | parent | Filters by parent (for * example: folders/123). | | state, lifecycleState | Filters by state. | Some * example queries are: * Query `displayName=Test*` returns Folder resources * whose display name starts with "Test". * Query `state=ACTIVE` returns Folder * resources with `state` set to `ACTIVE`. * Query `parent=folders/123` returns * Folder resources that have `folders/123` as a parent resource. * Query * `parent=folders/123 AND state=ACTIVE` returns active Folder resources that * have `folders/123` as a parent resource. * Query `displayName=\\\\"Test * String\\\\"` returns Folder resources with display names that include both * "Test" and "String". */ @property(nonatomic, copy, nullable) NSString *query; /** * Fetches a @c GTLRCloudResourceManager_SearchFoldersResponse. * * Search for folders that match specific filter criteria. `search()` provides * an eventually consistent view of the folders a user has access to which meet * the specified filter criteria. This will only return folders on which the * caller has the permission `resourcemanager.folders.get`. * * @return GTLRCloudResourceManagerQuery_FoldersSearch * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)query; @end /** * Sets the access control policy on a folder, replacing any existing policy. * The `resource` field should be the folder's resource name, for example: * "folders/1234". The caller must have `resourcemanager.folders.setIamPolicy` * permission on the identified folder. * * Method: cloudresourcemanager.folders.setIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_FoldersSetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being specified. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Sets the access control policy on a folder, replacing any existing policy. * The `resource` field should be the folder's resource name, for example: * "folders/1234". The caller must have `resourcemanager.folders.setIamPolicy` * permission on the identified folder. * * @param object The @c GTLRCloudResourceManager_SetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * specified. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_FoldersSetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_SetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Returns permissions that a caller has on the specified folder. The * `resource` field should be the folder's resource name, for example: * "folders/1234". There are no permissions required for making this API call. * * Method: cloudresourcemanager.folders.testIamPermissions * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_FoldersTestIamPermissions : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy detail is being requested. See * the operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_TestIamPermissionsResponse. * * Returns permissions that a caller has on the specified folder. The * `resource` field should be the folder's resource name, for example: * "folders/1234". There are no permissions required for making this API call. * * @param object The @c GTLRCloudResourceManager_TestIamPermissionsRequest to * include in the query. * @param resource REQUIRED: The resource for which the policy detail is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_FoldersTestIamPermissions */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TestIamPermissionsRequest *)object resource:(NSString *)resource; @end /** * Cancels the deletion request for a folder. This method may be called on a * folder in any state. If the folder is in the ACTIVE state the result will be * a no-op success. In order to succeed, the folder's parent must be in the * ACTIVE state. In addition, reintroducing the folder into the tree must not * violate folder naming, height, and fanout constraints described in the * CreateFolder documentation. The caller must have * `resourcemanager.folders.undelete` permission on the identified folder. * * Method: cloudresourcemanager.folders.undelete * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_FoldersUndelete : GTLRCloudResourceManagerQuery /** * Required. The resource name of the folder to undelete. Must be of the form * `folders/{folder_id}`. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Cancels the deletion request for a folder. This method may be called on a * folder in any state. If the folder is in the ACTIVE state the result will be * a no-op success. In order to succeed, the folder's parent must be in the * ACTIVE state. In addition, reintroducing the folder into the tree must not * violate folder naming, height, and fanout constraints described in the * CreateFolder documentation. The caller must have * `resourcemanager.folders.undelete` permission on the identified folder. * * @param object The @c GTLRCloudResourceManager_UndeleteFolderRequest to * include in the query. * @param name Required. The resource name of the folder to undelete. Must be * of the form `folders/{folder_id}`. * * @return GTLRCloudResourceManagerQuery_FoldersUndelete */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_UndeleteFolderRequest *)object name:(NSString *)name; @end /** * Create a Lien which applies to the resource denoted by the `parent` field. * Callers of this method will require permission on the `parent` resource. For * example, applying to `projects/1234` requires permission * `resourcemanager.projects.updateLiens`. NOTE: Some resources may limit the * number of Liens which may be applied. * * Method: cloudresourcemanager.liens.create * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_LiensCreate : GTLRCloudResourceManagerQuery /** * Fetches a @c GTLRCloudResourceManager_Lien. * * Create a Lien which applies to the resource denoted by the `parent` field. * Callers of this method will require permission on the `parent` resource. For * example, applying to `projects/1234` requires permission * `resourcemanager.projects.updateLiens`. NOTE: Some resources may limit the * number of Liens which may be applied. * * @param object The @c GTLRCloudResourceManager_Lien to include in the query. * * @return GTLRCloudResourceManagerQuery_LiensCreate */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_Lien *)object; @end /** * Delete a Lien by `name`. Callers of this method will require permission on * the `parent` resource. For example, a Lien with a `parent` of * `projects/1234` requires permission `resourcemanager.projects.updateLiens`. * * Method: cloudresourcemanager.liens.delete * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_LiensDelete : GTLRCloudResourceManagerQuery /** Required. The name/identifier of the Lien to delete. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Empty. * * Delete a Lien by `name`. Callers of this method will require permission on * the `parent` resource. For example, a Lien with a `parent` of * `projects/1234` requires permission `resourcemanager.projects.updateLiens`. * * @param name Required. The name/identifier of the Lien to delete. * * @return GTLRCloudResourceManagerQuery_LiensDelete */ + (instancetype)queryWithName:(NSString *)name; @end /** * Retrieve a Lien by `name`. Callers of this method will require permission on * the `parent` resource. For example, a Lien with a `parent` of * `projects/1234` requires permission `resourcemanager.projects.get` * * Method: cloudresourcemanager.liens.get * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_LiensGet : GTLRCloudResourceManagerQuery /** Required. The name/identifier of the Lien. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Lien. * * Retrieve a Lien by `name`. Callers of this method will require permission on * the `parent` resource. For example, a Lien with a `parent` of * `projects/1234` requires permission `resourcemanager.projects.get` * * @param name Required. The name/identifier of the Lien. * * @return GTLRCloudResourceManagerQuery_LiensGet */ + (instancetype)queryWithName:(NSString *)name; @end /** * List all Liens applied to the `parent` resource. Callers of this method will * require permission on the `parent` resource. For example, a Lien with a * `parent` of `projects/1234` requires permission * `resourcemanager.projects.get`. * * Method: cloudresourcemanager.liens.list * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_LiensList : GTLRCloudResourceManagerQuery /** * The maximum number of items to return. This is a suggestion for the server. * The server can return fewer liens than requested. If unspecified, server * picks an appropriate default. */ @property(nonatomic, assign) NSInteger pageSize; /** * The `next_page_token` value returned from a previous List request, if any. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Required. The name of the resource to list all attached Liens. For example, * `projects/1234`. (google.api.field_policy).resource_type annotation is not * set since the parent depends on the meta api implementation. This field * could be a project or other sub project resources. */ @property(nonatomic, copy, nullable) NSString *parent; /** * Fetches a @c GTLRCloudResourceManager_ListLiensResponse. * * List all Liens applied to the `parent` resource. Callers of this method will * require permission on the `parent` resource. For example, a Lien with a * `parent` of `projects/1234` requires permission * `resourcemanager.projects.get`. * * @return GTLRCloudResourceManagerQuery_LiensList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)query; @end /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * * Method: cloudresourcemanager.operations.get * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_OperationsGet : GTLRCloudResourceManagerQuery /** The name of the operation resource. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * * @param name The name of the operation resource. * * @return GTLRCloudResourceManagerQuery_OperationsGet */ + (instancetype)queryWithName:(NSString *)name; @end /** * Fetches an organization resource identified by the specified resource name. * * Method: cloudresourcemanager.organizations.get * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_OrganizationsGet : GTLRCloudResourceManagerQuery /** * Required. The resource name of the Organization to fetch. This is the * organization's relative path in the API, formatted as * "organizations/[organizationId]". For example, "organizations/1234". */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Organization. * * Fetches an organization resource identified by the specified resource name. * * @param name Required. The resource name of the Organization to fetch. This * is the organization's relative path in the API, formatted as * "organizations/[organizationId]". For example, "organizations/1234". * * @return GTLRCloudResourceManagerQuery_OrganizationsGet */ + (instancetype)queryWithName:(NSString *)name; @end /** * Gets the access control policy for an organization resource. The policy may * be empty if no such policy or resource exists. The `resource` field should * be the organization's resource name, for example: "organizations/123". * Authorization requires the IAM permission * `resourcemanager.organizations.getIamPolicy` on the specified organization. * * Method: cloudresourcemanager.organizations.getIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_OrganizationsGetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being requested. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Gets the access control policy for an organization resource. The policy may * be empty if no such policy or resource exists. The `resource` field should * be the organization's resource name, for example: "organizations/123". * Authorization requires the IAM permission * `resourcemanager.organizations.getIamPolicy` on the specified organization. * * @param object The @c GTLRCloudResourceManager_GetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_OrganizationsGetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_GetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Searches organization resources that are visible to the user and satisfy the * specified filter. This method returns organizations in an unspecified order. * New organizations do not necessarily appear at the end of the results, and * may take a small amount of time to appear. Search will only return * organizations on which the user has the permission * `resourcemanager.organizations.get` * * Method: cloudresourcemanager.organizations.search * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_OrganizationsSearch : GTLRCloudResourceManagerQuery /** * Optional. The maximum number of organizations to return in the response. The * server can return fewer organizations than requested. If unspecified, server * picks an appropriate default. */ @property(nonatomic, assign) NSInteger pageSize; /** * Optional. A pagination token returned from a previous call to * `SearchOrganizations` that indicates from where listing should continue. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Optional. An optional query string used to filter the Organizations to * return in the response. Query rules are case-insensitive. | Field | * Description | * |------------------|--------------------------------------------| | * directoryCustomerId, owner.directoryCustomerId | Filters by directory * customer id. | | domain | Filters by domain. | Organizations may be queried * by `directoryCustomerId` or by `domain`, where the domain is a G Suite * domain, for example: * Query `directorycustomerid:123456789` returns * Organization resources with `owner.directory_customer_id` equal to * `123456789`. * Query `domain:google.com` returns Organization resources * corresponding to the domain `google.com`. */ @property(nonatomic, copy, nullable) NSString *query; /** * Fetches a @c GTLRCloudResourceManager_SearchOrganizationsResponse. * * Searches organization resources that are visible to the user and satisfy the * specified filter. This method returns organizations in an unspecified order. * New organizations do not necessarily appear at the end of the results, and * may take a small amount of time to appear. Search will only return * organizations on which the user has the permission * `resourcemanager.organizations.get` * * @return GTLRCloudResourceManagerQuery_OrganizationsSearch * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)query; @end /** * Sets the access control policy on an organization resource. Replaces any * existing policy. The `resource` field should be the organization's resource * name, for example: "organizations/123". Authorization requires the IAM * permission `resourcemanager.organizations.setIamPolicy` on the specified * organization. * * Method: cloudresourcemanager.organizations.setIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_OrganizationsSetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being specified. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Sets the access control policy on an organization resource. Replaces any * existing policy. The `resource` field should be the organization's resource * name, for example: "organizations/123". Authorization requires the IAM * permission `resourcemanager.organizations.setIamPolicy` on the specified * organization. * * @param object The @c GTLRCloudResourceManager_SetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * specified. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_OrganizationsSetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_SetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Returns the permissions that a caller has on the specified organization. The * `resource` field should be the organization's resource name, for example: * "organizations/123". There are no permissions required for making this API * call. * * Method: cloudresourcemanager.organizations.testIamPermissions * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_OrganizationsTestIamPermissions : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy detail is being requested. See * the operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_TestIamPermissionsResponse. * * Returns the permissions that a caller has on the specified organization. The * `resource` field should be the organization's resource name, for example: * "organizations/123". There are no permissions required for making this API * call. * * @param object The @c GTLRCloudResourceManager_TestIamPermissionsRequest to * include in the query. * @param resource REQUIRED: The resource for which the policy detail is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_OrganizationsTestIamPermissions */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TestIamPermissionsRequest *)object resource:(NSString *)resource; @end /** * Request that a new project be created. The result is an `Operation` which * can be used to track the creation process. This process usually takes a few * seconds, but can sometimes take much longer. The tracking `Operation` is * automatically deleted after a few hours, so there is no need to call * `DeleteOperation`. * * Method: cloudresourcemanager.projects.create * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_ProjectsCreate : GTLRCloudResourceManagerQuery /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Request that a new project be created. The result is an `Operation` which * can be used to track the creation process. This process usually takes a few * seconds, but can sometimes take much longer. The tracking `Operation` is * automatically deleted after a few hours, so there is no need to call * `DeleteOperation`. * * @param object The @c GTLRCloudResourceManager_Project to include in the * query. * * @return GTLRCloudResourceManagerQuery_ProjectsCreate */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_Project *)object; @end /** * Marks the project identified by the specified `name` (for example, * `projects/415104041262`) for deletion. This method will only affect the * project if it has a lifecycle state of ACTIVE. This method changes the * Project's lifecycle state from ACTIVE to DELETE_REQUESTED. The deletion * starts at an unspecified time, at which point the Project is no longer * accessible. Until the deletion completes, you can check the lifecycle state * checked by retrieving the project with GetProject, and the project remains * visible to ListProjects. However, you cannot update the project. After the * deletion completes, the project is not retrievable by the GetProject, * ListProjects, and SearchProjects methods. This method behaves idempotently, * such that deleting a `DELETE_REQUESTED` project will not cause an error, but * also won't do anything. The caller must have * `resourcemanager.projects.delete` permissions for this project. * * Method: cloudresourcemanager.projects.delete * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_ProjectsDelete : GTLRCloudResourceManagerQuery /** * Required. The name of the Project (for example, `projects/415104041262`). */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Marks the project identified by the specified `name` (for example, * `projects/415104041262`) for deletion. This method will only affect the * project if it has a lifecycle state of ACTIVE. This method changes the * Project's lifecycle state from ACTIVE to DELETE_REQUESTED. The deletion * starts at an unspecified time, at which point the Project is no longer * accessible. Until the deletion completes, you can check the lifecycle state * checked by retrieving the project with GetProject, and the project remains * visible to ListProjects. However, you cannot update the project. After the * deletion completes, the project is not retrievable by the GetProject, * ListProjects, and SearchProjects methods. This method behaves idempotently, * such that deleting a `DELETE_REQUESTED` project will not cause an error, but * also won't do anything. The caller must have * `resourcemanager.projects.delete` permissions for this project. * * @param name Required. The name of the Project (for example, * `projects/415104041262`). * * @return GTLRCloudResourceManagerQuery_ProjectsDelete */ + (instancetype)queryWithName:(NSString *)name; @end /** * Retrieves the project identified by the specified `name` (for example, * `projects/415104041262`). The caller must have * `resourcemanager.projects.get` permission for this project. * * Method: cloudresourcemanager.projects.get * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_ProjectsGet : GTLRCloudResourceManagerQuery /** * Required. The name of the project (for example, `projects/415104041262`). */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Project. * * Retrieves the project identified by the specified `name` (for example, * `projects/415104041262`). The caller must have * `resourcemanager.projects.get` permission for this project. * * @param name Required. The name of the project (for example, * `projects/415104041262`). * * @return GTLRCloudResourceManagerQuery_ProjectsGet */ + (instancetype)queryWithName:(NSString *)name; @end /** * Returns the IAM access control policy for the specified project, in the * format `projects/{ProjectIdOrNumber}` e.g. projects/123. Permission is * denied if the policy or the resource do not exist. * * Method: cloudresourcemanager.projects.getIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_ProjectsGetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being requested. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Returns the IAM access control policy for the specified project, in the * format `projects/{ProjectIdOrNumber}` e.g. projects/123. Permission is * denied if the policy or the resource do not exist. * * @param object The @c GTLRCloudResourceManager_GetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_ProjectsGetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_GetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Lists projects that are direct children of the specified folder or * organization resource. `list()` provides a strongly consistent view of the * projects underneath the specified parent resource. `list()` returns projects * sorted based upon the (ascending) lexical ordering of their `display_name`. * The caller must have `resourcemanager.projects.list` permission on the * identified parent. * * Method: cloudresourcemanager.projects.list * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_ProjectsList : GTLRCloudResourceManagerQuery /** * Optional. The maximum number of projects to return in the response. The * server can return fewer projects than requested. If unspecified, server * picks an appropriate default. */ @property(nonatomic, assign) NSInteger pageSize; /** * Optional. A pagination token returned from a previous call to ListProjects * that indicates from where listing should continue. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Required. The name of the parent resource to list projects under. For * example, setting this field to 'folders/1234' would list all projects * directly under that folder. */ @property(nonatomic, copy, nullable) NSString *parent; /** * Optional. Indicate that projects in the `DELETE_REQUESTED` state should also * be returned. Normally only `ACTIVE` projects are returned. */ @property(nonatomic, assign) BOOL showDeleted; /** * Fetches a @c GTLRCloudResourceManager_ListProjectsResponse. * * Lists projects that are direct children of the specified folder or * organization resource. `list()` provides a strongly consistent view of the * projects underneath the specified parent resource. `list()` returns projects * sorted based upon the (ascending) lexical ordering of their `display_name`. * The caller must have `resourcemanager.projects.list` permission on the * identified parent. * * @return GTLRCloudResourceManagerQuery_ProjectsList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)query; @end /** * Move a project to another place in your resource hierarchy, under a new * resource parent. Returns an operation which can be used to track the process * of the project move workflow. Upon success, the `Operation.response` field * will be populated with the moved project. The caller must have * `resourcemanager.projects.update` permission on the project and have * `resourcemanager.projects.move` permission on the project's current and * proposed new parent. If project has no current parent, or it currently does * not have an associated organization resource, you will also need the * `resourcemanager.projects.setIamPolicy` permission in the project. * * Method: cloudresourcemanager.projects.move * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_ProjectsMove : GTLRCloudResourceManagerQuery /** Required. The name of the project to move. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Move a project to another place in your resource hierarchy, under a new * resource parent. Returns an operation which can be used to track the process * of the project move workflow. Upon success, the `Operation.response` field * will be populated with the moved project. The caller must have * `resourcemanager.projects.update` permission on the project and have * `resourcemanager.projects.move` permission on the project's current and * proposed new parent. If project has no current parent, or it currently does * not have an associated organization resource, you will also need the * `resourcemanager.projects.setIamPolicy` permission in the project. * * @param object The @c GTLRCloudResourceManager_MoveProjectRequest to include * in the query. * @param name Required. The name of the project to move. * * @return GTLRCloudResourceManagerQuery_ProjectsMove */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_MoveProjectRequest *)object name:(NSString *)name; @end /** * Updates the `display_name` and labels of the project identified by the * specified `name` (for example, `projects/415104041262`). Deleting all labels * requires an update mask for labels field. The caller must have * `resourcemanager.projects.update` permission for this project. * * Method: cloudresourcemanager.projects.patch * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_ProjectsPatch : GTLRCloudResourceManagerQuery /** * Output only. The unique resource name of the project. It is an int64 * generated number prefixed by "projects/". Example: `projects/415104041262` */ @property(nonatomic, copy, nullable) NSString *name; /** * Optional. An update mask to selectively update fields. * * String format is a comma-separated list of fields. */ @property(nonatomic, copy, nullable) NSString *updateMask; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Updates the `display_name` and labels of the project identified by the * specified `name` (for example, `projects/415104041262`). Deleting all labels * requires an update mask for labels field. The caller must have * `resourcemanager.projects.update` permission for this project. * * @param object The @c GTLRCloudResourceManager_Project to include in the * query. * @param name Output only. The unique resource name of the project. It is an * int64 generated number prefixed by "projects/". Example: * `projects/415104041262` * * @return GTLRCloudResourceManagerQuery_ProjectsPatch */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_Project *)object name:(NSString *)name; @end /** * Search for projects that the caller has both `resourcemanager.projects.get` * permission on, and also satisfy the specified query. This method returns * projects in an unspecified order. This method is eventually consistent with * project mutations; this means that a newly created project may not appear in * the results or recent updates to an existing project may not be reflected in * the results. To retrieve the latest state of a project, use the GetProject * method. * * Method: cloudresourcemanager.projects.search * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_ProjectsSearch : GTLRCloudResourceManagerQuery /** * Optional. The maximum number of projects to return in the response. The * server can return fewer projects than requested. If unspecified, server * picks an appropriate default. */ @property(nonatomic, assign) NSInteger pageSize; /** * Optional. A pagination token returned from a previous call to ListProjects * that indicates from where listing should continue. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Optional. A query string for searching for projects that the caller has * `resourcemanager.projects.get` permission to. If multiple fields are * included in the query, the it will return results that match any of the * fields. Some eligible fields are: | Field | Description | * |-------------------------|----------------------------------------------| | * displayName, name | Filters by displayName. | | parent | Project's parent * (for example: folders/123, organizations/ *). Prefer parent field over * parent.type and parent.id.| | parent.type | Parent's type: `folder` or * `organization`. | | parent.id | Parent's id number (for example: 123) | | * id, projectId | Filters by projectId. | | state, lifecycleState | Filters by * state. | | labels | Filters by label name or value. | | labels.\\ (where * *key* is the name of a label) | Filters by label name.| Search expressions * are case insensitive. Some examples queries: | Query | Description | * |------------------|-----------------------------------------------------| | * name:how* | The project's name starts with "how". | | name:Howl | The * project's name is `Howl` or `howl`. | | name:HOWL | Equivalent to above. | | * NAME:howl | Equivalent to above. | | labels.color:* | The project has the * label `color`. | | labels.color:red | The project's label `color` has the * value `red`. | | labels.color:red labels.size:big | The project's label * `color` has the value `red` and its label `size` has the value `big`.| If no * query is specified, the call will return projects for which the user has the * `resourcemanager.projects.get` permission. */ @property(nonatomic, copy, nullable) NSString *query; /** * Fetches a @c GTLRCloudResourceManager_SearchProjectsResponse. * * Search for projects that the caller has both `resourcemanager.projects.get` * permission on, and also satisfy the specified query. This method returns * projects in an unspecified order. This method is eventually consistent with * project mutations; this means that a newly created project may not appear in * the results or recent updates to an existing project may not be reflected in * the results. To retrieve the latest state of a project, use the GetProject * method. * * @return GTLRCloudResourceManagerQuery_ProjectsSearch * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)query; @end /** * Sets the IAM access control policy for the specified project, in the format * `projects/{ProjectIdOrNumber}` e.g. projects/123. CAUTION: This method will * replace the existing policy, and cannot be used to append additional IAM * settings. Note: Removing service accounts from policies or changing their * roles can render services completely inoperable. It is important to * understand how the service account is being used before removing or updating * its roles. The following constraints apply when using `setIamPolicy()`: + * Project does not support `allUsers` and `allAuthenticatedUsers` as `members` * in a `Binding` of a `Policy`. + The owner role can be granted to a `user`, * `serviceAccount`, or a group that is part of an organization. For example, * group\@myownpersonaldomain.com could be added as an owner to a project in * the myownpersonaldomain.com organization, but not the examplepetstore.com * organization. + Service accounts can be made owners of a project directly * without any restrictions. However, to be added as an owner, a user must be * invited using the Cloud Platform console and must accept the invitation. + A * user cannot be granted the owner role using `setIamPolicy()`. The user must * be granted the owner role using the Cloud Platform Console and must * explicitly accept the invitation. + Invitations to grant the owner role * cannot be sent using `setIamPolicy()`; they must be sent only using the * Cloud Platform Console. + Membership changes that leave the project without * any owners that have accepted the Terms of Service (ToS) will be rejected. + * If the project is not part of an organization, there must be at least one * owner who has accepted the Terms of Service (ToS) agreement in the policy. * Calling `setIamPolicy()` to remove the last ToS-accepted owner from the * policy will fail. This restriction also applies to legacy projects that no * longer have owners who have accepted the ToS. Edits to IAM policies will be * rejected until the lack of a ToS-accepting owner is rectified. + Calling * this method requires enabling the App Engine Admin API. * * Method: cloudresourcemanager.projects.setIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_ProjectsSetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being specified. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Sets the IAM access control policy for the specified project, in the format * `projects/{ProjectIdOrNumber}` e.g. projects/123. CAUTION: This method will * replace the existing policy, and cannot be used to append additional IAM * settings. Note: Removing service accounts from policies or changing their * roles can render services completely inoperable. It is important to * understand how the service account is being used before removing or updating * its roles. The following constraints apply when using `setIamPolicy()`: + * Project does not support `allUsers` and `allAuthenticatedUsers` as `members` * in a `Binding` of a `Policy`. + The owner role can be granted to a `user`, * `serviceAccount`, or a group that is part of an organization. For example, * group\@myownpersonaldomain.com could be added as an owner to a project in * the myownpersonaldomain.com organization, but not the examplepetstore.com * organization. + Service accounts can be made owners of a project directly * without any restrictions. However, to be added as an owner, a user must be * invited using the Cloud Platform console and must accept the invitation. + A * user cannot be granted the owner role using `setIamPolicy()`. The user must * be granted the owner role using the Cloud Platform Console and must * explicitly accept the invitation. + Invitations to grant the owner role * cannot be sent using `setIamPolicy()`; they must be sent only using the * Cloud Platform Console. + Membership changes that leave the project without * any owners that have accepted the Terms of Service (ToS) will be rejected. + * If the project is not part of an organization, there must be at least one * owner who has accepted the Terms of Service (ToS) agreement in the policy. * Calling `setIamPolicy()` to remove the last ToS-accepted owner from the * policy will fail. This restriction also applies to legacy projects that no * longer have owners who have accepted the ToS. Edits to IAM policies will be * rejected until the lack of a ToS-accepting owner is rectified. + Calling * this method requires enabling the App Engine Admin API. * * @param object The @c GTLRCloudResourceManager_SetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * specified. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_ProjectsSetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_SetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Returns permissions that a caller has on the specified project, in the * format `projects/{ProjectIdOrNumber}` e.g. projects/123.. * * Method: cloudresourcemanager.projects.testIamPermissions * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_ProjectsTestIamPermissions : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy detail is being requested. See * the operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_TestIamPermissionsResponse. * * Returns permissions that a caller has on the specified project, in the * format `projects/{ProjectIdOrNumber}` e.g. projects/123.. * * @param object The @c GTLRCloudResourceManager_TestIamPermissionsRequest to * include in the query. * @param resource REQUIRED: The resource for which the policy detail is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_ProjectsTestIamPermissions */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TestIamPermissionsRequest *)object resource:(NSString *)resource; @end /** * Restores the project identified by the specified `name` (for example, * `projects/415104041262`). You can only use this method for a project that * has a lifecycle state of DELETE_REQUESTED. After deletion starts, the * project cannot be restored. The caller must have * `resourcemanager.projects.undelete` permission for this project. * * Method: cloudresourcemanager.projects.undelete * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_ProjectsUndelete : GTLRCloudResourceManagerQuery /** * Required. The name of the project (for example, `projects/415104041262`). * Required. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Restores the project identified by the specified `name` (for example, * `projects/415104041262`). You can only use this method for a project that * has a lifecycle state of DELETE_REQUESTED. After deletion starts, the * project cannot be restored. The caller must have * `resourcemanager.projects.undelete` permission for this project. * * @param object The @c GTLRCloudResourceManager_UndeleteProjectRequest to * include in the query. * @param name Required. The name of the project (for example, * `projects/415104041262`). Required. * * @return GTLRCloudResourceManagerQuery_ProjectsUndelete */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_UndeleteProjectRequest *)object name:(NSString *)name; @end /** * Creates a TagBinding between a TagValue and a cloud resource (currently * project, folder, or organization). * * Method: cloudresourcemanager.tagBindings.create * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagBindingsCreate : GTLRCloudResourceManagerQuery /** * Optional. Set to true to perform the validations necessary for creating the * resource, but not actually perform the action. */ @property(nonatomic, assign) BOOL validateOnly; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Creates a TagBinding between a TagValue and a cloud resource (currently * project, folder, or organization). * * @param object The @c GTLRCloudResourceManager_TagBinding to include in the * query. * * @return GTLRCloudResourceManagerQuery_TagBindingsCreate */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TagBinding *)object; @end /** * Deletes a TagBinding. * * Method: cloudresourcemanager.tagBindings.delete * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagBindingsDelete : GTLRCloudResourceManagerQuery /** * Required. The name of the TagBinding. This is a String of the form: * `tagBindings/{id}` (e.g. * `tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456`). */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Deletes a TagBinding. * * @param name Required. The name of the TagBinding. This is a String of the * form: `tagBindings/{id}` (e.g. * `tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456`). * * @return GTLRCloudResourceManagerQuery_TagBindingsDelete */ + (instancetype)queryWithName:(NSString *)name; @end /** * Lists the TagBindings for the given cloud resource, as specified with * `parent`. NOTE: The `parent` field is expected to be a full resource name: * https://cloud.google.com/apis/design/resource_names#full_resource_name * * Method: cloudresourcemanager.tagBindings.list * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_TagBindingsList : GTLRCloudResourceManagerQuery /** * Optional. The maximum number of TagBindings to return in the response. The * server allows a maximum of 300 TagBindings to return. If unspecified, the * server will use 100 as the default. */ @property(nonatomic, assign) NSInteger pageSize; /** * Optional. A pagination token returned from a previous call to * `ListTagBindings` that indicates where this listing should continue from. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Required. The full resource name of a resource for which you want to list * existing TagBindings. E.g. * "//cloudresourcemanager.googleapis.com/projects/123" */ @property(nonatomic, copy, nullable) NSString *parent; /** * Fetches a @c GTLRCloudResourceManager_ListTagBindingsResponse. * * Lists the TagBindings for the given cloud resource, as specified with * `parent`. NOTE: The `parent` field is expected to be a full resource name: * https://cloud.google.com/apis/design/resource_names#full_resource_name * * @return GTLRCloudResourceManagerQuery_TagBindingsList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)query; @end /** * Creates a new TagKey. If another request with the same parameters is sent * while the original request is in process, the second request will receive an * error. A maximum of 300 TagKeys can exist under a parent at any given time. * * Method: cloudresourcemanager.tagKeys.create * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagKeysCreate : GTLRCloudResourceManagerQuery /** * Optional. Set to true to perform validations necessary for creating the * resource, but not actually perform the action. */ @property(nonatomic, assign) BOOL validateOnly; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Creates a new TagKey. If another request with the same parameters is sent * while the original request is in process, the second request will receive an * error. A maximum of 300 TagKeys can exist under a parent at any given time. * * @param object The @c GTLRCloudResourceManager_TagKey to include in the * query. * * @return GTLRCloudResourceManagerQuery_TagKeysCreate */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TagKey *)object; @end /** * Deletes a TagKey. The TagKey cannot be deleted if it has any child * TagValues. * * Method: cloudresourcemanager.tagKeys.delete * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagKeysDelete : GTLRCloudResourceManagerQuery /** * Optional. The etag known to the client for the expected state of the TagKey. * This is to be used for optimistic concurrency. */ @property(nonatomic, copy, nullable) NSString *ETag; /** * Required. The resource name of a TagKey to be deleted in the format * `tagKeys/123`. The TagKey cannot be a parent of any existing TagValues or it * will not be deleted successfully. */ @property(nonatomic, copy, nullable) NSString *name; /** * Optional. Set as true to perform validations necessary for deletion, but not * actually perform the action. */ @property(nonatomic, assign) BOOL validateOnly; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Deletes a TagKey. The TagKey cannot be deleted if it has any child * TagValues. * * @param name Required. The resource name of a TagKey to be deleted in the * format `tagKeys/123`. The TagKey cannot be a parent of any existing * TagValues or it will not be deleted successfully. * * @return GTLRCloudResourceManagerQuery_TagKeysDelete */ + (instancetype)queryWithName:(NSString *)name; @end /** * Retrieves a TagKey. This method will return `PERMISSION_DENIED` if the key * does not exist or the user does not have permission to view it. * * Method: cloudresourcemanager.tagKeys.get * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_TagKeysGet : GTLRCloudResourceManagerQuery /** * Required. A resource name in the format `tagKeys/{id}`, such as * `tagKeys/123`. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_TagKey. * * Retrieves a TagKey. This method will return `PERMISSION_DENIED` if the key * does not exist or the user does not have permission to view it. * * @param name Required. A resource name in the format `tagKeys/{id}`, such as * `tagKeys/123`. * * @return GTLRCloudResourceManagerQuery_TagKeysGet */ + (instancetype)queryWithName:(NSString *)name; @end /** * Gets the access control policy for a TagKey. The returned policy may be * empty if no such policy or resource exists. The `resource` field should be * the TagKey's resource name. For example, "tagKeys/1234". The caller must * have `cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy` permission * on the specified TagKey. * * Method: cloudresourcemanager.tagKeys.getIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_TagKeysGetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being requested. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Gets the access control policy for a TagKey. The returned policy may be * empty if no such policy or resource exists. The `resource` field should be * the TagKey's resource name. For example, "tagKeys/1234". The caller must * have `cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy` permission * on the specified TagKey. * * @param object The @c GTLRCloudResourceManager_GetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_TagKeysGetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_GetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Lists all TagKeys for a parent resource. * * Method: cloudresourcemanager.tagKeys.list * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_TagKeysList : GTLRCloudResourceManagerQuery /** * Optional. The maximum number of TagKeys to return in the response. The * server allows a maximum of 300 TagKeys to return. If unspecified, the server * will use 100 as the default. */ @property(nonatomic, assign) NSInteger pageSize; /** * Optional. A pagination token returned from a previous call to `ListTagKey` * that indicates where this listing should continue from. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Required. The resource name of the new TagKey's parent. Must be of the form * `folders/{folder_id}` or `organizations/{org_id}`. */ @property(nonatomic, copy, nullable) NSString *parent; /** * Fetches a @c GTLRCloudResourceManager_ListTagKeysResponse. * * Lists all TagKeys for a parent resource. * * @return GTLRCloudResourceManagerQuery_TagKeysList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)query; @end /** * Updates the attributes of the TagKey resource. * * Method: cloudresourcemanager.tagKeys.patch * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagKeysPatch : GTLRCloudResourceManagerQuery /** * Immutable. The resource name for a TagKey. Must be in the format * `tagKeys/{tag_key_id}`, where `tag_key_id` is the generated numeric id for * the TagKey. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fields to be updated. The mask may only contain `description` or `etag`. If * omitted entirely, both `description` and `etag` are assumed to be * significant. * * String format is a comma-separated list of fields. */ @property(nonatomic, copy, nullable) NSString *updateMask; /** * Set as true to perform validations necessary for updating the resource, but * not actually perform the action. */ @property(nonatomic, assign) BOOL validateOnly; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Updates the attributes of the TagKey resource. * * @param object The @c GTLRCloudResourceManager_TagKey to include in the * query. * @param name Immutable. The resource name for a TagKey. Must be in the format * `tagKeys/{tag_key_id}`, where `tag_key_id` is the generated numeric id for * the TagKey. * * @return GTLRCloudResourceManagerQuery_TagKeysPatch */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TagKey *)object name:(NSString *)name; @end /** * Sets the access control policy on a TagKey, replacing any existing policy. * The `resource` field should be the TagKey's resource name. For example, * "tagKeys/1234". The caller must have `resourcemanager.tagKeys.setIamPolicy` * permission on the identified tagValue. * * Method: cloudresourcemanager.tagKeys.setIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagKeysSetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being specified. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Sets the access control policy on a TagKey, replacing any existing policy. * The `resource` field should be the TagKey's resource name. For example, * "tagKeys/1234". The caller must have `resourcemanager.tagKeys.setIamPolicy` * permission on the identified tagValue. * * @param object The @c GTLRCloudResourceManager_SetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * specified. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_TagKeysSetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_SetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Returns permissions that a caller has on the specified TagKey. The * `resource` field should be the TagKey's resource name. For example, * "tagKeys/1234". There are no permissions required for making this API call. * * Method: cloudresourcemanager.tagKeys.testIamPermissions * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagKeysTestIamPermissions : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy detail is being requested. See * the operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_TestIamPermissionsResponse. * * Returns permissions that a caller has on the specified TagKey. The * `resource` field should be the TagKey's resource name. For example, * "tagKeys/1234". There are no permissions required for making this API call. * * @param object The @c GTLRCloudResourceManager_TestIamPermissionsRequest to * include in the query. * @param resource REQUIRED: The resource for which the policy detail is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_TagKeysTestIamPermissions */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TestIamPermissionsRequest *)object resource:(NSString *)resource; @end /** * Creates a TagValue as a child of the specified TagKey. If a another request * with the same parameters is sent while the original request is in process * the second request will receive an error. A maximum of 300 TagValues can * exist under a TagKey at any given time. * * Method: cloudresourcemanager.tagValues.create * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagValuesCreate : GTLRCloudResourceManagerQuery /** * Optional. Set as true to perform the validations necessary for creating the * resource, but not actually perform the action. */ @property(nonatomic, assign) BOOL validateOnly; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Creates a TagValue as a child of the specified TagKey. If a another request * with the same parameters is sent while the original request is in process * the second request will receive an error. A maximum of 300 TagValues can * exist under a TagKey at any given time. * * @param object The @c GTLRCloudResourceManager_TagValue to include in the * query. * * @return GTLRCloudResourceManagerQuery_TagValuesCreate */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TagValue *)object; @end /** * Deletes a TagValue. The TagValue cannot have any bindings when it is * deleted. * * Method: cloudresourcemanager.tagValues.delete * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagValuesDelete : GTLRCloudResourceManagerQuery /** * Optional. The etag known to the client for the expected state of the * TagValue. This is to be used for optimistic concurrency. */ @property(nonatomic, copy, nullable) NSString *ETag; /** * Required. Resource name for TagValue to be deleted in the format * tagValues/456. */ @property(nonatomic, copy, nullable) NSString *name; /** * Optional. Set as true to perform the validations necessary for deletion, but * not actually perform the action. */ @property(nonatomic, assign) BOOL validateOnly; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Deletes a TagValue. The TagValue cannot have any bindings when it is * deleted. * * @param name Required. Resource name for TagValue to be deleted in the format * tagValues/456. * * @return GTLRCloudResourceManagerQuery_TagValuesDelete */ + (instancetype)queryWithName:(NSString *)name; @end /** * Retrieves TagValue. If the TagValue or namespaced name does not exist, or if * the user does not have permission to view it, this method will return * `PERMISSION_DENIED`. * * Method: cloudresourcemanager.tagValues.get * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_TagValuesGet : GTLRCloudResourceManagerQuery /** * Required. Resource name for TagValue to be fetched in the format * `tagValues/456`. */ @property(nonatomic, copy, nullable) NSString *name; /** * Fetches a @c GTLRCloudResourceManager_TagValue. * * Retrieves TagValue. If the TagValue or namespaced name does not exist, or if * the user does not have permission to view it, this method will return * `PERMISSION_DENIED`. * * @param name Required. Resource name for TagValue to be fetched in the format * `tagValues/456`. * * @return GTLRCloudResourceManagerQuery_TagValuesGet */ + (instancetype)queryWithName:(NSString *)name; @end /** * Gets the access control policy for a TagValue. The returned policy may be * empty if no such policy or resource exists. The `resource` field should be * the TagValue's resource name. For example: `tagValues/1234`. The caller must * have the `cloudresourcemanager.googleapis.com/tagValues.getIamPolicy` * permission on the identified TagValue to get the access control policy. * * Method: cloudresourcemanager.tagValues.getIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_TagValuesGetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being requested. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Gets the access control policy for a TagValue. The returned policy may be * empty if no such policy or resource exists. The `resource` field should be * the TagValue's resource name. For example: `tagValues/1234`. The caller must * have the `cloudresourcemanager.googleapis.com/tagValues.getIamPolicy` * permission on the identified TagValue to get the access control policy. * * @param object The @c GTLRCloudResourceManager_GetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_TagValuesGetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_GetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Lists all TagValues for a specific TagKey. * * Method: cloudresourcemanager.tagValues.list * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform * @c kGTLRAuthScopeCloudResourceManagerCloudPlatformReadOnly */ @interface GTLRCloudResourceManagerQuery_TagValuesList : GTLRCloudResourceManagerQuery /** * Optional. The maximum number of TagValues to return in the response. The * server allows a maximum of 300 TagValues to return. If unspecified, the * server will use 100 as the default. */ @property(nonatomic, assign) NSInteger pageSize; /** * Optional. A pagination token returned from a previous call to * `ListTagValues` that indicates where this listing should continue from. */ @property(nonatomic, copy, nullable) NSString *pageToken; /** * Required. Resource name for TagKey, parent of the TagValues to be listed, in * the format `tagKeys/123`. */ @property(nonatomic, copy, nullable) NSString *parent; /** * Fetches a @c GTLRCloudResourceManager_ListTagValuesResponse. * * Lists all TagValues for a specific TagKey. * * @return GTLRCloudResourceManagerQuery_TagValuesList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)query; @end /** * Updates the attributes of the TagValue resource. * * Method: cloudresourcemanager.tagValues.patch * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagValuesPatch : GTLRCloudResourceManagerQuery /** Immutable. Resource name for TagValue in the format `tagValues/456`. */ @property(nonatomic, copy, nullable) NSString *name; /** * Optional. Fields to be updated. * * String format is a comma-separated list of fields. */ @property(nonatomic, copy, nullable) NSString *updateMask; /** * Optional. True to perform validations necessary for updating the resource, * but not actually perform the action. */ @property(nonatomic, assign) BOOL validateOnly; /** * Fetches a @c GTLRCloudResourceManager_Operation. * * Updates the attributes of the TagValue resource. * * @param object The @c GTLRCloudResourceManager_TagValue to include in the * query. * @param name Immutable. Resource name for TagValue in the format * `tagValues/456`. * * @return GTLRCloudResourceManagerQuery_TagValuesPatch */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TagValue *)object name:(NSString *)name; @end /** * Sets the access control policy on a TagValue, replacing any existing policy. * The `resource` field should be the TagValue's resource name. For example: * `tagValues/1234`. The caller must have * `resourcemanager.tagValues.setIamPolicy` permission on the identified * tagValue. * * Method: cloudresourcemanager.tagValues.setIamPolicy * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagValuesSetIamPolicy : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy is being specified. See the * operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_Policy. * * Sets the access control policy on a TagValue, replacing any existing policy. * The `resource` field should be the TagValue's resource name. For example: * `tagValues/1234`. The caller must have * `resourcemanager.tagValues.setIamPolicy` permission on the identified * tagValue. * * @param object The @c GTLRCloudResourceManager_SetIamPolicyRequest to include * in the query. * @param resource REQUIRED: The resource for which the policy is being * specified. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_TagValuesSetIamPolicy */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_SetIamPolicyRequest *)object resource:(NSString *)resource; @end /** * Returns permissions that a caller has on the specified TagValue. The * `resource` field should be the TagValue's resource name. For example: * `tagValues/1234`. There are no permissions required for making this API * call. * * Method: cloudresourcemanager.tagValues.testIamPermissions * * Authorization scope(s): * @c kGTLRAuthScopeCloudResourceManagerCloudPlatform */ @interface GTLRCloudResourceManagerQuery_TagValuesTestIamPermissions : GTLRCloudResourceManagerQuery /** * REQUIRED: The resource for which the policy detail is being requested. See * the operation documentation for the appropriate value for this field. */ @property(nonatomic, copy, nullable) NSString *resource; /** * Fetches a @c GTLRCloudResourceManager_TestIamPermissionsResponse. * * Returns permissions that a caller has on the specified TagValue. The * `resource` field should be the TagValue's resource name. For example: * `tagValues/1234`. There are no permissions required for making this API * call. * * @param object The @c GTLRCloudResourceManager_TestIamPermissionsRequest to * include in the query. * @param resource REQUIRED: The resource for which the policy detail is being * requested. See the operation documentation for the appropriate value for * this field. * * @return GTLRCloudResourceManagerQuery_TagValuesTestIamPermissions */ + (instancetype)queryWithObject:(GTLRCloudResourceManager_TestIamPermissionsRequest *)object resource:(NSString *)resource; @end NS_ASSUME_NONNULL_END #pragma clang diagnostic pop
39.468441
126
0.753824
[ "render", "object" ]
7fd72a698b4da84bd7ca022226957887a89a60e8
4,122
h
C
d2dcustomeffects/cpp/vertexshader/deviceresources.h
kaid7pro/old-Windows-universal-samples
f97d2b880420fff7bcf7ea0aaf20ee837c002d7d
[ "MIT" ]
6
2015-12-23T22:28:56.000Z
2021-11-06T17:05:51.000Z
d2dcustomeffects/cpp/vertexshader/deviceresources.h
y3key/Windows-universal-samples
f97d2b880420fff7bcf7ea0aaf20ee837c002d7d
[ "MIT" ]
null
null
null
d2dcustomeffects/cpp/vertexshader/deviceresources.h
y3key/Windows-universal-samples
f97d2b880420fff7bcf7ea0aaf20ee837c002d7d
[ "MIT" ]
8
2015-10-26T01:44:51.000Z
2022-03-12T09:47:56.000Z
#pragma once namespace DX { // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created. interface IDeviceNotify { virtual void OnDeviceLost() = 0; virtual void OnDeviceRestored() = 0; }; // Controls all the DirectX device resources. class DeviceResources { public: DeviceResources(); void SetWindow(Windows::UI::Core::CoreWindow^ window); void SetLogicalSize(Windows::Foundation::Size logicalSize); void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation); void SetDpi(float dpi); void ValidateDevice(); void HandleDeviceLost(); void RegisterDeviceNotify(IDeviceNotify* deviceNotify); void Trim(); void Present(); // Device Accessors. Windows::Foundation::Size GetOutputSize() const { return m_outputSize; } Windows::Foundation::Size GetLogicalSize() const { return m_logicalSize; } // D3D Accessors. ID3D11Device2* GetD3DDevice() const { return m_d3dDevice.Get(); } ID3D11DeviceContext3* GetD3DDeviceContext() const { return m_d3dContext.Get(); } IDXGISwapChain1* GetSwapChain() const { return m_swapChain.Get(); } D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const { return m_d3dFeatureLevel; } ID3D11RenderTargetView* GetBackBufferRenderTargetView() const { return m_d3dRenderTargetView.Get(); } ID3D11DepthStencilView* GetDepthStencilView() const { return m_d3dDepthStencilView.Get(); } D3D11_VIEWPORT GetScreenViewport() const { return m_screenViewport; } DirectX::XMFLOAT4X4 GetOrientationTransform3D() const { return m_orientationTransform3D; } // D2D Accessors. ID2D1Factory3* GetD2DFactory() const { return m_d2dFactory.Get(); } ID2D1Device2* GetD2DDevice() const { return m_d2dDevice.Get(); } ID2D1DeviceContext2* GetD2DDeviceContext() const { return m_d2dContext.Get(); } ID2D1Bitmap1* GetD2DTargetBitmap() const { return m_d2dTargetBitmap.Get(); } IDWriteFactory2* GetDWriteFactory() const { return m_dwriteFactory.Get(); } IWICImagingFactory2* GetWicImagingFactory() const { return m_wicFactory.Get(); } D2D1::Matrix3x2F GetOrientationTransform2D() const { return m_orientationTransform2D; } private: void CreateDeviceIndependentResources(); void CreateDeviceResources(); void CreateWindowSizeDependentResources(); DXGI_MODE_ROTATION ComputeDisplayRotation(); // Direct3D objects. Microsoft::WRL::ComPtr<ID3D11Device2> m_d3dDevice; Microsoft::WRL::ComPtr<ID3D11DeviceContext3> m_d3dContext; Microsoft::WRL::ComPtr<IDXGISwapChain1> m_swapChain; // Direct3D rendering objects. Required for 3D. Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_d3dRenderTargetView; Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_d3dDepthStencilView; D3D11_VIEWPORT m_screenViewport; // Direct2D drawing components. Microsoft::WRL::ComPtr<ID2D1Factory3> m_d2dFactory; Microsoft::WRL::ComPtr<ID2D1Device2> m_d2dDevice; Microsoft::WRL::ComPtr<ID2D1DeviceContext2> m_d2dContext; Microsoft::WRL::ComPtr<ID2D1Bitmap1> m_d2dTargetBitmap; // DirectWrite drawing components. Microsoft::WRL::ComPtr<IDWriteFactory2> m_dwriteFactory; Microsoft::WRL::ComPtr<IWICImagingFactory2> m_wicFactory; // Cached reference to the Window. Platform::Agile<Windows::UI::Core::CoreWindow> m_window; // Cached device properties. D3D_FEATURE_LEVEL m_d3dFeatureLevel; Windows::Foundation::Size m_d3dRenderTargetSize; Windows::Foundation::Size m_outputSize; Windows::Foundation::Size m_logicalSize; Windows::Graphics::Display::DisplayOrientations m_nativeOrientation; Windows::Graphics::Display::DisplayOrientations m_currentOrientation; float m_dpi; // Transforms used for display orientation. D2D1::Matrix3x2F m_orientationTransform2D; DirectX::XMFLOAT4X4 m_orientationTransform3D; // The IDeviceNotify can be held directly as it owns the DeviceResources. IDeviceNotify* m_deviceNotify; }; }
43.389474
126
0.743086
[ "3d" ]
7fd7c836e2290284a2f99ab3c5f8ad0c11b3b13a
2,483
h
C
src/script/descriptor.h
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
13
2019-01-23T04:36:05.000Z
2022-02-21T11:20:25.000Z
src/script/descriptor.h
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
null
null
null
src/script/descriptor.h
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
3
2019-01-24T07:48:15.000Z
2021-06-11T13:34:44.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2018比特币核心开发者 //根据MIT软件许可证分发,请参见随附的 //文件复制或http://www.opensource.org/licenses/mit-license.php。 #ifndef BITCOIN_SCRIPT_DESCRIPTOR_H #define BITCOIN_SCRIPT_DESCRIPTOR_H #include <script/script.h> #include <script/sign.h> #include <vector> //描述符是描述一组scriptPubKeys的字符串,以及 //解决问题所需的所有信息。将所有信息合并到 //第一,它们避免了分别导入键和脚本的需要。 // //描述符可以是范围的,当其中的公钥是 //以HD链(xpubs)的形式指定。 // //描述符始终表示公共信息-公钥和脚本- //但是在需要将私钥与描述符一起传送的情况下, //通过将公钥更改为私钥(WIF)可以将它们包含在内部 //格式),并按xprvs更改xpubs。 // //有关描述符语言的参考文档可在 //文档/描述符.md. /*用于解析的描述符对象的接口。*/ struct Descriptor { virtual ~Descriptor() = default; /*此描述符的扩展是否取决于位置。*/ virtual bool IsRange() const = 0; /*此描述符是否具有有关忽略缺少私钥的签名的所有信息。 *除使用“raw”或“addr”结构的描述符外,所有描述符都是如此。*/ virtual bool IsSolvable() const = 0; /*将描述符转换回字符串,撤消解析。*/ virtual std::string ToString() const = 0; /*将描述符转换为私有字符串。如果提供的提供程序没有相关的私钥,则此操作失败。*/ virtual bool ToPrivateString(const SigningProvider& provider, std::string& out) const = 0; /*在指定位置展开描述符。 * *pos:扩展描述符的位置。如果isrange()为false,则忽略它。 *provider:在硬派生的情况下查询私钥的提供程序。 *输出脚本:将在此处放置扩展的scriptPubKeys。 *out:将在此处放置解决扩展的scriptPubKeys所需的脚本和公钥(可能等于提供程序)。 *缓存:矢量,将被缓存数据覆盖,此时需要评估描述符,而不访问私钥。 **/ virtual bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, std::vector<unsigned char>* cache = nullptr) const = 0; /*使用缓存的扩展数据在指定位置展开描述符。 * *pos:扩展描述符的位置。如果isrange()为false,则忽略它。 *缓存:从中读取缓存的扩展数据的向量。 *输出脚本:将在此处放置扩展的scriptPubKeys。 *out:将在此处放置解决扩展的scriptPubKeys所需的脚本和公钥(可能等于提供程序)。 **/ virtual bool ExpandFromCache(int pos, const std::vector<unsigned char>& cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const = 0; }; /*分析描述符字符串。包含的私钥将被放入。如果分析失败,则返回nullptr。*/ std::unique_ptr<Descriptor> Parse(const std::string& descriptor, FlatSigningProvider& out); /*尽可能使用提供者提供的信息查找指定脚本的描述符。 * *只生成指定脚本的非范围描述符将全部返回 *环境。 * *对于带有密钥来源信息的公钥,此信息将保存在返回的 *描述符。 * *-如果“provider”中存在解决“script”问题的所有信息,则将返回描述符。 *它是“issolvable()”,并封装了所述信息。 *-如果失败,则如果“script”对应于已知的地址类型,“addr()”描述符将 *返回(不是'issolvable()`)。 *-如果失败,则返回“raw()”描述符。 **/ std::unique_ptr<Descriptor> InferDescriptor(const CScript& script, const SigningProvider& provider); #endif //比特币脚本描述符
25.597938
185
0.730165
[ "vector" ]
7fd972f145106d895b7489d002d1f7f1aa56b08a
9,612
c
C
filters/GStreamer/CustomFilter/src/gstcustomfilter.c
0x384c0/ffmpeg-Experiments
e1531cfe5b5cafdaeca72d545c5b6528546f074f
[ "MIT" ]
2
2017-02-08T07:38:15.000Z
2017-04-17T10:50:07.000Z
filters/GStreamer/CustomFilter/src/gstcustomfilter.c
0x384c0/ffmpeg-Experiments
e1531cfe5b5cafdaeca72d545c5b6528546f074f
[ "MIT" ]
null
null
null
filters/GStreamer/CustomFilter/src/gstcustomfilter.c
0x384c0/ffmpeg-Experiments
e1531cfe5b5cafdaeca72d545c5b6528546f074f
[ "MIT" ]
null
null
null
/* * GStreamer * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org> * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net> * Copyright (C) 2019 <<user@hostname.org>> * * 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. * * Alternatively, the contents of this file may be used under the * GNU Lesser General Public License Version 2.1 (the "LGPL"), in * which case the following provisions apply instead of the ones * mentioned above: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * SECTION:element-customfilter * * FIXME:Describe customfilter here. * * <refsect2> * <title>Example launch line</title> * |[ * gst-launch -v -m fakesrc ! customfilter ! fakesink silent=TRUE * ]| * </refsect2> */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <stdio.h> #include <gst/gst.h> #include <gst/audio/audio.h> #include <gst/audio/gstaudiofilter.h> #include "gstcustomfilter.h" GST_DEBUG_CATEGORY_STATIC (gst_custom_filter_debug); #define GST_CAT_DEFAULT gst_custom_filter_debug /* Filter signals and args */ enum { /* FILL ME */ LAST_SIGNAL }; enum { PROP_0, PROP_SILENT }; /* the capabilities of the inputs and outputs. * * describe the real formats here. */ static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ( "audio/x-raw, " "format = (string) " GST_AUDIO_NE (S16) ", " "channels = (int) { 1, 2 }, " "rate = (int) [ 8000, 96000 ]" ) ); static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS ( "audio/x-raw, " //video/x-raw-rgb "format = (string) " GST_AUDIO_NE (S16) ", " "channels = (int) { 1, 2 }, " "rate = (int) [ 8000, 96000 ]" ) ); #define gst_custom_filter_parent_class parent_class G_DEFINE_TYPE (GstCustomFilter, gst_custom_filter, GST_TYPE_ELEMENT); static void gst_custom_filter_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_custom_filter_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static gboolean gst_custom_filter_sink_event (GstPad * pad, GstObject * parent, GstEvent * event); static GstFlowReturn gst_custom_filter_chain (GstPad * pad, GstObject * parent, GstBuffer * buf); /* GObject vmethod implementations */ /* initialize the customfilter's class */ static void gst_custom_filter_class_init (GstCustomFilterClass * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; gobject_class->set_property = gst_custom_filter_set_property; gobject_class->get_property = gst_custom_filter_get_property; g_object_class_install_property (gobject_class, PROP_SILENT, g_param_spec_boolean ("silent", "Silent", "Produce verbose output ?", FALSE, G_PARAM_READWRITE)); gst_element_class_set_details_simple(gstelement_class, "CustomFilter", "FIXME:Generic", "FIXME:Generic Template Element", " <<user@hostname.org>>"); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&src_factory)); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&sink_factory)); } /* initialize the new element * instantiate pads and add them to element * set pad calback functions * initialize instance structure */ static void gst_custom_filter_init (GstCustomFilter * filter) { filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink"); gst_pad_set_event_function (filter->sinkpad, GST_DEBUG_FUNCPTR(gst_custom_filter_sink_event)); gst_pad_set_chain_function (filter->sinkpad, GST_DEBUG_FUNCPTR(gst_custom_filter_chain)); GST_PAD_SET_PROXY_CAPS (filter->sinkpad); gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad); filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src"); GST_PAD_SET_PROXY_CAPS (filter->srcpad); gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad); filter->silent = FALSE; } static void gst_custom_filter_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstCustomFilter *filter = GST_CUSTOMFILTER (object); switch (prop_id) { case PROP_SILENT: filter->silent = g_value_get_boolean (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_custom_filter_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstCustomFilter *filter = GST_CUSTOMFILTER (object); switch (prop_id) { case PROP_SILENT: g_value_set_boolean (value, filter->silent); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } /* GstElement vmethod implementations */ /* this function handles sink events */ static gboolean gst_custom_filter_sink_event (GstPad * pad, GstObject * parent, GstEvent * event) { GstCustomFilter *filter; gboolean ret; filter = GST_CUSTOMFILTER (parent); GST_LOG_OBJECT (filter, "Received %s event: %" GST_PTR_FORMAT, GST_EVENT_TYPE_NAME (event), event); switch (GST_EVENT_TYPE (event)) { case GST_EVENT_CAPS: { GstCaps * caps; gst_event_parse_caps (event, &caps); /* do something with the caps */ /* and forward */ ret = gst_pad_event_default (pad, parent, event); break; } default: ret = gst_pad_event_default (pad, parent, event); break; } return ret; } /* chain function * this function does the actual processing */ static GstFlowReturn gst_custom_filter_chain (GstPad * pad, GstObject * parent, GstBuffer * buf) { GstCustomFilter *filter; filter = GST_CUSTOMFILTER (parent); if (filter->silent == FALSE) fprintf( stderr, "Have data of size %" G_GSIZE_FORMAT" bytes!\n", gst_buffer_get_size (buf)); //process audio samples GstBuffer * bufWritable = gst_buffer_make_writable(buf); //make buffer writable GstMapInfo info; gst_buffer_map(bufWritable,&info,GST_MAP_READWRITE); //get momory with samples for (gsize i = 0; i < info.size; i++) info.data[i] *= 2; //amplify samples gst_buffer_unmap(bufWritable,&info); //put samples back /* just push out the incoming buffer without touching it */ return gst_pad_push (filter->srcpad, bufWritable); } /* entry point to initialize the plug-in * initialize the plug-in itself * register the element factories and other features */ static gboolean customfilter_init (GstPlugin * customfilter) { /* debug category for fltering log messages * * exchange the string 'Template customfilter' with your description */ GST_DEBUG_CATEGORY_INIT (gst_custom_filter_debug, "customfilter", 0, "Template customfilter"); return gst_element_register (customfilter, "customfilter", GST_RANK_NONE, GST_TYPE_CUSTOMFILTER); } /* PACKAGE: this is usually set by autotools depending on some _INIT macro * in configure.ac and then written into and defined in config.h, but we can * just set it ourselves here in case someone doesn't use autotools to * compile this code. GST_PLUGIN_DEFINE needs PACKAGE to be defined. */ #ifndef PACKAGE #define PACKAGE "myfirstcustomfilter" #endif /* gstreamer looks for this structure to register plugins * * exchange the string 'Template customfilter' with your customfilter description */ GST_PLUGIN_DEFINE ( GST_VERSION_MAJOR, GST_VERSION_MINOR, customfilter, "Template customfilter", customfilter_init, PACKAGE_VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN )
30.514286
98
0.726904
[ "object" ]
7fdd7527d59f30d16a8f97cc0a54e2e4c9e87a6b
5,854
h
C
ev/external/abseil-cpp/absl/debugging/internal/vdso_support.h
sergiorr/yastack
17cdc12a52ea5869f429aa8ec421c3d1d25b32e7
[ "Apache-2.0" ]
91
2018-11-24T05:33:58.000Z
2022-03-16T05:58:05.000Z
ev/external/abseil-cpp/absl/debugging/internal/vdso_support.h
sergiorr/yastack
17cdc12a52ea5869f429aa8ec421c3d1d25b32e7
[ "Apache-2.0" ]
11
2019-06-02T23:50:17.000Z
2022-02-04T23:58:56.000Z
ev/external/abseil-cpp/absl/debugging/internal/vdso_support.h
sergiorr/yastack
17cdc12a52ea5869f429aa8ec421c3d1d25b32e7
[ "Apache-2.0" ]
18
2018-11-24T10:35:29.000Z
2021-04-22T07:22:10.000Z
// // Copyright 2017 The Abseil Authors. // // 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. // // Allow dynamic symbol lookup in the kernel VDSO page. // // VDSO stands for "Virtual Dynamic Shared Object" -- a page of // executable code, which looks like a shared library, but doesn't // necessarily exist anywhere on disk, and which gets mmap()ed into // every process by kernels which support VDSO, such as 2.6.x for 32-bit // executables, and 2.6.24 and above for 64-bit executables. // // More details could be found here: // http://www.trilithium.com/johan/2005/08/linux-gate/ // // VDSOSupport -- a class representing kernel VDSO (if present). // // Example usage: // VDSOSupport vdso; // VDSOSupport::SymbolInfo info; // typedef (*FN)(unsigned *, void *, void *); // FN fn = nullptr; // if (vdso.LookupSymbol("__vdso_getcpu", "LINUX_2.6", STT_FUNC, &info)) { // fn = reinterpret_cast<FN>(info.address); // } #ifndef ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_ #define ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_ #include <atomic> #include "absl/base/attributes.h" #include "absl/debugging/internal/elf_mem_image.h" #ifdef ABSL_HAVE_ELF_MEM_IMAGE #ifdef ABSL_HAVE_VDSO_SUPPORT #error ABSL_HAVE_VDSO_SUPPORT cannot be directly set #else #define ABSL_HAVE_VDSO_SUPPORT 1 #endif namespace absl { inline namespace lts_2018_06_20 { namespace debugging_internal { // NOTE: this class may be used from within tcmalloc, and can not // use any memory allocation routines. class VDSOSupport { public: VDSOSupport(); typedef ElfMemImage::SymbolInfo SymbolInfo; typedef ElfMemImage::SymbolIterator SymbolIterator; // On PowerPC64 VDSO symbols can either be of type STT_FUNC or STT_NOTYPE // depending on how the kernel is built. The kernel is normally built with // STT_NOTYPE type VDSO symbols. Let's make things simpler first by using a // compile-time constant. #ifdef __powerpc64__ enum { kVDSOSymbolType = STT_NOTYPE }; #else enum { kVDSOSymbolType = STT_FUNC }; #endif // Answers whether we have a vdso at all. bool IsPresent() const { return image_.IsPresent(); } // Allow to iterate over all VDSO symbols. SymbolIterator begin() const { return image_.begin(); } SymbolIterator end() const { return image_.end(); } // Look up versioned dynamic symbol in the kernel VDSO. // Returns false if VDSO is not present, or doesn't contain given // symbol/version/type combination. // If info_out != nullptr, additional details are filled in. bool LookupSymbol(const char *name, const char *version, int symbol_type, SymbolInfo *info_out) const; // Find info about symbol (if any) which overlaps given address. // Returns true if symbol was found; false if VDSO isn't present // or doesn't have a symbol overlapping given address. // If info_out != nullptr, additional details are filled in. bool LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const; // Used only for testing. Replace real VDSO base with a mock. // Returns previous value of vdso_base_. After you are done testing, // you are expected to call SetBase() with previous value, in order to // reset state to the way it was. const void *SetBase(const void *s); // Computes vdso_base_ and returns it. Should be called as early as // possible; before any thread creation, chroot or setuid. static const void *Init(); private: // image_ represents VDSO ELF image in memory. // image_.ehdr_ == nullptr implies there is no VDSO. ElfMemImage image_; // Cached value of auxv AT_SYSINFO_EHDR, computed once. // This is a tri-state: // kInvalidBase => value hasn't been determined yet. // 0 => there is no VDSO. // else => vma of VDSO Elf{32,64}_Ehdr. // // When testing with mock VDSO, low bit is set. // The low bit is always available because vdso_base_ is // page-aligned. static std::atomic<const void *> vdso_base_; // NOLINT on 'long' because these routines mimic kernel api. // The 'cache' parameter may be used by some versions of the kernel, // and should be nullptr or point to a static buffer containing at // least two 'long's. static long InitAndGetCPU(unsigned *cpu, void *cache, // NOLINT 'long'. void *unused); static long GetCPUViaSyscall(unsigned *cpu, void *cache, // NOLINT 'long'. void *unused); typedef long (*GetCpuFn)(unsigned *cpu, void *cache, // NOLINT 'long'. void *unused); // This function pointer may point to InitAndGetCPU, // GetCPUViaSyscall, or __vdso_getcpu at different stages of initialization. ABSL_CONST_INIT static std::atomic<GetCpuFn> getcpu_fn_; friend int GetCPU(void); // Needs access to getcpu_fn_. VDSOSupport(const VDSOSupport&) = delete; VDSOSupport& operator=(const VDSOSupport&) = delete; }; // Same as sched_getcpu() on later glibc versions. // Return current CPU, using (fast) __vdso_getcpu@LINUX_2.6 if present, // otherwise use syscall(SYS_getcpu,...). // May return -1 with errno == ENOSYS if the kernel doesn't // support SYS_getcpu. int GetCPU(); } // namespace debugging_internal } // inline namespace lts_2018_06_20 } // namespace absl #endif // ABSL_HAVE_ELF_MEM_IMAGE #endif // ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_
36.81761
78
0.713871
[ "object" ]
7fdf7a691aace8f0f088eb79820035066a76853c
1,476
h
C
src/qt/qrdialog.h
microftech65/syscoin
f1009e323a153095e1151c3abe173c8fb801b16c
[ "MIT" ]
null
null
null
src/qt/qrdialog.h
microftech65/syscoin
f1009e323a153095e1151c3abe173c8fb801b16c
[ "MIT" ]
null
null
null
src/qt/qrdialog.h
microftech65/syscoin
f1009e323a153095e1151c3abe173c8fb801b16c
[ "MIT" ]
null
null
null
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef SYSCOIN_QT_QRDIALOG_H #define SYSCOIN_QT_QRDIALOG_H #include <qt/walletmodel.h> #include <QDialog> #include <QImage> #include <QLabel> class OptionsModel; namespace Ui { class QRDialog; } QT_BEGIN_NAMESPACE class QMenu; QT_END_NAMESPACE /* Label widget for QR code. This image can be dragged, dropped, copied and saved * to disk. */ class QRGeneralImageWidget : public QLabel { Q_OBJECT public: explicit QRGeneralImageWidget(QWidget *parent = 0); QImage exportImage(); public Q_SLOTS: void saveImage(); void copyImage(); protected: virtual void mousePressEvent(QMouseEvent *event); virtual void contextMenuEvent(QContextMenuEvent *event); private: QMenu *contextMenu; }; class QRDialog : public QDialog { Q_OBJECT public: explicit QRDialog(QWidget *parent = 0); ~QRDialog(); void setModel(OptionsModel *model); void setInfo(QString strWindowtitle, QString strQRCode, QString strTextInfo, QString strQRCodeTitle); private Q_SLOTS: void update(); private: Ui::QRDialog *ui; OptionsModel *model; QString strWindowtitle; QString strQRCode; QString strTextInfo; QString strQRCodeTitle; }; #endif // SYSCOIN_QT_QRDIALOG_H
20.5
105
0.737805
[ "model" ]
7fe11a7eb372ea4596ff167d856e86735334a0c2
5,369
h
C
modules/audio_coding/codecs/g722/include/g722_interface.h
whxcctv/I-Love-Web_Rtc
975c17f938d2b7eb550c134d8e0aea497ef8d76d
[ "DOC", "BSD-3-Clause" ]
null
null
null
modules/audio_coding/codecs/g722/include/g722_interface.h
whxcctv/I-Love-Web_Rtc
975c17f938d2b7eb550c134d8e0aea497ef8d76d
[ "DOC", "BSD-3-Clause" ]
2
2019-01-16T13:52:47.000Z
2019-02-03T11:34:44.000Z
modules/audio_coding/codecs/g722/include/g722_interface.h
svn2github/webrtc-Revision-8758
fe5f663cdf54162e750a6281c302e11c5629030c
[ "DOC", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MODULES_AUDIO_CODING_CODECS_G722_MAIN_INTERFACE_G722_INTERFACE_H_ #define MODULES_AUDIO_CODING_CODECS_G722_MAIN_INTERFACE_G722_INTERFACE_H_ #include "webrtc/typedefs.h" /* * Solution to support multiple instances */ typedef struct WebRtcG722EncInst G722EncInst; typedef struct WebRtcG722DecInst G722DecInst; /* * Comfort noise constants */ #define G722_WEBRTC_SPEECH 1 #define G722_WEBRTC_CNG 2 #ifdef __cplusplus extern "C" { #endif /**************************************************************************** * WebRtcG722_CreateEncoder(...) * * Create memory used for G722 encoder * * Input: * - G722enc_inst : G722 instance for encoder * * Return value : 0 - Ok * -1 - Error */ int16_t WebRtcG722_CreateEncoder(G722EncInst **G722enc_inst); /**************************************************************************** * WebRtcG722_EncoderInit(...) * * This function initializes a G722 instance * * Input: * - G722enc_inst : G722 instance, i.e. the user that should receive * be initialized * * Return value : 0 - Ok * -1 - Error */ int16_t WebRtcG722_EncoderInit(G722EncInst *G722enc_inst); /**************************************************************************** * WebRtcG722_FreeEncoder(...) * * Free the memory used for G722 encoder * * Input: * - G722enc_inst : G722 instance for encoder * * Return value : 0 - Ok * -1 - Error */ int16_t WebRtcG722_FreeEncoder(G722EncInst *G722enc_inst); /**************************************************************************** * WebRtcG722_Encode(...) * * This function encodes G722 encoded data. * * Input: * - G722enc_inst : G722 instance, i.e. the user that should encode * a packet * - speechIn : Input speech vector * - len : Samples in speechIn * * Output: * - encoded : The encoded data vector * * Return value : Length (in bytes) of coded data */ int16_t WebRtcG722_Encode(G722EncInst* G722enc_inst, const int16_t* speechIn, int16_t len, uint8_t* encoded); /**************************************************************************** * WebRtcG722_CreateDecoder(...) * * Create memory used for G722 encoder * * Input: * - G722dec_inst : G722 instance for decoder * * Return value : 0 - Ok * -1 - Error */ int16_t WebRtcG722_CreateDecoder(G722DecInst **G722dec_inst); /**************************************************************************** * WebRtcG722_DecoderInit(...) * * This function initializes a G729 instance * * Input: * - G729_decinst_t : G729 instance, i.e. the user that should receive * be initialized * * Return value : 0 - Ok * -1 - Error */ int16_t WebRtcG722_DecoderInit(G722DecInst *G722dec_inst); /**************************************************************************** * WebRtcG722_FreeDecoder(...) * * Free the memory used for G722 decoder * * Input: * - G722dec_inst : G722 instance for decoder * * Return value : 0 - Ok * -1 - Error */ int16_t WebRtcG722_FreeDecoder(G722DecInst *G722dec_inst); /**************************************************************************** * WebRtcG722_Decode(...) * * This function decodes a packet with G729 frame(s). Output speech length * will be a multiple of 80 samples (80*frames/packet). * * Input: * - G722dec_inst : G722 instance, i.e. the user that should decode * a packet * - encoded : Encoded G722 frame(s) * - len : Bytes in encoded vector * * Output: * - decoded : The decoded vector * - speechType : 1 normal, 2 CNG (Since G722 does not have its own * DTX/CNG scheme it should always return 1) * * Return value : >0 - Samples in decoded vector * -1 - Error */ int16_t WebRtcG722_Decode(G722DecInst *G722dec_inst, const uint8_t* encoded, int16_t len, int16_t *decoded, int16_t *speechType); /**************************************************************************** * WebRtcG722_Version(...) * * Get a string with the current version of the codec */ int16_t WebRtcG722_Version(char *versionStr, short len); #ifdef __cplusplus } #endif #endif /* MODULES_AUDIO_CODING_CODECS_G722_MAIN_INTERFACE_G722_INTERFACE_H_ */
28.257895
80
0.508661
[ "vector" ]
7fe12de57674b694ac33c46bd676413905100b56
26,096
c
C
libsks/src/serialize_ck.c
foundriesio/optee_client
2e92e5ea56aea39c828521ecb9552ea5a6864eea
[ "BSD-2-Clause" ]
1
2021-08-14T21:22:06.000Z
2021-08-14T21:22:06.000Z
libsks/src/serialize_ck.c
foundriesio/optee_client
2e92e5ea56aea39c828521ecb9552ea5a6864eea
[ "BSD-2-Clause" ]
null
null
null
libsks/src/serialize_ck.c
foundriesio/optee_client
2e92e5ea56aea39c828521ecb9552ea5a6864eea
[ "BSD-2-Clause" ]
1
2021-08-14T21:22:08.000Z
2021-08-14T21:22:08.000Z
/* * Copyright (c) 2017-2018, Linaro Limited * * SPDX-License-Identifier: BSD-2-Clause */ #include <pkcs11.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <sks_ck_debug.h> #include <sks_ta.h> #include "ck_helpers.h" #include "local_utils.h" #include "serializer.h" #include "serialize_ck.h" /* * Generic way of serializing CK keys, certif, mechanism parameters, ... * In cryptoki 2.40 parameters are almost all packaged as struture below: */ struct ck_ref { CK_ULONG id; CK_BYTE_PTR ptr; CK_ULONG len; }; #if 0 /* * Append cryptoki generic buffer reference structure into a sks serial * object. * * ck_ref points to a structure aligned CK reference (attributes or else) */ static CK_RV serialize_ck_ref(struct serializer *obj, void *ck_ref) { struct ck_ref *ref = ck_ref; CK_RV rv; rv = serialize_ck_ulong(obj, ref->id); if (rv) return rv; rv = serialize_ck_ulong(obj, ref->len); if (rv) return rv; rv = serialize_buffer(obj, ref->ptr, ref->len); if (rv) return rv; obj->item_count++; return rv; } /* * ck_ref points to a structure aligned CK reference (attributes or else) * * Same as serialize_ck_ref but reference is a ULONG so the blob size * to be set accoring to the 32bit/64bit configuration of target CK ABI. */ static CK_RV serialize_ulong_ck_ref(struct serializer *obj, void *ck_ref) { struct ck_ref *ref = ck_ref; CK_ULONG ck_value; uint32_t sks_value; CK_RV rv; rv = serialize_ck_ulong(obj, ref->id); if (rv) return rv; rv = serialize_ck_ulong(obj, sizeof(sks_value)); if (rv) return rv; memcpy(&ck_value, ref->ptr, sizeof(CK_ULONG)); sks_value = ck_value; rv = serialize_buffer(obj, &sks_value, sizeof(sks_value)); if (rv) return rv; obj->item_count++; return rv; } #endif /* * This is for attributes that contains data memory indirections. * In other words, an attributes that defines a list of attributes. * They are identified from the attribute type CKA_... * * @obj - ref used to track the serial object being created * @attribute - pointer to a structure aligned of the CK_ATTRIBUTE struct */ static CK_RV serialize_indirect_attribute(struct serializer *obj, CK_ATTRIBUTE_PTR attribute) { CK_ATTRIBUTE_PTR attr; CK_ULONG count; CK_RV rv; struct serializer obj2; switch (attribute->type) { /* These are serialized each seperately */ case CKA_WRAP_TEMPLATE: case CKA_UNWRAP_TEMPLATE: count = attribute->ulValueLen / sizeof(CK_ATTRIBUTE); attr = (CK_ATTRIBUTE_PTR)attribute->pValue; break; default: return CKR_NO_EVENT; } /* Create a serialized object for the content */ rv = serialize_ck_attributes(&obj2, attr, count); if (rv) return rv; /* * Append the created serialized object into target object: * [attrib-id][byte-size][attributes-data] */ rv = serialize_32b(obj, ck2sks_attribute_type(attribute->type)); if (rv) return rv; rv = serialize_32b(obj, obj2.size); if (rv) return rv; rv = serialize_buffer(obj, obj2.buffer, obj2.size); if (rv) return rv; obj->item_count++; return rv; } static CK_RV deserialize_indirect_attribute(struct sks_attribute_head *obj, CK_ATTRIBUTE_PTR attribute) { CK_ULONG count; CK_ATTRIBUTE_PTR attr; CK_RV rv; switch (attribute->type) { /* These are serialized each seperately */ case CKA_WRAP_TEMPLATE: case CKA_UNWRAP_TEMPLATE: count = attribute->ulValueLen / sizeof(CK_ATTRIBUTE); attr = (CK_ATTRIBUTE_PTR)attribute->pValue; break; default: return CKR_GENERAL_ERROR; } /* * deserialize_ck_attributes expects sks_attribute_head, * not sks_object_head, so we need to correct the pointer */ rv = deserialize_ck_attributes(obj->data, attr, count); return rv; } static int ck_attr_is_ulong(CK_ATTRIBUTE_TYPE attribute_id) { return (ck_attr_is_class(attribute_id) || ck_attr_is_type(attribute_id) || attribute_id == CKA_VALUE_LEN || attribute_id == CKA_CERTIFICATE_CATEGORY || attribute_id == CKA_NAME_HASH_ALGORITHM || attribute_id == CKA_MODULUS_BITS); } static CK_RV serialize_ck_attribute(struct serializer *obj, CK_ATTRIBUTE *attr) { uint32_t sks_id = SKS_UNDEFINED_ID; uint32_t sks_size = 0; uint32_t sks_data32; void *sks_pdata; int sks_pdata_alloced = 0; CK_ULONG ck_ulong = 0; /* keep compiler happy */ CK_RV rv; unsigned int n; unsigned int m; /* Expect only those from the identification table */ sks_id = ck2sks_attribute_type(attr->type); if (sks_id == SKS_UNDEFINED_ID) return CKR_ATTRIBUTE_TYPE_INVALID; if (ck_attr_is_ulong(attr->type)) { /* PKCS#11 CK_ULONG are use */ if (attr->ulValueLen != sizeof(CK_ULONG)) return CKR_ATTRIBUTE_TYPE_INVALID; memcpy(&ck_ulong, attr->pValue, sizeof(ck_ulong)); } switch (attr->type) { case CKA_CLASS: sks_data32 = ck2sks_object_class(ck_ulong); sks_pdata = &sks_data32; sks_size = sizeof(uint32_t); break; case CKA_KEY_TYPE: sks_data32 = ck2sks_key_type(ck_ulong); sks_pdata = &sks_data32; sks_size = sizeof(uint32_t); break; case CKA_CERTIFICATE_TYPE: sks_data32 = ck2sks_certificate_type(ck_ulong); sks_pdata = &sks_data32; sks_size = sizeof(uint32_t); break; case CKA_WRAP_TEMPLATE: case CKA_UNWRAP_TEMPLATE: return serialize_indirect_attribute(obj, attr); case CKA_ALLOWED_MECHANISMS: n = attr->ulValueLen / sizeof(CK_ULONG); sks_size = n * sizeof(uint32_t); sks_pdata = malloc(sks_size); if (!sks_pdata) return CKR_HOST_MEMORY; sks_pdata_alloced = 1; for (m = 0; m < n; m++) { CK_MECHANISM_TYPE *type = attr->pValue; sks_data32 = ck2sks_mechanism_type(type[m]); if (sks_data32 == SKS_UNDEFINED_ID) { free(sks_pdata); return CKR_MECHANISM_INVALID; } ((uint32_t *)sks_pdata)[m] = sks_data32; } break; /* Attributes which data value do not need conversion (aside ulong) */ default: if (ck_attr_is_ulong(attr->type)) { sks_data32 = (uint32_t)ck_ulong; sks_pdata = &sks_data32; sks_size = sizeof(uint32_t); } else { sks_pdata = attr->pValue; sks_size = attr->ulValueLen; } break; } rv = serialize_32b(obj, sks_id); if (rv) goto bail; rv = serialize_32b(obj, sks_size); if (rv) goto bail; rv = serialize_buffer(obj, sks_pdata, sks_size); if (rv) goto bail; obj->item_count++; bail: if (sks_pdata_alloced) free(sks_pdata); return rv; } #ifdef SKS_WITH_GENERIC_ATTRIBS_IN_HEAD static CK_RV get_class(struct serializer *obj, struct ck_ref *ref) { CK_ULONG ck_value; uint32_t sks_value; if (ref->len != sizeof(ck_value)) return CKR_TEMPLATE_INCONSISTENT; memcpy(&ck_value, ref->ptr, sizeof(ck_value)); sks_value = ck2sks_object_class(ck_value); if (sks_value == SKS_UNDEFINED_ID) return CKR_TEMPLATE_INCONSISTENT; // TODO: errno if (obj->object == SKS_UNDEFINED_ID) obj->object = sks_value; if (obj->object != sks_value) { printf("Attribute %s redefined\n", cka2str(ref->id)); return CKR_TEMPLATE_INCONSISTENT; } return CKR_OK; } static CK_RV get_type(struct serializer *obj, struct ck_ref *ref, CK_ULONG class) { CK_ULONG ck_value; uint32_t sks_value; if (ref->len != sizeof(ck_value)) return CKR_TEMPLATE_INCONSISTENT; memcpy(&ck_value, ref->ptr, sizeof(ck_value)); sks_value = ck2sks_type_in_class(ck_value, class); if (sks_value == SKS_UNDEFINED_ID) return CKR_TEMPLATE_INCONSISTENT; // TODO: errno if (obj->type == SKS_UNDEFINED_ID) obj->type = sks_value; if (obj->type != sks_value) { printf("Attribute %s redefined\n", cktype2str(ck_value, class)); return CKR_TEMPLATE_INCONSISTENT; } return CKR_OK; } #ifdef /* SKS_WITH_BOOLPROP_ATTRIBS_IN_HEAD */ static CK_RV get_boolprop(struct serializer *obj, struct ck_ref *ref, uint32_t *sanity) { int shift; uint32_t mask; uint32_t value; uint32_t *boolprop_ptr; uint32_t *sanity_ptr; CK_BBOOL bbool; /* Get the boolean property shift position and value */ shift = ck_attr2boolprop_shift(ref->id); if (shift < 0) return CKR_NO_EVENT; if (shift >= SKS_MAX_BOOLPROP_SHIFT) return CKR_FUNCTION_FAILED; memcpy(&bbool, ref->ptr, sizeof(bbool)); mask = 1 << (shift % 32); if (bbool == CK_TRUE) value = mask; else value = 0; /* Locate the current config value for the boolean property */ boolprop_ptr = obj->boolprop + (shift / 32); sanity_ptr = sanity + (shift / 32); /* Error if already set to a different boolean value */ if ((*sanity_ptr & mask) && value != (*boolprop_ptr & mask)) { printf("Attribute %s redefined\n", cka2str(ref->id)); return CKR_TEMPLATE_INCONSISTENT; } *sanity_ptr |= mask; if (value) *boolprop_ptr |= mask; else *boolprop_ptr &= ~mask; return CKR_OK; } #endif /* SKS_WITH_BOOLPROP_ATTRIBS_IN_HEAD */ /* * Extract object generic attributes * - all objects must provide at least a class * - some classes expect a type * - some classes can define generic boolean attributes (boolprops) */ static CK_RV serialize_generic_attributes(struct serializer *obj, CK_ATTRIBUTE_PTR attributes, CK_ULONG count) { struct ck_ref *ref; size_t n; uint32_t sanity[SKS_MAX_BOOLPROP_ARRAY] = { 0 }; CK_RV rv = CKR_OK; CK_ULONG class; for (ref = (struct ck_ref *)attributes, n = 0; n < count; n++, ref++) { if (ck_attr_is_class(ref->id)) rv = get_class(obj, ref); if (rv) return rv; } rv = sks2ck_object_class(&class, obj->object); if (rv) return rv; for (ref = (struct ck_ref *)attributes, n = 0; n < count; n++, ref++) { if (ck_attr_is_type(ref->id)) { rv = get_type(obj, ref, class); if (rv) return rv; continue; } #ifdef SKS_WITH_BOOLPROP_ATTRIBS_IN_HEAD if (sks_object_has_boolprop(obj->object) && ck_attr2boolprop_shift(ref->id) >= 0) { rv = get_boolprop(obj, ref, sanity); if (rv == CKR_NO_EVENT) rv = CKR_OK; if (rv) return rv; continue; } #endif } return rv; } static int ck_attr_is_generic(CK_ULONG attribute_id) { return (ck_attr_is_class(attribute_id) || #ifdef SKS_WITH_BOOLPROP_ATTRIBS_IN_HEAD (ck_attr2boolprop_shift(attribute_id) >= 0) || #endif ck_attr_is_type(attribute_id)); } #endif /* SKS_WITH_GENERIC_ATTRIBS_IN_HEAD */ /* CK attribute reference arguments are list of attribute item */ CK_RV serialize_ck_attributes(struct serializer *obj, CK_ATTRIBUTE_PTR attributes, CK_ULONG count) { CK_ATTRIBUTE_PTR cur_attr = attributes; CK_ULONG n = count; CK_RV rv = CKR_OK; rv = init_serial_object(obj); if (rv) return rv; #ifdef SKS_WITH_GENERIC_ATTRIBS_IN_HEAD rv = serialize_generic_attributes(obj, attributes, count); if (rv) goto out; #endif for (; n; n--, cur_attr++) { CK_ATTRIBUTE attr; memcpy(&attr, cur_attr, sizeof(attr)); #ifdef SKS_WITH_GENERIC_ATTRIBS_IN_HEAD if (ck_attr_is_generic(attr.type)) continue; #endif rv = serialize_ck_attribute(obj, &attr); if (rv) goto out; } out: if (rv) release_serial_object(obj); else finalize_serial_object(obj); return rv; } static CK_RV deserialize_ck_attribute(struct sks_attribute_head *in, CK_ATTRIBUTE_PTR out) { CK_ULONG ck_ulong; uint32_t sks_data32 = 0; size_t n; CK_RV rv; rv = sks2ck_attribute_type(&(out->type), in->id); if (rv) return rv; if (out->ulValueLen < in->size) { out->ulValueLen = in->size; return CKR_OK; } if (!out->pValue) return CKR_OK; /* Specific ulong encoded as 32bit in SKS TA API */ if (ck_attr_is_ulong(out->type)) { if (out->ulValueLen != sizeof(CK_ULONG)) return CKR_ATTRIBUTE_TYPE_INVALID; memcpy(&sks_data32, in->data, sizeof(uint32_t)); } switch (out->type) { case CKA_CLASS: rv = sks2ck_object_class(&ck_ulong, sks_data32); if (rv) return rv; memcpy(out->pValue, &ck_ulong, sizeof(CK_ULONG)); break; case CKA_KEY_TYPE: rv = sks2ck_key_type(&ck_ulong, sks_data32); if (rv) return rv; memcpy(out->pValue, &ck_ulong, sizeof(CK_ULONG)); break; case CKA_CERTIFICATE_TYPE: rv = sks2ck_certificate_type(&ck_ulong, sks_data32); if (rv) return rv; memcpy(out->pValue, &ck_ulong, sizeof(CK_ULONG)); break; case CKA_KEY_GEN_MECHANISM: memcpy(&sks_data32, in->data, sizeof(uint32_t)); if (sks_data32 == SKS_UNAVAILABLE_INFORMATION) ck_ulong = CK_UNAVAILABLE_INFORMATION; else ck_ulong = sks_data32; memcpy(out->pValue, &ck_ulong, sizeof(CK_ULONG)); rv = CKR_OK; break; case CKA_WRAP_TEMPLATE: case CKA_UNWRAP_TEMPLATE: rv = deserialize_indirect_attribute(in, out->pValue); break; case CKA_ALLOWED_MECHANISMS: n = out->ulValueLen / sizeof(CK_ULONG); rv = sks2ck_mechanism_type_list(out->pValue, in->data, n); break; /* Attributes which data value do not need conversion (aside ulong) */ default: memcpy(out->pValue, in->data, in->size); rv = CKR_OK; break; } return rv; } CK_RV deserialize_ck_attributes(uint8_t *in, CK_ATTRIBUTE_PTR attributes, CK_ULONG count) { CK_ATTRIBUTE_PTR cur_attr = attributes; CK_ULONG n; CK_RV rv = CKR_OK; uint8_t *curr_head = in; size_t len; curr_head += sizeof(struct sks_object_head); #ifdef SKS_WITH_GENERIC_ATTRIBS_IN_HEAD #error Not supported. #endif for (n = count; n > 0; n--, cur_attr++, curr_head += len) { struct sks_attribute_head *cli_ref = (struct sks_attribute_head *)(void *)curr_head; len = sizeof(*cli_ref); /* * Can't trust size becuase it was set to reflect * required buffer. */ if (cur_attr->pValue) len += cli_ref->size; rv = deserialize_ck_attribute(cli_ref, cur_attr); if (rv) goto out; } out: return rv; } /* * Serialization of CK mechanism parameters * * Most mechanism have no parameters. * Some mechanism have a single 32bit parameter. * Some mechanism have a specific parameter structure which may contain * indirected data (data referred by a buffer pointer). * * Below are each structure specific mechanisms parameters. * * Be careful that CK_ULONG based types translate to 32bit sks ulong fields. */ /* * typedef struct CK_AES_CTR_PARAMS { * CK_ULONG ulCounterBits; * CK_BYTE cb[16]; * } CK_AES_CTR_PARAMS; */ static CK_RV serialize_mecha_aes_ctr(struct serializer *obj, CK_MECHANISM_PTR mecha) { CK_AES_CTR_PARAMS_PTR param = mecha->pParameter; CK_RV rv; uint32_t size; rv = serialize_32b(obj, obj->type); if (rv) return rv; size = sizeof(uint32_t) + sizeof(param->cb); rv = serialize_32b(obj, size); if (rv) return rv; rv = serialize_ck_ulong(obj, param->ulCounterBits); if (rv) return rv; rv = serialize_buffer(obj, param->cb, sizeof(param->cb)); if (rv) return rv; return rv; } /* * typedef struct CK_GCM_PARAMS { * CK_BYTE_PTR pIv; * CK_ULONG ulIvLen; * CK_ULONG ulIvBits; -> unused (deprecated?) * CK_BYTE_PTR pAAD; * CK_ULONG ulAADLen; * CK_ULONG ulTagBits; * } CK_GCM_PARAMS; * * Serialized: * [uint32_t mechanism_id] * [uint32_t parameters_byte_size = 3 * 8 + IV size + AAD size] * [uint32_t iv_byte_size] * [uint8_t iv[iv_byte_size]] * [uint32_t aad_byte_size] * [uint8_t aad[aad_byte_size]] * [uint32_t tag_bit_size] */ static CK_RV serialize_mecha_aes_gcm(struct serializer *obj, CK_MECHANISM_PTR mecha) { CK_GCM_PARAMS_PTR param = mecha->pParameter; CK_RV rv; CK_ULONG aad_len; /* AAD is not manadatory */ if (param->pAAD) aad_len = param->ulAADLen; else aad_len = 0; if (!param->pIv) return CKR_MECHANISM_PARAM_INVALID; rv = serialize_32b(obj, obj->type); if (rv) return rv; rv = serialize_32b(obj, 3 * sizeof(uint32_t) + param->ulIvLen + aad_len); if (rv) return rv; rv = serialize_ck_ulong(obj, param->ulIvLen); if (rv) return rv; rv = serialize_buffer(obj, param->pIv, param->ulIvLen); if (rv) return rv; rv = serialize_ck_ulong(obj, aad_len); if (rv) return rv; rv = serialize_buffer(obj, param->pAAD, aad_len); if (rv) return rv; return serialize_ck_ulong(obj, param->ulTagBits); } /* * typedef struct CK_CCM_PARAMS { * CK_ULONG ulDataLen; * CK_BYTE_PTR pNonce; * CK_ULONG ulNonceLen; * CK_BYTE_PTR pAAD; * CK_ULONG ulAADLen; * CK_ULONG ulMACLen; *} CK_CCM_PARAMS; */ static CK_RV serialize_mecha_aes_ccm(struct serializer *obj, CK_MECHANISM_PTR mecha) { CK_CCM_PARAMS_PTR param = mecha->pParameter; CK_RV rv; rv = serialize_32b(obj, obj->type); if (rv) return rv; rv = serialize_32b(obj, 4 * sizeof(uint32_t) + param->ulNonceLen + param->ulAADLen); if (rv) return rv; rv = serialize_ck_ulong(obj, param->ulDataLen); if (rv) return rv; rv = serialize_ck_ulong(obj, param->ulNonceLen); if (rv) return rv; rv = serialize_buffer(obj, param->pNonce, param->ulNonceLen); if (rv) return rv; rv = serialize_ck_ulong(obj, param->ulAADLen); if (rv) return rv; rv = serialize_buffer(obj, param->pAAD, param->ulAADLen); if (rv) return rv; return serialize_ck_ulong(obj, param->ulMACLen); } static CK_RV serialize_mecha_aes_iv(struct serializer *obj, CK_MECHANISM_PTR mecha) { uint32_t iv_size = mecha->ulParameterLen; CK_RV rv; rv = serialize_32b(obj, obj->type); if (rv) return rv; rv = serialize_32b(obj, iv_size); if (rv) return rv; return serialize_buffer(obj, mecha->pParameter, mecha->ulParameterLen); } static CK_RV serialize_mecha_ulong_param(struct serializer *obj, CK_MECHANISM_PTR mecha) { CK_RV rv; uint32_t sks_data; CK_ULONG ck_data; memcpy(&ck_data, mecha->pParameter, mecha->ulParameterLen); sks_data = ck_data; rv = serialize_32b(obj, obj->type); if (rv) return rv; rv = serialize_32b(obj, sizeof(uint32_t)); if (rv) return rv; return serialize_32b(obj, sks_data); } static CK_RV serialize_mecha_ecdh1_derive_param(struct serializer *obj, CK_MECHANISM_PTR mecha) { CK_ECDH1_DERIVE_PARAMS *params = mecha->pParameter; CK_RV rv; size_t params_size = 3 * sizeof(uint32_t) + params->ulSharedDataLen + params->ulPublicDataLen; rv = serialize_32b(obj, obj->type); if (rv) return rv; rv = serialize_32b(obj, params_size); if (rv) return rv; rv = serialize_32b(obj, ck2sks_ec_kdf_type(params->kdf)); if (rv) return rv; rv = serialize_32b(obj, params->ulSharedDataLen); if (rv) return rv; rv = serialize_buffer(obj, params->pSharedData, params->ulSharedDataLen); if (rv) return rv; rv = serialize_32b(obj, params->ulPublicDataLen); if (rv) return rv; return serialize_buffer(obj, params->pPublicData, params->ulPublicDataLen); } static CK_RV serialize_mecha_ecdh_aes_key_wrap_param(struct serializer *obj, CK_MECHANISM_PTR mecha) { CK_ECDH_AES_KEY_WRAP_PARAMS *params = mecha->pParameter; CK_RV rv; size_t params_size = 3 * sizeof(uint32_t) + params->ulSharedDataLen; rv = serialize_32b(obj, obj->type); if (rv) return rv; rv = serialize_32b(obj, params_size); if (rv) return rv; rv = serialize_32b(obj, params->ulAESKeyBits); if (rv) return rv; rv = serialize_32b(obj, ck2sks_ec_kdf_type(params->kdf)); if (rv) return rv; rv = serialize_32b(obj, params->ulSharedDataLen); if (rv) return rv; return serialize_buffer(obj, params->pSharedData, params->ulSharedDataLen); } static CK_RV serialize_mecha_rsa_oaep_param(struct serializer *obj, CK_MECHANISM_PTR mecha) { CK_RSA_PKCS_OAEP_PARAMS *params = mecha->pParameter; CK_RV rv; size_t params_size = 4 * sizeof(uint32_t) + params->ulSourceDataLen; rv = serialize_32b(obj, obj->type); if (rv) return rv; rv = serialize_32b(obj, params_size); if (rv) return rv; rv = serialize_32b(obj, ck2sks_mechanism_type(params->hashAlg)); if (rv) return rv; rv = serialize_32b(obj, ck2sks_rsa_pkcs_mgf_type(params->mgf)); if (rv) return rv; rv = serialize_32b(obj, ck2sks_rsa_pkcs_oaep_source_type(params->source)); if (rv) return rv; rv = serialize_32b(obj, params->ulSourceDataLen); if (rv) return rv; return serialize_buffer(obj, params->pSourceData, params->ulSourceDataLen); } static CK_RV serialize_mecha_rsa_pss_param(struct serializer *obj, CK_MECHANISM_PTR mecha) { CK_RSA_PKCS_PSS_PARAMS *params = mecha->pParameter; CK_RV rv; size_t params_size = 3 * sizeof(uint32_t); rv = serialize_32b(obj, obj->type); if (rv) return rv; rv = serialize_32b(obj, params_size); if (rv) return rv; rv = serialize_32b(obj, ck2sks_mechanism_type(params->hashAlg)); if (rv) return rv; rv = serialize_32b(obj, ck2sks_rsa_pkcs_mgf_type(params->mgf)); if (rv) return rv; return serialize_32b(obj, params->sLen); } static CK_RV serialize_mecha_rsa_aes_key_wrap_param(struct serializer *obj, CK_MECHANISM_PTR mecha) { CK_RSA_AES_KEY_WRAP_PARAMS *params = mecha->pParameter; CK_RSA_PKCS_OAEP_PARAMS *oaep_p = params->pOAEPParams; CK_RV rv; size_t params_size = 5 * sizeof(uint32_t) + params->pOAEPParams->ulSourceDataLen; rv = serialize_32b(obj, obj->type); if (rv) return rv; rv = serialize_32b(obj, params_size); if (rv) return rv; rv = serialize_32b(obj, params->ulAESKeyBits); if (rv) return rv; rv = serialize_32b(obj, ck2sks_mechanism_type(oaep_p->hashAlg)); if (rv) return rv; rv = serialize_32b(obj, ck2sks_rsa_pkcs_mgf_type(oaep_p->mgf)); if (rv) return rv; rv = serialize_32b(obj, ck2sks_rsa_pkcs_oaep_source_type(oaep_p->source)); if (rv) return rv; rv = serialize_32b(obj, oaep_p->ulSourceDataLen); if (rv) return rv; return serialize_buffer(obj, oaep_p->pSourceData, oaep_p->ulSourceDataLen); } /** * serialize_ck_mecha_params - serialize a mechanism type & params * * @obj - serializer used to track the serialization * @mechanism - pointer of the in structure aligned CK_MECHANISM. * * Serialized content: * [sks-mechanism-type][sks-mechanism-param-blob] * * [sks-mechanism-param-blob] depends on mechanism type ID, see * serialize_mecha_XXX(). */ CK_RV serialize_ck_mecha_params(struct serializer *obj, CK_MECHANISM_PTR mechanism) { CK_MECHANISM mecha; CK_RV rv; memset(obj, 0, sizeof(*obj)); obj->object = SKS_CKO_MECHANISM; memcpy(&mecha, mechanism, sizeof(mecha)); obj->type = ck2sks_mechanism_type(mecha.mechanism); if (obj->type == SKS_UNDEFINED_ID) return CKR_MECHANISM_INVALID; switch (mecha.mechanism) { case CKM_GENERIC_SECRET_KEY_GEN: case CKM_AES_KEY_GEN: case CKM_AES_ECB: case CKM_AES_CMAC: case CKM_MD5_HMAC: case CKM_SHA_1_HMAC: case CKM_SHA224_HMAC: case CKM_SHA256_HMAC: case CKM_SHA384_HMAC: case CKM_SHA512_HMAC: case CKM_AES_XCBC_MAC: case CKM_AES_XCBC_MAC_96: case CKM_EC_KEY_PAIR_GEN: case CKM_RSA_PKCS_KEY_PAIR_GEN: case CKM_ECDSA: case CKM_ECDSA_SHA1: case CKM_ECDSA_SHA224: case CKM_ECDSA_SHA256: case CKM_ECDSA_SHA384: case CKM_ECDSA_SHA512: case CKM_RSA_PKCS: case CKM_RSA_9796: case CKM_RSA_X_509: case CKM_SHA1_RSA_PKCS: case CKM_SHA256_RSA_PKCS: case CKM_SHA384_RSA_PKCS: case CKM_SHA512_RSA_PKCS: case CKM_SHA224_RSA_PKCS: case CKM_DES_KEY_GEN: /* No parameter expected, size shall be 0 */ if (mechanism->ulParameterLen) return CKR_MECHANISM_PARAM_INVALID; rv = serialize_32b(obj, obj->type); if (rv) return rv; return serialize_32b(obj, 0); case CKM_AES_CMAC_GENERAL: return serialize_mecha_ulong_param(obj, &mecha); case CKM_AES_CBC: case CKM_AES_CBC_PAD: case CKM_AES_CTS: return serialize_mecha_aes_iv(obj, &mecha); case CKM_AES_CTR: return serialize_mecha_aes_ctr(obj, &mecha); case CKM_AES_CCM: return serialize_mecha_aes_ccm(obj, &mecha); case CKM_AES_GCM: return serialize_mecha_aes_gcm(obj, &mecha); case CKM_ECDH1_DERIVE: case CKM_ECDH1_COFACTOR_DERIVE: return serialize_mecha_ecdh1_derive_param(obj, &mecha); case CKM_ECDH_AES_KEY_WRAP: return serialize_mecha_ecdh_aes_key_wrap_param(obj, &mecha); case CKM_RSA_PKCS_OAEP: return serialize_mecha_rsa_oaep_param(obj, &mecha); case CKM_RSA_PKCS_PSS: case CKM_SHA1_RSA_PKCS_PSS: case CKM_SHA256_RSA_PKCS_PSS: case CKM_SHA384_RSA_PKCS_PSS: case CKM_SHA512_RSA_PKCS_PSS: case CKM_SHA224_RSA_PKCS_PSS: return serialize_mecha_rsa_pss_param(obj, &mecha); case CKM_RSA_AES_KEY_WRAP: return serialize_mecha_rsa_aes_key_wrap_param(obj, &mecha); default: return CKR_MECHANISM_INVALID; } } /* * Debug: dump CK attribute array to output trace */ static CK_RV trace_attributes(char *prefix, void *src, void *end) { size_t next = 0; char *prefix2; size_t prefix_len = strlen(prefix); char *cur = src; /* append 4 spaces to the prefix */ prefix2 = malloc(prefix_len + 1 + 4) ; memcpy(prefix2, prefix, prefix_len + 1); memset(prefix2 + prefix_len, ' ', 4); *(prefix2 + prefix_len + 1 + 4) = '\0'; for (; cur < (char *)end; cur += next) { struct sks_attribute_head ref; memcpy(&ref, cur, sizeof(ref)); next = sizeof(ref) + ref.size; LOG_DEBUG("%s attr 0x%" PRIx32 " (%" PRIu32" byte) : %02x %02x %02x %02x ...\n", prefix, ref.id, ref.size, *((char *)cur + sizeof(ref) + 0), *((char *)cur + sizeof(ref) + 1), *((char *)cur + sizeof(ref) + 2), *((char *)cur + sizeof(ref) + 3)); switch (ref.id) { case SKS_CKA_WRAP_TEMPLATE: case SKS_CKA_UNWRAP_TEMPLATE: serial_trace_attributes_from_head(prefix2, cur + sizeof(ref)); break; default: break; } } /* sanity */ if (cur != (char *)end) { LOG_ERROR("unexpected none alignement\n"); } free(prefix2); return CKR_OK; } CK_RV serial_trace_attributes_from_head(char *prefix, void *ref) { struct sks_object_head head; char *pre; CK_RV rv; memcpy(&head, ref, sizeof(head)); pre = calloc(1, prefix ? strlen(prefix) + 2 : 2) ; if (!pre) return CKR_HOST_MEMORY; if (prefix) memcpy(pre, prefix, strlen(prefix)); LOG_INFO("%s,--- (serial object) Attributes list --------\n", pre); LOG_INFO("%s| %" PRIu32 " item(s) - %" PRIu32 " bytes\n", pre, head.attrs_count, head.attrs_size); pre[prefix ? strlen(prefix) + 1 : 0] = '|'; rv = trace_attributes(pre, (char *)ref + sizeof(head), (char *)ref + sizeof(head) + head.attrs_size); if (rv) goto bail; LOG_INFO("%s`-----------------------\n", prefix ? prefix : ""); bail: free(pre); return rv; } CK_RV serial_trace_attributes(char *prefix, struct serializer *obj) { return serial_trace_attributes_from_head(prefix, obj->buffer); }
22.323353
82
0.710147
[ "object" ]
7fe9252824c73b94f0ec9c03432dda4f3e89efdc
81,929
h
C
llvm/include/llvm/CodeGen/GlobalISel/MachineIRBuilder.h
ornata/llvm-project
494913b8b4e4bce0b3525e5569d8e486e82b9a52
[ "Apache-2.0" ]
null
null
null
llvm/include/llvm/CodeGen/GlobalISel/MachineIRBuilder.h
ornata/llvm-project
494913b8b4e4bce0b3525e5569d8e486e82b9a52
[ "Apache-2.0" ]
null
null
null
llvm/include/llvm/CodeGen/GlobalISel/MachineIRBuilder.h
ornata/llvm-project
494913b8b4e4bce0b3525e5569d8e486e82b9a52
[ "Apache-2.0" ]
null
null
null
//===-- llvm/CodeGen/GlobalISel/MachineIRBuilder.h - MIBuilder --*- 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 // //===----------------------------------------------------------------------===// /// \file /// This file declares the MachineIRBuilder class. /// This is a helper class to build MachineInstr. //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_GLOBALISEL_MACHINEIRBUILDER_H #define LLVM_CODEGEN_GLOBALISEL_MACHINEIRBUILDER_H #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetOpcodes.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/Module.h" namespace llvm { // Forward declarations. class APInt; class BlockAddress; class Constant; class ConstantFP; class ConstantInt; class DataLayout; class GISelCSEInfo; class GlobalValue; class TargetRegisterClass; class MachineFunction; class MachineInstr; class TargetInstrInfo; class GISelChangeObserver; /// Class which stores all the state required in a MachineIRBuilder. /// Since MachineIRBuilders will only store state in this object, it allows /// to transfer BuilderState between different kinds of MachineIRBuilders. struct MachineIRBuilderState { /// MachineFunction under construction. MachineFunction *MF = nullptr; /// Information used to access the description of the opcodes. const TargetInstrInfo *TII = nullptr; /// Information used to verify types are consistent and to create virtual registers. MachineRegisterInfo *MRI = nullptr; /// Debug location to be set to any instruction we create. DebugLoc DL; /// \name Fields describing the insertion point. /// @{ MachineBasicBlock *MBB = nullptr; MachineBasicBlock::iterator II; /// @} GISelChangeObserver *Observer = nullptr; GISelCSEInfo *CSEInfo = nullptr; }; class DstOp { union { LLT LLTTy; Register Reg; const TargetRegisterClass *RC; }; public: enum class DstType { Ty_LLT, Ty_Reg, Ty_RC }; DstOp(unsigned R) : Reg(R), Ty(DstType::Ty_Reg) {} DstOp(Register R) : Reg(R), Ty(DstType::Ty_Reg) {} DstOp(const MachineOperand &Op) : Reg(Op.getReg()), Ty(DstType::Ty_Reg) {} DstOp(const LLT T) : LLTTy(T), Ty(DstType::Ty_LLT) {} DstOp(const TargetRegisterClass *TRC) : RC(TRC), Ty(DstType::Ty_RC) {} void addDefToMIB(MachineRegisterInfo &MRI, MachineInstrBuilder &MIB) const { switch (Ty) { case DstType::Ty_Reg: MIB.addDef(Reg); break; case DstType::Ty_LLT: MIB.addDef(MRI.createGenericVirtualRegister(LLTTy)); break; case DstType::Ty_RC: MIB.addDef(MRI.createVirtualRegister(RC)); break; } } LLT getLLTTy(const MachineRegisterInfo &MRI) const { switch (Ty) { case DstType::Ty_RC: return LLT{}; case DstType::Ty_LLT: return LLTTy; case DstType::Ty_Reg: return MRI.getType(Reg); } llvm_unreachable("Unrecognised DstOp::DstType enum"); } Register getReg() const { assert(Ty == DstType::Ty_Reg && "Not a register"); return Reg; } const TargetRegisterClass *getRegClass() const { switch (Ty) { case DstType::Ty_RC: return RC; default: llvm_unreachable("Not a RC Operand"); } } DstType getDstOpKind() const { return Ty; } private: DstType Ty; }; class SrcOp { union { MachineInstrBuilder SrcMIB; Register Reg; CmpInst::Predicate Pred; int64_t Imm; }; public: enum class SrcType { Ty_Reg, Ty_MIB, Ty_Predicate, Ty_Imm }; SrcOp(Register R) : Reg(R), Ty(SrcType::Ty_Reg) {} SrcOp(const MachineOperand &Op) : Reg(Op.getReg()), Ty(SrcType::Ty_Reg) {} SrcOp(const MachineInstrBuilder &MIB) : SrcMIB(MIB), Ty(SrcType::Ty_MIB) {} SrcOp(const CmpInst::Predicate P) : Pred(P), Ty(SrcType::Ty_Predicate) {} /// Use of registers held in unsigned integer variables (or more rarely signed /// integers) is no longer permitted to avoid ambiguity with upcoming support /// for immediates. SrcOp(unsigned) = delete; SrcOp(int) = delete; SrcOp(uint64_t V) : Imm(V), Ty(SrcType::Ty_Imm) {} SrcOp(int64_t V) : Imm(V), Ty(SrcType::Ty_Imm) {} void addSrcToMIB(MachineInstrBuilder &MIB) const { switch (Ty) { case SrcType::Ty_Predicate: MIB.addPredicate(Pred); break; case SrcType::Ty_Reg: MIB.addUse(Reg); break; case SrcType::Ty_MIB: MIB.addUse(SrcMIB->getOperand(0).getReg()); break; case SrcType::Ty_Imm: MIB.addImm(Imm); break; } } LLT getLLTTy(const MachineRegisterInfo &MRI) const { switch (Ty) { case SrcType::Ty_Predicate: case SrcType::Ty_Imm: llvm_unreachable("Not a register operand"); case SrcType::Ty_Reg: return MRI.getType(Reg); case SrcType::Ty_MIB: return MRI.getType(SrcMIB->getOperand(0).getReg()); } llvm_unreachable("Unrecognised SrcOp::SrcType enum"); } Register getReg() const { switch (Ty) { case SrcType::Ty_Predicate: case SrcType::Ty_Imm: llvm_unreachable("Not a register operand"); case SrcType::Ty_Reg: return Reg; case SrcType::Ty_MIB: return SrcMIB->getOperand(0).getReg(); } llvm_unreachable("Unrecognised SrcOp::SrcType enum"); } CmpInst::Predicate getPredicate() const { switch (Ty) { case SrcType::Ty_Predicate: return Pred; default: llvm_unreachable("Not a register operand"); } } int64_t getImm() const { switch (Ty) { case SrcType::Ty_Imm: return Imm; default: llvm_unreachable("Not an immediate"); } } SrcType getSrcOpKind() const { return Ty; } private: SrcType Ty; }; /// Helper class to build MachineInstr. /// It keeps internally the insertion point and debug location for all /// the new instructions we want to create. /// This information can be modify via the related setters. class MachineIRBuilder { MachineIRBuilderState State; protected: void validateTruncExt(const LLT Dst, const LLT Src, bool IsExtend); void validateUnaryOp(const LLT Res, const LLT Op0); void validateBinaryOp(const LLT Res, const LLT Op0, const LLT Op1); void validateShiftOp(const LLT Res, const LLT Op0, const LLT Op1); void validateSelectOp(const LLT ResTy, const LLT TstTy, const LLT Op0Ty, const LLT Op1Ty); void recordInsertion(MachineInstr *InsertedInstr) const { if (State.Observer) State.Observer->createdInstr(*InsertedInstr); } public: /// Some constructors for easy use. MachineIRBuilder() = default; MachineIRBuilder(MachineFunction &MF) { setMF(MF); } MachineIRBuilder(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt) { setMF(*MBB.getParent()); setInsertPt(MBB, InsPt); } MachineIRBuilder(MachineInstr &MI) : MachineIRBuilder(*MI.getParent(), MI.getIterator()) { setInstr(MI); setDebugLoc(MI.getDebugLoc()); } MachineIRBuilder(MachineInstr &MI, GISelChangeObserver &Observer) : MachineIRBuilder(MI) { setChangeObserver(Observer); } virtual ~MachineIRBuilder() = default; MachineIRBuilder(const MachineIRBuilderState &BState) : State(BState) {} const TargetInstrInfo &getTII() { assert(State.TII && "TargetInstrInfo is not set"); return *State.TII; } /// Getter for the function we currently build. MachineFunction &getMF() { assert(State.MF && "MachineFunction is not set"); return *State.MF; } const MachineFunction &getMF() const { assert(State.MF && "MachineFunction is not set"); return *State.MF; } const DataLayout &getDataLayout() const { return getMF().getFunction().getParent()->getDataLayout(); } /// Getter for DebugLoc const DebugLoc &getDL() { return State.DL; } /// Getter for MRI MachineRegisterInfo *getMRI() { return State.MRI; } const MachineRegisterInfo *getMRI() const { return State.MRI; } /// Getter for the State MachineIRBuilderState &getState() { return State; } /// Getter for the basic block we currently build. const MachineBasicBlock &getMBB() const { assert(State.MBB && "MachineBasicBlock is not set"); return *State.MBB; } MachineBasicBlock &getMBB() { return const_cast<MachineBasicBlock &>( const_cast<const MachineIRBuilder *>(this)->getMBB()); } GISelCSEInfo *getCSEInfo() { return State.CSEInfo; } const GISelCSEInfo *getCSEInfo() const { return State.CSEInfo; } /// Current insertion point for new instructions. MachineBasicBlock::iterator getInsertPt() { return State.II; } /// Set the insertion point before the specified position. /// \pre MBB must be in getMF(). /// \pre II must be a valid iterator in MBB. void setInsertPt(MachineBasicBlock &MBB, MachineBasicBlock::iterator II) { assert(MBB.getParent() == &getMF() && "Basic block is in a different function"); State.MBB = &MBB; State.II = II; } /// @} void setCSEInfo(GISelCSEInfo *Info) { State.CSEInfo = Info; } /// \name Setters for the insertion point. /// @{ /// Set the MachineFunction where to build instructions. void setMF(MachineFunction &MF); /// Set the insertion point to the end of \p MBB. /// \pre \p MBB must be contained by getMF(). void setMBB(MachineBasicBlock &MBB) { State.MBB = &MBB; State.II = MBB.end(); assert(&getMF() == MBB.getParent() && "Basic block is in a different function"); } /// Set the insertion point to before MI. /// \pre MI must be in getMF(). void setInstr(MachineInstr &MI) { assert(MI.getParent() && "Instruction is not part of a basic block"); setMBB(*MI.getParent()); State.II = MI.getIterator(); } /// @} /// Set the insertion point to before MI, and set the debug loc to MI's loc. /// \pre MI must be in getMF(). void setInstrAndDebugLoc(MachineInstr &MI) { setInstr(MI); setDebugLoc(MI.getDebugLoc()); } void setChangeObserver(GISelChangeObserver &Observer) { State.Observer = &Observer; } void stopObservingChanges() { State.Observer = nullptr; } /// @} /// Set the debug location to \p DL for all the next build instructions. void setDebugLoc(const DebugLoc &DL) { this->State.DL = DL; } /// Get the current instruction's debug location. const DebugLoc &getDebugLoc() { return State.DL; } /// Build and insert <empty> = \p Opcode <empty>. /// The insertion point is the one set by the last call of either /// setBasicBlock or setMI. /// /// \pre setBasicBlock or setMI must have been called. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildInstr(unsigned Opcode) { return insertInstr(buildInstrNoInsert(Opcode)); } /// Build but don't insert <empty> = \p Opcode <empty>. /// /// \pre setMF, setBasicBlock or setMI must have been called. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildInstrNoInsert(unsigned Opcode); /// Insert an existing instruction at the insertion point. MachineInstrBuilder insertInstr(MachineInstrBuilder MIB); /// Build and insert a DBG_VALUE instruction expressing the fact that the /// associated \p Variable lives in \p Reg (suitably modified by \p Expr). MachineInstrBuilder buildDirectDbgValue(Register Reg, const MDNode *Variable, const MDNode *Expr); /// Build and insert a DBG_VALUE instruction expressing the fact that the /// associated \p Variable lives in memory at \p Reg (suitably modified by \p /// Expr). MachineInstrBuilder buildIndirectDbgValue(Register Reg, const MDNode *Variable, const MDNode *Expr); /// Build and insert a DBG_VALUE instruction expressing the fact that the /// associated \p Variable lives in the stack slot specified by \p FI /// (suitably modified by \p Expr). MachineInstrBuilder buildFIDbgValue(int FI, const MDNode *Variable, const MDNode *Expr); /// Build and insert a DBG_VALUE instructions specifying that \p Variable is /// given by \p C (suitably modified by \p Expr). MachineInstrBuilder buildConstDbgValue(const Constant &C, const MDNode *Variable, const MDNode *Expr); /// Build and insert a DBG_LABEL instructions specifying that \p Label is /// given. Convert "llvm.dbg.label Label" to "DBG_LABEL Label". MachineInstrBuilder buildDbgLabel(const MDNode *Label); /// Build and insert \p Res = G_DYN_STACKALLOC \p Size, \p Align /// /// G_DYN_STACKALLOC does a dynamic stack allocation and writes the address of /// the allocated memory into \p Res. /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with pointer type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildDynStackAlloc(const DstOp &Res, const SrcOp &Size, Align Alignment); /// Build and insert \p Res = G_FRAME_INDEX \p Idx /// /// G_FRAME_INDEX materializes the address of an alloca value or other /// stack-based object. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with pointer type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildFrameIndex(const DstOp &Res, int Idx); /// Build and insert \p Res = G_GLOBAL_VALUE \p GV /// /// G_GLOBAL_VALUE materializes the address of the specified global /// into \p Res. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with pointer type /// in the same address space as \p GV. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildGlobalValue(const DstOp &Res, const GlobalValue *GV); /// Build and insert \p Res = G_PTR_ADD \p Op0, \p Op1 /// /// G_PTR_ADD adds \p Op1 addressible units to the pointer specified by \p Op0, /// storing the resulting pointer in \p Res. Addressible units are typically /// bytes but this can vary between targets. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res and \p Op0 must be generic virtual registers with pointer /// type. /// \pre \p Op1 must be a generic virtual register with scalar type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildPtrAdd(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1); /// Materialize and insert \p Res = G_PTR_ADD \p Op0, (G_CONSTANT \p Value) /// /// G_PTR_ADD adds \p Value bytes to the pointer specified by \p Op0, /// storing the resulting pointer in \p Res. If \p Value is zero then no /// G_PTR_ADD or G_CONSTANT will be created and \pre Op0 will be assigned to /// \p Res. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Op0 must be a generic virtual register with pointer type. /// \pre \p ValueTy must be a scalar type. /// \pre \p Res must be 0. This is to detect confusion between /// materializePtrAdd() and buildPtrAdd(). /// \post \p Res will either be a new generic virtual register of the same /// type as \p Op0 or \p Op0 itself. /// /// \return a MachineInstrBuilder for the newly created instruction. Optional<MachineInstrBuilder> materializePtrAdd(Register &Res, Register Op0, const LLT ValueTy, uint64_t Value); /// Build and insert \p Res = G_PTRMASK \p Op0, \p Op1 MachineInstrBuilder buildPtrMask(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1) { return buildInstr(TargetOpcode::G_PTRMASK, {Res}, {Op0, Op1}); } /// Build and insert \p Res = G_PTRMASK \p Op0, \p G_CONSTANT (1 << NumBits) - 1 /// /// This clears the low bits of a pointer operand without destroying its /// pointer properties. This has the effect of rounding the address *down* to /// a specified alignment in bits. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res and \p Op0 must be generic virtual registers with pointer /// type. /// \pre \p NumBits must be an integer representing the number of low bits to /// be cleared in \p Op0. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildMaskLowPtrBits(const DstOp &Res, const SrcOp &Op0, uint32_t NumBits); /// Build and insert /// a, b, ..., x = G_UNMERGE_VALUES \p Op0 /// \p Res = G_BUILD_VECTOR a, b, ..., x, undef, ..., undef /// /// Pad \p Op0 with undef elements to match number of elements in \p Res. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res and \p Op0 must be generic virtual registers with vector type, /// same vector element type and Op0 must have fewer elements then Res. /// /// \return a MachineInstrBuilder for the newly created build vector instr. MachineInstrBuilder buildPadVectorWithUndefElements(const DstOp &Res, const SrcOp &Op0); /// Build and insert /// a, b, ..., x, y, z = G_UNMERGE_VALUES \p Op0 /// \p Res = G_BUILD_VECTOR a, b, ..., x /// /// Delete trailing elements in \p Op0 to match number of elements in \p Res. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res and \p Op0 must be generic virtual registers with vector type, /// same vector element type and Op0 must have more elements then Res. /// /// \return a MachineInstrBuilder for the newly created build vector instr. MachineInstrBuilder buildDeleteTrailingVectorElements(const DstOp &Res, const SrcOp &Op0); /// Build and insert \p Res, \p CarryOut = G_UADDO \p Op0, \p Op1 /// /// G_UADDO sets \p Res to \p Op0 + \p Op1 (truncated to the bit width) and /// sets \p CarryOut to 1 if the result overflowed in unsigned arithmetic. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res, \p Op0 and \p Op1 must be generic virtual registers with the /// same scalar type. ////\pre \p CarryOut must be generic virtual register with scalar type ///(typically s1) /// /// \return The newly created instruction. MachineInstrBuilder buildUAddo(const DstOp &Res, const DstOp &CarryOut, const SrcOp &Op0, const SrcOp &Op1) { return buildInstr(TargetOpcode::G_UADDO, {Res, CarryOut}, {Op0, Op1}); } /// Build and insert \p Res, \p CarryOut = G_USUBO \p Op0, \p Op1 MachineInstrBuilder buildUSubo(const DstOp &Res, const DstOp &CarryOut, const SrcOp &Op0, const SrcOp &Op1) { return buildInstr(TargetOpcode::G_USUBO, {Res, CarryOut}, {Op0, Op1}); } /// Build and insert \p Res, \p CarryOut = G_SADDO \p Op0, \p Op1 MachineInstrBuilder buildSAddo(const DstOp &Res, const DstOp &CarryOut, const SrcOp &Op0, const SrcOp &Op1) { return buildInstr(TargetOpcode::G_SADDO, {Res, CarryOut}, {Op0, Op1}); } /// Build and insert \p Res, \p CarryOut = G_SUBO \p Op0, \p Op1 MachineInstrBuilder buildSSubo(const DstOp &Res, const DstOp &CarryOut, const SrcOp &Op0, const SrcOp &Op1) { return buildInstr(TargetOpcode::G_SSUBO, {Res, CarryOut}, {Op0, Op1}); } /// Build and insert \p Res, \p CarryOut = G_UADDE \p Op0, /// \p Op1, \p CarryIn /// /// G_UADDE sets \p Res to \p Op0 + \p Op1 + \p CarryIn (truncated to the bit /// width) and sets \p CarryOut to 1 if the result overflowed in unsigned /// arithmetic. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res, \p Op0 and \p Op1 must be generic virtual registers /// with the same scalar type. /// \pre \p CarryOut and \p CarryIn must be generic virtual /// registers with the same scalar type (typically s1) /// /// \return The newly created instruction. MachineInstrBuilder buildUAdde(const DstOp &Res, const DstOp &CarryOut, const SrcOp &Op0, const SrcOp &Op1, const SrcOp &CarryIn) { return buildInstr(TargetOpcode::G_UADDE, {Res, CarryOut}, {Op0, Op1, CarryIn}); } /// Build and insert \p Res, \p CarryOut = G_USUBE \p Op0, \p Op1, \p CarryInp MachineInstrBuilder buildUSube(const DstOp &Res, const DstOp &CarryOut, const SrcOp &Op0, const SrcOp &Op1, const SrcOp &CarryIn) { return buildInstr(TargetOpcode::G_USUBE, {Res, CarryOut}, {Op0, Op1, CarryIn}); } /// Build and insert \p Res, \p CarryOut = G_SADDE \p Op0, \p Op1, \p CarryInp MachineInstrBuilder buildSAdde(const DstOp &Res, const DstOp &CarryOut, const SrcOp &Op0, const SrcOp &Op1, const SrcOp &CarryIn) { return buildInstr(TargetOpcode::G_SADDE, {Res, CarryOut}, {Op0, Op1, CarryIn}); } /// Build and insert \p Res, \p CarryOut = G_SSUBE \p Op0, \p Op1, \p CarryInp MachineInstrBuilder buildSSube(const DstOp &Res, const DstOp &CarryOut, const SrcOp &Op0, const SrcOp &Op1, const SrcOp &CarryIn) { return buildInstr(TargetOpcode::G_SSUBE, {Res, CarryOut}, {Op0, Op1, CarryIn}); } /// Build and insert \p Res = G_ANYEXT \p Op0 /// /// G_ANYEXT produces a register of the specified width, with bits 0 to /// sizeof(\p Ty) * 8 set to \p Op. The remaining bits are unspecified /// (i.e. this is neither zero nor sign-extension). For a vector register, /// each element is extended individually. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or vector type. /// \pre \p Op must be a generic virtual register with scalar or vector type. /// \pre \p Op must be smaller than \p Res /// /// \return The newly created instruction. MachineInstrBuilder buildAnyExt(const DstOp &Res, const SrcOp &Op); /// Build and insert \p Res = G_SEXT \p Op /// /// G_SEXT produces a register of the specified width, with bits 0 to /// sizeof(\p Ty) * 8 set to \p Op. The remaining bits are duplicated from the /// high bit of \p Op (i.e. 2s-complement sign extended). /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or vector type. /// \pre \p Op must be a generic virtual register with scalar or vector type. /// \pre \p Op must be smaller than \p Res /// /// \return The newly created instruction. MachineInstrBuilder buildSExt(const DstOp &Res, const SrcOp &Op); /// Build and insert \p Res = G_SEXT_INREG \p Op, ImmOp MachineInstrBuilder buildSExtInReg(const DstOp &Res, const SrcOp &Op, int64_t ImmOp) { return buildInstr(TargetOpcode::G_SEXT_INREG, {Res}, {Op, SrcOp(ImmOp)}); } /// Build and insert \p Res = G_FPEXT \p Op MachineInstrBuilder buildFPExt(const DstOp &Res, const SrcOp &Op, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FPEXT, {Res}, {Op}, Flags); } /// Build and insert a G_PTRTOINT instruction. MachineInstrBuilder buildPtrToInt(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_PTRTOINT, {Dst}, {Src}); } /// Build and insert a G_INTTOPTR instruction. MachineInstrBuilder buildIntToPtr(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_INTTOPTR, {Dst}, {Src}); } /// Build and insert \p Dst = G_BITCAST \p Src MachineInstrBuilder buildBitcast(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_BITCAST, {Dst}, {Src}); } /// Build and insert \p Dst = G_ADDRSPACE_CAST \p Src MachineInstrBuilder buildAddrSpaceCast(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_ADDRSPACE_CAST, {Dst}, {Src}); } /// \return The opcode of the extension the target wants to use for boolean /// values. unsigned getBoolExtOp(bool IsVec, bool IsFP) const; // Build and insert \p Res = G_ANYEXT \p Op, \p Res = G_SEXT \p Op, or \p Res // = G_ZEXT \p Op depending on how the target wants to extend boolean values. MachineInstrBuilder buildBoolExt(const DstOp &Res, const SrcOp &Op, bool IsFP); /// Build and insert \p Res = G_ZEXT \p Op /// /// G_ZEXT produces a register of the specified width, with bits 0 to /// sizeof(\p Ty) * 8 set to \p Op. The remaining bits are 0. For a vector /// register, each element is extended individually. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or vector type. /// \pre \p Op must be a generic virtual register with scalar or vector type. /// \pre \p Op must be smaller than \p Res /// /// \return The newly created instruction. MachineInstrBuilder buildZExt(const DstOp &Res, const SrcOp &Op); /// Build and insert \p Res = G_SEXT \p Op, \p Res = G_TRUNC \p Op, or /// \p Res = COPY \p Op depending on the differing sizes of \p Res and \p Op. /// /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or vector type. /// \pre \p Op must be a generic virtual register with scalar or vector type. /// /// \return The newly created instruction. MachineInstrBuilder buildSExtOrTrunc(const DstOp &Res, const SrcOp &Op); /// Build and insert \p Res = G_ZEXT \p Op, \p Res = G_TRUNC \p Op, or /// \p Res = COPY \p Op depending on the differing sizes of \p Res and \p Op. /// /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or vector type. /// \pre \p Op must be a generic virtual register with scalar or vector type. /// /// \return The newly created instruction. MachineInstrBuilder buildZExtOrTrunc(const DstOp &Res, const SrcOp &Op); // Build and insert \p Res = G_ANYEXT \p Op, \p Res = G_TRUNC \p Op, or /// \p Res = COPY \p Op depending on the differing sizes of \p Res and \p Op. /// /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or vector type. /// \pre \p Op must be a generic virtual register with scalar or vector type. /// /// \return The newly created instruction. MachineInstrBuilder buildAnyExtOrTrunc(const DstOp &Res, const SrcOp &Op); /// Build and insert \p Res = \p ExtOpc, \p Res = G_TRUNC \p /// Op, or \p Res = COPY \p Op depending on the differing sizes of \p Res and /// \p Op. /// /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or vector type. /// \pre \p Op must be a generic virtual register with scalar or vector type. /// /// \return The newly created instruction. MachineInstrBuilder buildExtOrTrunc(unsigned ExtOpc, const DstOp &Res, const SrcOp &Op); /// Build and inserts \p Res = \p G_AND \p Op, \p LowBitsSet(ImmOp) /// Since there is no G_ZEXT_INREG like G_SEXT_INREG, the instruction is /// emulated using G_AND. MachineInstrBuilder buildZExtInReg(const DstOp &Res, const SrcOp &Op, int64_t ImmOp); /// Build and insert an appropriate cast between two registers of equal size. MachineInstrBuilder buildCast(const DstOp &Dst, const SrcOp &Src); /// Build and insert G_BR \p Dest /// /// G_BR is an unconditional branch to \p Dest. /// /// \pre setBasicBlock or setMI must have been called. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildBr(MachineBasicBlock &Dest); /// Build and insert G_BRCOND \p Tst, \p Dest /// /// G_BRCOND is a conditional branch to \p Dest. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Tst must be a generic virtual register with scalar /// type. At the beginning of legalization, this will be a single /// bit (s1). Targets with interesting flags registers may change /// this. For a wider type, whether the branch is taken must only /// depend on bit 0 (for now). /// /// \return The newly created instruction. MachineInstrBuilder buildBrCond(const SrcOp &Tst, MachineBasicBlock &Dest); /// Build and insert G_BRINDIRECT \p Tgt /// /// G_BRINDIRECT is an indirect branch to \p Tgt. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Tgt must be a generic virtual register with pointer type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildBrIndirect(Register Tgt); /// Build and insert G_BRJT \p TablePtr, \p JTI, \p IndexReg /// /// G_BRJT is a jump table branch using a table base pointer \p TablePtr, /// jump table index \p JTI and index \p IndexReg /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p TablePtr must be a generic virtual register with pointer type. /// \pre \p JTI must be be a jump table index. /// \pre \p IndexReg must be a generic virtual register with pointer type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildBrJT(Register TablePtr, unsigned JTI, Register IndexReg); /// Build and insert \p Res = G_CONSTANT \p Val /// /// G_CONSTANT is an integer constant with the specified size and value. \p /// Val will be extended or truncated to the size of \p Reg. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or pointer /// type. /// /// \return The newly created instruction. virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val); /// Build and insert \p Res = G_CONSTANT \p Val /// /// G_CONSTANT is an integer constant with the specified size and value. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar type. /// /// \return The newly created instruction. MachineInstrBuilder buildConstant(const DstOp &Res, int64_t Val); MachineInstrBuilder buildConstant(const DstOp &Res, const APInt &Val); /// Build and insert \p Res = G_FCONSTANT \p Val /// /// G_FCONSTANT is a floating-point constant with the specified size and /// value. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar type. /// /// \return The newly created instruction. virtual MachineInstrBuilder buildFConstant(const DstOp &Res, const ConstantFP &Val); MachineInstrBuilder buildFConstant(const DstOp &Res, double Val); MachineInstrBuilder buildFConstant(const DstOp &Res, const APFloat &Val); /// Build and insert \p Res = COPY Op /// /// Register-to-register COPY sets \p Res to \p Op. /// /// \pre setBasicBlock or setMI must have been called. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op); /// Build and insert G_ASSERT_SEXT, G_ASSERT_ZEXT, or G_ASSERT_ALIGN /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAssertOp(unsigned Opc, const DstOp &Res, const SrcOp &Op, unsigned Val) { return buildInstr(Opc, Res, Op).addImm(Val); } /// Build and insert \p Res = G_ASSERT_ZEXT Op, Size /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAssertZExt(const DstOp &Res, const SrcOp &Op, unsigned Size) { return buildAssertOp(TargetOpcode::G_ASSERT_ZEXT, Res, Op, Size); } /// Build and insert \p Res = G_ASSERT_SEXT Op, Size /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAssertSExt(const DstOp &Res, const SrcOp &Op, unsigned Size) { return buildAssertOp(TargetOpcode::G_ASSERT_SEXT, Res, Op, Size); } /// Build and insert \p Res = G_ASSERT_ALIGN Op, AlignVal /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAssertAlign(const DstOp &Res, const SrcOp &Op, Align AlignVal) { return buildAssertOp(TargetOpcode::G_ASSERT_ALIGN, Res, Op, AlignVal.value()); } /// Build and insert `Res = G_LOAD Addr, MMO`. /// /// Loads the value stored at \p Addr. Puts the result in \p Res. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildLoad(const DstOp &Res, const SrcOp &Addr, MachineMemOperand &MMO) { return buildLoadInstr(TargetOpcode::G_LOAD, Res, Addr, MMO); } /// Build and insert a G_LOAD instruction, while constructing the /// MachineMemOperand. MachineInstrBuilder buildLoad(const DstOp &Res, const SrcOp &Addr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone, const AAMDNodes &AAInfo = AAMDNodes()); /// Build and insert `Res = <opcode> Addr, MMO`. /// /// Loads the value stored at \p Addr. Puts the result in \p Res. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildLoadInstr(unsigned Opcode, const DstOp &Res, const SrcOp &Addr, MachineMemOperand &MMO); /// Helper to create a load from a constant offset given a base address. Load /// the type of \p Dst from \p Offset from the given base address and memory /// operand. MachineInstrBuilder buildLoadFromOffset(const DstOp &Dst, const SrcOp &BasePtr, MachineMemOperand &BaseMMO, int64_t Offset); /// Build and insert `G_STORE Val, Addr, MMO`. /// /// Stores the value \p Val to \p Addr. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Val must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachineMemOperand &MMO); /// Build and insert a G_STORE instruction, while constructing the /// MachineMemOperand. MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone, const AAMDNodes &AAInfo = AAMDNodes()); /// Build and insert `Res0, ... = G_EXTRACT Src, Idx0`. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res and \p Src must be generic virtual registers. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildExtract(const DstOp &Res, const SrcOp &Src, uint64_t Index); /// Build and insert \p Res = IMPLICIT_DEF. MachineInstrBuilder buildUndef(const DstOp &Res); /// Build and insert instructions to put \p Ops together at the specified p /// Indices to form a larger register. /// /// If the types of the input registers are uniform and cover the entirity of /// \p Res then a G_MERGE_VALUES will be produced. Otherwise an IMPLICIT_DEF /// followed by a sequence of G_INSERT instructions. /// /// \pre setBasicBlock or setMI must have been called. /// \pre The final element of the sequence must not extend past the end of the /// destination register. /// \pre The bits defined by each Op (derived from index and scalar size) must /// not overlap. /// \pre \p Indices must be in ascending order of bit position. void buildSequence(Register Res, ArrayRef<Register> Ops, ArrayRef<uint64_t> Indices); /// Build and insert \p Res = G_MERGE_VALUES \p Op0, ... /// /// G_MERGE_VALUES combines the input elements contiguously into a larger /// register. /// /// \pre setBasicBlock or setMI must have been called. /// \pre The entire register \p Res (and no more) must be covered by the input /// registers. /// \pre The type of all \p Ops registers must be identical. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildMerge(const DstOp &Res, ArrayRef<Register> Ops); MachineInstrBuilder buildMerge(const DstOp &Res, std::initializer_list<SrcOp> Ops); /// Build and insert \p Res0, ... = G_UNMERGE_VALUES \p Op /// /// G_UNMERGE_VALUES splits contiguous bits of the input into multiple /// /// \pre setBasicBlock or setMI must have been called. /// \pre The entire register \p Res (and no more) must be covered by the input /// registers. /// \pre The type of all \p Res registers must be identical. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildUnmerge(ArrayRef<LLT> Res, const SrcOp &Op); MachineInstrBuilder buildUnmerge(ArrayRef<Register> Res, const SrcOp &Op); /// Build and insert an unmerge of \p Res sized pieces to cover \p Op MachineInstrBuilder buildUnmerge(LLT Res, const SrcOp &Op); /// Build and insert \p Res = G_BUILD_VECTOR \p Op0, ... /// /// G_BUILD_VECTOR creates a vector value from multiple scalar registers. /// \pre setBasicBlock or setMI must have been called. /// \pre The entire register \p Res (and no more) must be covered by the /// input scalar registers. /// \pre The type of all \p Ops registers must be identical. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildBuildVector(const DstOp &Res, ArrayRef<Register> Ops); /// Build and insert \p Res = G_BUILD_VECTOR \p Op0, ... where each OpN is /// built with G_CONSTANT. MachineInstrBuilder buildBuildVectorConstant(const DstOp &Res, ArrayRef<APInt> Ops); /// Build and insert \p Res = G_BUILD_VECTOR with \p Src replicated to fill /// the number of elements MachineInstrBuilder buildSplatVector(const DstOp &Res, const SrcOp &Src); /// Build and insert \p Res = G_BUILD_VECTOR_TRUNC \p Op0, ... /// /// G_BUILD_VECTOR_TRUNC creates a vector value from multiple scalar registers /// which have types larger than the destination vector element type, and /// truncates the values to fit. /// /// If the operands given are already the same size as the vector elt type, /// then this method will instead create a G_BUILD_VECTOR instruction. /// /// \pre setBasicBlock or setMI must have been called. /// \pre The type of all \p Ops registers must be identical. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildBuildVectorTrunc(const DstOp &Res, ArrayRef<Register> Ops); /// Build and insert a vector splat of a scalar \p Src using a /// G_INSERT_VECTOR_ELT and G_SHUFFLE_VECTOR idiom. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Src must have the same type as the element type of \p Dst /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildShuffleSplat(const DstOp &Res, const SrcOp &Src); /// Build and insert \p Res = G_SHUFFLE_VECTOR \p Src1, \p Src2, \p Mask /// /// \pre setBasicBlock or setMI must have been called. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildShuffleVector(const DstOp &Res, const SrcOp &Src1, const SrcOp &Src2, ArrayRef<int> Mask); /// Build and insert \p Res = G_CONCAT_VECTORS \p Op0, ... /// /// G_CONCAT_VECTORS creates a vector from the concatenation of 2 or more /// vectors. /// /// \pre setBasicBlock or setMI must have been called. /// \pre The entire register \p Res (and no more) must be covered by the input /// registers. /// \pre The type of all source operands must be identical. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildConcatVectors(const DstOp &Res, ArrayRef<Register> Ops); MachineInstrBuilder buildInsert(const DstOp &Res, const SrcOp &Src, const SrcOp &Op, unsigned Index); /// Build and insert either a G_INTRINSIC (if \p HasSideEffects is false) or /// G_INTRINSIC_W_SIDE_EFFECTS instruction. Its first operand will be the /// result register definition unless \p Reg is NoReg (== 0). The second /// operand will be the intrinsic's ID. /// /// Callers are expected to add the required definitions and uses afterwards. /// /// \pre setBasicBlock or setMI must have been called. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildIntrinsic(Intrinsic::ID ID, ArrayRef<Register> Res, bool HasSideEffects); MachineInstrBuilder buildIntrinsic(Intrinsic::ID ID, ArrayRef<DstOp> Res, bool HasSideEffects); /// Build and insert \p Res = G_FPTRUNC \p Op /// /// G_FPTRUNC converts a floating-point value into one with a smaller type. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or vector type. /// \pre \p Op must be a generic virtual register with scalar or vector type. /// \pre \p Res must be smaller than \p Op /// /// \return The newly created instruction. MachineInstrBuilder buildFPTrunc(const DstOp &Res, const SrcOp &Op, Optional<unsigned> Flags = None); /// Build and insert \p Res = G_TRUNC \p Op /// /// G_TRUNC extracts the low bits of a type. For a vector type each element is /// truncated independently before being packed into the destination. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or vector type. /// \pre \p Op must be a generic virtual register with scalar or vector type. /// \pre \p Res must be smaller than \p Op /// /// \return The newly created instruction. MachineInstrBuilder buildTrunc(const DstOp &Res, const SrcOp &Op); /// Build and insert a \p Res = G_ICMP \p Pred, \p Op0, \p Op1 /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or /// vector type. Typically this starts as s1 or <N x s1>. /// \pre \p Op0 and Op1 must be generic virtual registers with the /// same number of elements as \p Res. If \p Res is a scalar, /// \p Op0 must be either a scalar or pointer. /// \pre \p Pred must be an integer predicate. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildICmp(CmpInst::Predicate Pred, const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1); /// Build and insert a \p Res = G_FCMP \p Pred\p Op0, \p Op1 /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar or /// vector type. Typically this starts as s1 or <N x s1>. /// \pre \p Op0 and Op1 must be generic virtual registers with the /// same number of elements as \p Res (or scalar, if \p Res is /// scalar). /// \pre \p Pred must be a floating-point predicate. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildFCmp(CmpInst::Predicate Pred, const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, Optional<unsigned> Flags = None); /// Build and insert a \p Res = G_SELECT \p Tst, \p Op0, \p Op1 /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res, \p Op0 and \p Op1 must be generic virtual registers /// with the same type. /// \pre \p Tst must be a generic virtual register with scalar, pointer or /// vector type. If vector then it must have the same number of /// elements as the other parameters. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildSelect(const DstOp &Res, const SrcOp &Tst, const SrcOp &Op0, const SrcOp &Op1, Optional<unsigned> Flags = None); /// Build and insert \p Res = G_INSERT_VECTOR_ELT \p Val, /// \p Elt, \p Idx /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res and \p Val must be a generic virtual register // with the same vector type. /// \pre \p Elt and \p Idx must be a generic virtual register /// with scalar type. /// /// \return The newly created instruction. MachineInstrBuilder buildInsertVectorElement(const DstOp &Res, const SrcOp &Val, const SrcOp &Elt, const SrcOp &Idx); /// Build and insert \p Res = G_EXTRACT_VECTOR_ELT \p Val, \p Idx /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register with scalar type. /// \pre \p Val must be a generic virtual register with vector type. /// \pre \p Idx must be a generic virtual register with scalar type. /// /// \return The newly created instruction. MachineInstrBuilder buildExtractVectorElement(const DstOp &Res, const SrcOp &Val, const SrcOp &Idx); /// Build and insert `OldValRes<def>, SuccessRes<def> = /// G_ATOMIC_CMPXCHG_WITH_SUCCESS Addr, CmpVal, NewVal, MMO`. /// /// Atomically replace the value at \p Addr with \p NewVal if it is currently /// \p CmpVal otherwise leaves it unchanged. Puts the original value from \p /// Addr in \p Res, along with an s1 indicating whether it was replaced. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register of scalar type. /// \pre \p SuccessRes must be a generic virtual register of scalar type. It /// will be assigned 0 on failure and 1 on success. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, \p CmpVal, and \p NewVal must be generic virtual /// registers of the same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicCmpXchgWithSuccess(Register OldValRes, Register SuccessRes, Register Addr, Register CmpVal, Register NewVal, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMIC_CMPXCHG Addr, CmpVal, NewVal, /// MMO`. /// /// Atomically replace the value at \p Addr with \p NewVal if it is currently /// \p CmpVal otherwise leaves it unchanged. Puts the original value from \p /// Addr in \p Res. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register of scalar type. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, \p CmpVal, and \p NewVal must be generic virtual /// registers of the same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicCmpXchg(Register OldValRes, Register Addr, Register CmpVal, Register NewVal, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_<Opcode> Addr, Val, MMO`. /// /// Atomically read-modify-update the value at \p Addr with \p Val. Puts the /// original value from \p Addr in \p OldValRes. The modification is /// determined by the opcode. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMW(unsigned Opcode, const DstOp &OldValRes, const SrcOp &Addr, const SrcOp &Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_XCHG Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with \p Val. Puts the original /// value from \p Addr in \p OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWXchg(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_ADD Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the addition of \p Val and /// the original value. Puts the original value from \p Addr in \p OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWAdd(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_SUB Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the subtraction of \p Val and /// the original value. Puts the original value from \p Addr in \p OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWSub(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_AND Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the bitwise and of \p Val and /// the original value. Puts the original value from \p Addr in \p OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWAnd(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_NAND Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the bitwise nand of \p Val /// and the original value. Puts the original value from \p Addr in \p /// OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWNand(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_OR Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the bitwise or of \p Val and /// the original value. Puts the original value from \p Addr in \p OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWOr(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_XOR Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the bitwise xor of \p Val and /// the original value. Puts the original value from \p Addr in \p OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWXor(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_MAX Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the signed maximum of \p /// Val and the original value. Puts the original value from \p Addr in \p /// OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWMax(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_MIN Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the signed minimum of \p /// Val and the original value. Puts the original value from \p Addr in \p /// OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWMin(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_UMAX Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the unsigned maximum of \p /// Val and the original value. Puts the original value from \p Addr in \p /// OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWUmax(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_UMIN Addr, Val, MMO`. /// /// Atomically replace the value at \p Addr with the unsigned minimum of \p /// Val and the original value. Puts the original value from \p Addr in \p /// OldValRes. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p OldValRes must be a generic virtual register. /// \pre \p Addr must be a generic virtual register with pointer type. /// \pre \p OldValRes, and \p Val must be generic virtual registers of the /// same type. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAtomicRMWUmin(Register OldValRes, Register Addr, Register Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_FADD Addr, Val, MMO`. MachineInstrBuilder buildAtomicRMWFAdd( const DstOp &OldValRes, const SrcOp &Addr, const SrcOp &Val, MachineMemOperand &MMO); /// Build and insert `OldValRes<def> = G_ATOMICRMW_FSUB Addr, Val, MMO`. MachineInstrBuilder buildAtomicRMWFSub( const DstOp &OldValRes, const SrcOp &Addr, const SrcOp &Val, MachineMemOperand &MMO); /// Build and insert `G_FENCE Ordering, Scope`. MachineInstrBuilder buildFence(unsigned Ordering, unsigned Scope); /// Build and insert \p Dst = G_FREEZE \p Src MachineInstrBuilder buildFreeze(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_FREEZE, {Dst}, {Src}); } /// Build and insert \p Res = G_BLOCK_ADDR \p BA /// /// G_BLOCK_ADDR computes the address of a basic block. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res must be a generic virtual register of a pointer type. /// /// \return The newly created instruction. MachineInstrBuilder buildBlockAddress(Register Res, const BlockAddress *BA); /// Build and insert \p Res = G_ADD \p Op0, \p Op1 /// /// G_ADD sets \p Res to the sum of integer parameters \p Op0 and \p Op1, /// truncated to their width. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res, \p Op0 and \p Op1 must be generic virtual registers /// with the same (scalar or vector) type). /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAdd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_ADD, {Dst}, {Src0, Src1}, Flags); } /// Build and insert \p Res = G_SUB \p Op0, \p Op1 /// /// G_SUB sets \p Res to the difference of integer parameters \p Op0 and /// \p Op1, truncated to their width. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res, \p Op0 and \p Op1 must be generic virtual registers /// with the same (scalar or vector) type). /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildSub(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_SUB, {Dst}, {Src0, Src1}, Flags); } /// Build and insert \p Res = G_MUL \p Op0, \p Op1 /// /// G_MUL sets \p Res to the product of integer parameters \p Op0 and \p Op1, /// truncated to their width. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res, \p Op0 and \p Op1 must be generic virtual registers /// with the same (scalar or vector) type). /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildMul(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_MUL, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildUMulH(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_UMULH, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildSMulH(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_SMULH, {Dst}, {Src0, Src1}, Flags); } /// Build and insert \p Res = G_UREM \p Op0, \p Op1 MachineInstrBuilder buildURem(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_UREM, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildFMul(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FMUL, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildFMinNum(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FMINNUM, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildFMaxNum(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FMAXNUM, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildFMinNumIEEE(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FMINNUM_IEEE, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildFMaxNumIEEE(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FMAXNUM_IEEE, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildShl(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_SHL, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildLShr(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_LSHR, {Dst}, {Src0, Src1}, Flags); } MachineInstrBuilder buildAShr(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_ASHR, {Dst}, {Src0, Src1}, Flags); } /// Build and insert \p Res = G_AND \p Op0, \p Op1 /// /// G_AND sets \p Res to the bitwise and of integer parameters \p Op0 and \p /// Op1. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res, \p Op0 and \p Op1 must be generic virtual registers /// with the same (scalar or vector) type). /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildAnd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1) { return buildInstr(TargetOpcode::G_AND, {Dst}, {Src0, Src1}); } /// Build and insert \p Res = G_OR \p Op0, \p Op1 /// /// G_OR sets \p Res to the bitwise or of integer parameters \p Op0 and \p /// Op1. /// /// \pre setBasicBlock or setMI must have been called. /// \pre \p Res, \p Op0 and \p Op1 must be generic virtual registers /// with the same (scalar or vector) type). /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildOr(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_OR, {Dst}, {Src0, Src1}, Flags); } /// Build and insert \p Res = G_XOR \p Op0, \p Op1 MachineInstrBuilder buildXor(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1) { return buildInstr(TargetOpcode::G_XOR, {Dst}, {Src0, Src1}); } /// Build and insert a bitwise not, /// \p NegOne = G_CONSTANT -1 /// \p Res = G_OR \p Op0, NegOne MachineInstrBuilder buildNot(const DstOp &Dst, const SrcOp &Src0) { auto NegOne = buildConstant(Dst.getLLTTy(*getMRI()), -1); return buildInstr(TargetOpcode::G_XOR, {Dst}, {Src0, NegOne}); } /// Build and insert integer negation /// \p Zero = G_CONSTANT 0 /// \p Res = G_SUB Zero, \p Op0 MachineInstrBuilder buildNeg(const DstOp &Dst, const SrcOp &Src0) { auto Zero = buildConstant(Dst.getLLTTy(*getMRI()), 0); return buildInstr(TargetOpcode::G_SUB, {Dst}, {Zero, Src0}); } /// Build and insert \p Res = G_CTPOP \p Op0, \p Src0 MachineInstrBuilder buildCTPOP(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_CTPOP, {Dst}, {Src0}); } /// Build and insert \p Res = G_CTLZ \p Op0, \p Src0 MachineInstrBuilder buildCTLZ(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_CTLZ, {Dst}, {Src0}); } /// Build and insert \p Res = G_CTLZ_ZERO_UNDEF \p Op0, \p Src0 MachineInstrBuilder buildCTLZ_ZERO_UNDEF(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_CTLZ_ZERO_UNDEF, {Dst}, {Src0}); } /// Build and insert \p Res = G_CTTZ \p Op0, \p Src0 MachineInstrBuilder buildCTTZ(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_CTTZ, {Dst}, {Src0}); } /// Build and insert \p Res = G_CTTZ_ZERO_UNDEF \p Op0, \p Src0 MachineInstrBuilder buildCTTZ_ZERO_UNDEF(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_CTTZ_ZERO_UNDEF, {Dst}, {Src0}); } /// Build and insert \p Dst = G_BSWAP \p Src0 MachineInstrBuilder buildBSwap(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_BSWAP, {Dst}, {Src0}); } /// Build and insert \p Res = G_FADD \p Op0, \p Op1 MachineInstrBuilder buildFAdd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FADD, {Dst}, {Src0, Src1}, Flags); } /// Build and insert \p Res = G_FSUB \p Op0, \p Op1 MachineInstrBuilder buildFSub(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FSUB, {Dst}, {Src0, Src1}, Flags); } /// Build and insert \p Res = G_FDIV \p Op0, \p Op1 MachineInstrBuilder buildFDiv(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FDIV, {Dst}, {Src0, Src1}, Flags); } /// Build and insert \p Res = G_FMA \p Op0, \p Op1, \p Op2 MachineInstrBuilder buildFMA(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, const SrcOp &Src2, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FMA, {Dst}, {Src0, Src1, Src2}, Flags); } /// Build and insert \p Res = G_FMAD \p Op0, \p Op1, \p Op2 MachineInstrBuilder buildFMAD(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, const SrcOp &Src2, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FMAD, {Dst}, {Src0, Src1, Src2}, Flags); } /// Build and insert \p Res = G_FNEG \p Op0 MachineInstrBuilder buildFNeg(const DstOp &Dst, const SrcOp &Src0, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FNEG, {Dst}, {Src0}, Flags); } /// Build and insert \p Res = G_FABS \p Op0 MachineInstrBuilder buildFAbs(const DstOp &Dst, const SrcOp &Src0, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FABS, {Dst}, {Src0}, Flags); } /// Build and insert \p Dst = G_FCANONICALIZE \p Src0 MachineInstrBuilder buildFCanonicalize(const DstOp &Dst, const SrcOp &Src0, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FCANONICALIZE, {Dst}, {Src0}, Flags); } /// Build and insert \p Dst = G_INTRINSIC_TRUNC \p Src0 MachineInstrBuilder buildIntrinsicTrunc(const DstOp &Dst, const SrcOp &Src0, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_INTRINSIC_TRUNC, {Dst}, {Src0}, Flags); } /// Build and insert \p Res = GFFLOOR \p Op0, \p Op1 MachineInstrBuilder buildFFloor(const DstOp &Dst, const SrcOp &Src0, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FFLOOR, {Dst}, {Src0}, Flags); } /// Build and insert \p Dst = G_FLOG \p Src MachineInstrBuilder buildFLog(const DstOp &Dst, const SrcOp &Src, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FLOG, {Dst}, {Src}, Flags); } /// Build and insert \p Dst = G_FLOG2 \p Src MachineInstrBuilder buildFLog2(const DstOp &Dst, const SrcOp &Src, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FLOG2, {Dst}, {Src}, Flags); } /// Build and insert \p Dst = G_FEXP2 \p Src MachineInstrBuilder buildFExp2(const DstOp &Dst, const SrcOp &Src, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FEXP2, {Dst}, {Src}, Flags); } /// Build and insert \p Dst = G_FPOW \p Src0, \p Src1 MachineInstrBuilder buildFPow(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, Optional<unsigned> Flags = None) { return buildInstr(TargetOpcode::G_FPOW, {Dst}, {Src0, Src1}, Flags); } /// Build and insert \p Res = G_FCOPYSIGN \p Op0, \p Op1 MachineInstrBuilder buildFCopysign(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1) { return buildInstr(TargetOpcode::G_FCOPYSIGN, {Dst}, {Src0, Src1}); } /// Build and insert \p Res = G_UITOFP \p Src0 MachineInstrBuilder buildUITOFP(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_UITOFP, {Dst}, {Src0}); } /// Build and insert \p Res = G_SITOFP \p Src0 MachineInstrBuilder buildSITOFP(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_SITOFP, {Dst}, {Src0}); } /// Build and insert \p Res = G_FPTOUI \p Src0 MachineInstrBuilder buildFPTOUI(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_FPTOUI, {Dst}, {Src0}); } /// Build and insert \p Res = G_FPTOSI \p Src0 MachineInstrBuilder buildFPTOSI(const DstOp &Dst, const SrcOp &Src0) { return buildInstr(TargetOpcode::G_FPTOSI, {Dst}, {Src0}); } /// Build and insert \p Res = G_SMIN \p Op0, \p Op1 MachineInstrBuilder buildSMin(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1) { return buildInstr(TargetOpcode::G_SMIN, {Dst}, {Src0, Src1}); } /// Build and insert \p Res = G_SMAX \p Op0, \p Op1 MachineInstrBuilder buildSMax(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1) { return buildInstr(TargetOpcode::G_SMAX, {Dst}, {Src0, Src1}); } /// Build and insert \p Res = G_UMIN \p Op0, \p Op1 MachineInstrBuilder buildUMin(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1) { return buildInstr(TargetOpcode::G_UMIN, {Dst}, {Src0, Src1}); } /// Build and insert \p Res = G_UMAX \p Op0, \p Op1 MachineInstrBuilder buildUMax(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1) { return buildInstr(TargetOpcode::G_UMAX, {Dst}, {Src0, Src1}); } /// Build and insert \p Dst = G_ABS \p Src MachineInstrBuilder buildAbs(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_ABS, {Dst}, {Src}); } /// Build and insert \p Res = G_JUMP_TABLE \p JTI /// /// G_JUMP_TABLE sets \p Res to the address of the jump table specified by /// the jump table index \p JTI. /// /// \return a MachineInstrBuilder for the newly created instruction. MachineInstrBuilder buildJumpTable(const LLT PtrTy, unsigned JTI); /// Build and insert \p Res = G_VECREDUCE_SEQ_FADD \p ScalarIn, \p VecIn /// /// \p ScalarIn is the scalar accumulator input to start the sequential /// reduction operation of \p VecIn. MachineInstrBuilder buildVecReduceSeqFAdd(const DstOp &Dst, const SrcOp &ScalarIn, const SrcOp &VecIn) { return buildInstr(TargetOpcode::G_VECREDUCE_SEQ_FADD, {Dst}, {ScalarIn, {VecIn}}); } /// Build and insert \p Res = G_VECREDUCE_SEQ_FMUL \p ScalarIn, \p VecIn /// /// \p ScalarIn is the scalar accumulator input to start the sequential /// reduction operation of \p VecIn. MachineInstrBuilder buildVecReduceSeqFMul(const DstOp &Dst, const SrcOp &ScalarIn, const SrcOp &VecIn) { return buildInstr(TargetOpcode::G_VECREDUCE_SEQ_FMUL, {Dst}, {ScalarIn, {VecIn}}); } /// Build and insert \p Res = G_VECREDUCE_FADD \p Src /// /// \p ScalarIn is the scalar accumulator input to the reduction operation of /// \p VecIn. MachineInstrBuilder buildVecReduceFAdd(const DstOp &Dst, const SrcOp &ScalarIn, const SrcOp &VecIn) { return buildInstr(TargetOpcode::G_VECREDUCE_FADD, {Dst}, {ScalarIn, VecIn}); } /// Build and insert \p Res = G_VECREDUCE_FMUL \p Src /// /// \p ScalarIn is the scalar accumulator input to the reduction operation of /// \p VecIn. MachineInstrBuilder buildVecReduceFMul(const DstOp &Dst, const SrcOp &ScalarIn, const SrcOp &VecIn) { return buildInstr(TargetOpcode::G_VECREDUCE_FMUL, {Dst}, {ScalarIn, VecIn}); } /// Build and insert \p Res = G_VECREDUCE_FMAX \p Src MachineInstrBuilder buildVecReduceFMax(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_FMAX, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_FMIN \p Src MachineInstrBuilder buildVecReduceFMin(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_FMIN, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_ADD \p Src MachineInstrBuilder buildVecReduceAdd(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_ADD, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_MUL \p Src MachineInstrBuilder buildVecReduceMul(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_MUL, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_AND \p Src MachineInstrBuilder buildVecReduceAnd(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_AND, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_OR \p Src MachineInstrBuilder buildVecReduceOr(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_OR, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_XOR \p Src MachineInstrBuilder buildVecReduceXor(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_XOR, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_SMAX \p Src MachineInstrBuilder buildVecReduceSMax(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_SMAX, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_SMIN \p Src MachineInstrBuilder buildVecReduceSMin(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_SMIN, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_UMAX \p Src MachineInstrBuilder buildVecReduceUMax(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_UMAX, {Dst}, {Src}); } /// Build and insert \p Res = G_VECREDUCE_UMIN \p Src MachineInstrBuilder buildVecReduceUMin(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_VECREDUCE_UMIN, {Dst}, {Src}); } /// Build and insert G_MEMCPY or G_MEMMOVE MachineInstrBuilder buildMemTransferInst(unsigned Opcode, const SrcOp &DstPtr, const SrcOp &SrcPtr, const SrcOp &Size, MachineMemOperand &DstMMO, MachineMemOperand &SrcMMO) { auto MIB = buildInstr( Opcode, {}, {DstPtr, SrcPtr, Size, SrcOp(INT64_C(0) /*isTailCall*/)}); MIB.addMemOperand(&DstMMO); MIB.addMemOperand(&SrcMMO); return MIB; } MachineInstrBuilder buildMemCpy(const SrcOp &DstPtr, const SrcOp &SrcPtr, const SrcOp &Size, MachineMemOperand &DstMMO, MachineMemOperand &SrcMMO) { return buildMemTransferInst(TargetOpcode::G_MEMCPY, DstPtr, SrcPtr, Size, DstMMO, SrcMMO); } /// Build and insert \p Dst = G_SBFX \p Src, \p LSB, \p Width. MachineInstrBuilder buildSbfx(const DstOp &Dst, const SrcOp &Src, const SrcOp &LSB, const SrcOp &Width) { return buildInstr(TargetOpcode::G_SBFX, {Dst}, {Src, LSB, Width}); } /// Build and insert \p Dst = G_UBFX \p Src, \p LSB, \p Width. MachineInstrBuilder buildUbfx(const DstOp &Dst, const SrcOp &Src, const SrcOp &LSB, const SrcOp &Width) { return buildInstr(TargetOpcode::G_UBFX, {Dst}, {Src, LSB, Width}); } /// Build and insert \p Dst = G_ROTR \p Src, \p Amt MachineInstrBuilder buildRotateRight(const DstOp &Dst, const SrcOp &Src, const SrcOp &Amt) { return buildInstr(TargetOpcode::G_ROTR, {Dst}, {Src, Amt}); } /// Build and insert \p Dst = G_ROTL \p Src, \p Amt MachineInstrBuilder buildRotateLeft(const DstOp &Dst, const SrcOp &Src, const SrcOp &Amt) { return buildInstr(TargetOpcode::G_ROTL, {Dst}, {Src, Amt}); } /// Build and insert \p Dst = G_BITREVERSE \p Src MachineInstrBuilder buildBitReverse(const DstOp &Dst, const SrcOp &Src) { return buildInstr(TargetOpcode::G_BITREVERSE, {Dst}, {Src}); } virtual MachineInstrBuilder buildInstr(unsigned Opc, ArrayRef<DstOp> DstOps, ArrayRef<SrcOp> SrcOps, Optional<unsigned> Flags = None); }; } // End namespace llvm. #endif // LLVM_CODEGEN_GLOBALISEL_MACHINEIRBUILDER_H
42.144547
88
0.644192
[ "object", "vector" ]
7febbe07f84d82b898d6d3ea3b251e3b11efae3a
4,322
h
C
src/Vector3/Vector3.h
jerabaul29/vect_quat_simple_cpp
5b94a8b42514b3bf78420487849483047d73d6c8
[ "MIT" ]
null
null
null
src/Vector3/Vector3.h
jerabaul29/vect_quat_simple_cpp
5b94a8b42514b3bf78420487849483047d73d6c8
[ "MIT" ]
null
null
null
src/Vector3/Vector3.h
jerabaul29/vect_quat_simple_cpp
5b94a8b42514b3bf78420487849483047d73d6c8
[ "MIT" ]
null
null
null
/* Vector in dimension 3 */ #ifndef VQS_VECTOR3 #define VQS_VECTOR3 namespace vqs{ // ---------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------- // the Vector3 class, and its member functions // Vector3 is a 3D vector, with template-defined type template<typename type_base> class Vector3{ public: // -------------------- // a Vector3 has 3 components type_base ui; type_base uj; type_base uk; // -------------------- // constructors Vector3(void); Vector3(Vector3<type_base> const & vin); Vector3(type_base const ui, type_base const uj, type_base const uk); // -------------------- // norm properties type_base norm_squared(void) const; bool is_normed(type_base tol=VQS_DEFAULT_TOL) const; type_base norm(void) const; // -------------------- // modifiers void nullify(void); bool normalize(type_base tol=VQS_DEFAULT_TOL); }; // -------------------- // constructors // default constructor initializes to 0 template<typename type_base> Vector3<type_base>::Vector3(void): ui{0}, uj{0}, uk{0} {}; // copy constructor performs a deep copy template<typename type_base> Vector3<type_base>::Vector3(Vector3<type_base> const & vin): ui{vin.ui}, uj{vin.uj}, uk{vin.uk} {}; // construct by giving custom values template<typename type_base> Vector3<type_base>::Vector3(type_base const ui, type_base const uj, type_base const uk): ui{ui}, uj{uj}, uk{uk} {}; // -------------------- // norm properties // calculate the squared norm template<typename type_base> type_base Vector3<type_base>::norm_squared(void) const{ return ui*ui + uj*uj + uk*uk; } // calculate the norm template<typename type_base> type_base Vector3<type_base>::norm(void) const{ return sqrt(ui*ui + uj*uj + uk*uk); } // testing if the vector is normed, by looking at the square of the norm with a tolerance template<typename type_base> bool Vector3<type_base>::is_normed(type_base tol) const{ return abs(1 - this->norm_squared()) < tol; } // -------------------- // mofifiers // nullify, i.e. make equal to 0 template<typename type_base> void Vector3<type_base>::nullify(void){ ui = static_cast<type_base>(0.0); uj = static_cast<type_base>(0.0); uk = static_cast<type_base>(0.0); } // normalize the vector so that it gets norm 1, and return true; // in case this is the 0 vector, return false template<typename type_base> bool Vector3<type_base>::normalize(type_base tol){ type_base norm = this->norm(); if (abs(norm) < tol){ return false; } ui /= norm; uj /= norm; uk /= norm; return true; } // ---------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------- // extern functions acting on Vector3 objects // dot product as a pure function template<typename type_base> type_base dot_product(Vector3<type_base> const & vec_1, Vector3<type_base> const & vec_2){ } // dot to a pre-allocated output template<typename type_base> void dot_product(Vector3<type_base> const & vec_1, Vector3<type_base> const & vec_2, type_base & result){ } // TODO: put the double versions // addition as a pure function // addition to a pre-allocated output // negation as a pure function // negation to a pre-allocated output // scaling as a pure function // scaling to a pre-allocated output // subtraction as a pure function // subtraction to a pre-allocated output // cross product as a pure function template<typename type_base> // cross product to a pre-allocated output template<typename type_base> } #endif
28.064935
119
0.533087
[ "vector", "3d" ]
7fef711e3cee94d9270b0de03150d82be4ec4370
881
h
C
Source/Framework/Core/Manager/TeRendererManager.h
fabsgc/TweedeFramework
dfd48f53a6c64b1c8b11ae2ed204dbfcb3ae6fda
[ "MIT" ]
2
2019-04-18T18:13:51.000Z
2020-06-02T10:58:21.000Z
Source/Framework/Core/Manager/TeRendererManager.h
fabsgc/TweedeFramework
dfd48f53a6c64b1c8b11ae2ed204dbfcb3ae6fda
[ "MIT" ]
null
null
null
Source/Framework/Core/Manager/TeRendererManager.h
fabsgc/TweedeFramework
dfd48f53a6c64b1c8b11ae2ed204dbfcb3ae6fda
[ "MIT" ]
1
2020-02-11T15:38:27.000Z
2020-02-11T15:38:27.000Z
#pragma once #include "TeCorePrerequisites.h" #include "Utility/TeModule.h" #include "Renderer/TeRenderer.h" #include "Renderer/TeRendererFactory.h" namespace te { /** Manager that handles render system start up. */ class TE_CORE_EXPORT RendererManager : public Module<RendererManager> { public: /** Initializes the renderer, making it ready to render. */ SPtr<Renderer> Initialize(const String& pluginFilename); /** Returns the current renderer. Null if no renderer is active. */ SPtr<Renderer> GetRenderer() { return _renderer; } /** Registers a new render API factory responsible for creating a specific render system type. */ void RegisterFactory(SPtr<RendererFactory> factory); private: Vector<SPtr<RendererFactory>> _availableFactories; SPtr<Renderer> _renderer; }; /** @} */ }
30.37931
105
0.685585
[ "render", "vector" ]
7ff0bd215952a62d3cfcd6e8cdb182a7e51e8853
5,733
h
C
vendors/cypress/psoc6/psoc6csp/hal/include/cyhal_rtc.h
zst123/project-fimble_amazon-freertos
9ce6828264abda19c8befbfb4ef090de621ebbc9
[ "MIT" ]
null
null
null
vendors/cypress/psoc6/psoc6csp/hal/include/cyhal_rtc.h
zst123/project-fimble_amazon-freertos
9ce6828264abda19c8befbfb4ef090de621ebbc9
[ "MIT" ]
null
null
null
vendors/cypress/psoc6/psoc6csp/hal/include/cyhal_rtc.h
zst123/project-fimble_amazon-freertos
9ce6828264abda19c8befbfb4ef090de621ebbc9
[ "MIT" ]
null
null
null
/***************************************************************************//** * \file cyhal_rtc.h * * \brief * Provides a high level interface for interacting with the Real Time Clock on * Cypress devices. This interface abstracts out the chip specific details. * If any chip specific functionality is necessary, or performance is critical * the low level functions can be used directly. * ******************************************************************************** * \copyright * Copyright 2018-2019 Cypress Semiconductor Corporation * SPDX-License-Identifier: Apache-2.0 * * 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. *******************************************************************************/ /** * \addtogroup group_hal_rtc RTC (Real-Time Clock) * \ingroup group_hal * \{ * High level interface for interacting with the Cypress RTC. * * The real time clock provides tracking of the current time and date, as * well as the ability to trigger a callback at a specific time in the future. * * If a suitable clock source is available, the RTC can continue timekeeping * operations even when the device is in a low power operating mode. See the * device datasheet for more details. */ #pragma once #include <stdint.h> #include <stdbool.h> #include <time.h> #include "cy_result.h" #include "cyhal_hw_types.h" #include "cyhal_modules.h" /** RTC not initialized */ #define CY_RSLT_RTC_NOT_INITIALIZED CY_RSLT_CREATE(CY_RSLT_TYPE_ERROR, CYHAL_RSLT_MODULE_RTC, 0) #if defined(__cplusplus) extern "C" { #endif /** RTC interrupt triggers */ typedef enum { CYHAL_RTC_ALARM, } cyhal_rtc_event_t; /** @brief Defines which fields should be active for the alarm. */ typedef struct { uint8_t en_sec : 1; /** !< Enable match of seconds */ uint8_t en_min : 1; /** !< Enable match of minutes */ uint8_t en_hour : 1; /** !< Enable match of hours */ uint8_t en_day : 1; /** !< Enable match of day of week */ uint8_t en_date : 1; /** !< Enable match of date in month */ uint8_t en_month : 1; /** !< Enable match of month */ } cyhal_alarm_active_t; /** Handler for RTC events */ typedef void (*cyhal_rtc_event_callback_t)(void *callback_arg, cyhal_rtc_event_t event); /** Initialize the RTC peripheral * * Powerup the RTC in preparation for access. This function must be called * before any other RTC functions are called. This does not change the state * of the RTC. It just enables access to it. * NOTE: Before calling this, make sure all necessary System Clocks are setup * correctly. Generally this means making sure the RTC has access to a Crystal * for optimal accuracy and operation in low power. * * @param[out] obj RTC object * @return The status of the init request */ cy_rslt_t cyhal_rtc_init(cyhal_rtc_t *obj); /** Deinitialize RTC * * Frees resources associated with the RTC and disables CPU access. This * only affects the CPU domain and not the time keeping logic. * After this function is called no other RTC functions should be called * except for rtc_init. * * @param[in,out] obj RTC object */ void cyhal_rtc_free(cyhal_rtc_t *obj); /** Check if the RTC has the time set and is counting * * @param[in] obj RTC object * @return Whether the RTC is enabled or not */ bool cyhal_rtc_is_enabled(cyhal_rtc_t *obj); /** Get the current time from the RTC peripheral * * @param[in] obj RTC object * @param[out] time The current time (see: https://en.cppreference.com/w/cpp/chrono/c/tm) * @return The status of the read request */ cy_rslt_t cyhal_rtc_read(cyhal_rtc_t *obj, struct tm *time); /** Write the current time in seconds to the RTC peripheral * * @param[in] obj RTC object * @param[in] time The time to be set (see: https://en.cppreference.com/w/cpp/chrono/c/tm) * @return The status of the write request */ cy_rslt_t cyhal_rtc_write(cyhal_rtc_t *obj, const struct tm *time); /** Set an alarm for the specified time in seconds to the RTC peripheral * * @param[in] obj RTC object * @param[in] time The alarm time to be set (see: https://en.cppreference.com/w/cpp/chrono/c/tm) * @param[in] active The set of fields that are checked to trigger the alarm * @return The status of the set_alarm request */ cy_rslt_t cyhal_rtc_set_alarm(cyhal_rtc_t *obj, const struct tm *time, cyhal_alarm_active_t active); /** The RTC event callback handler registration * * @param[in] obj The RTC object * @param[in] callback The callback handler which will be invoked when the alarm fires * @param[in] callback_arg Generic argument that will be provided to the callback when called */ void cyhal_rtc_register_callback(cyhal_rtc_t *obj, cyhal_rtc_event_callback_t callback, void *callback_arg); /** Configure RTC event enablement. * * @param[in] obj The RTC object * @param[in] event The RTC event type * @param[in] intrPriority The priority for NVIC interrupt events * @param[in] enable True to turn on interrupts, False to turn off */ void cyhal_rtc_enable_event(cyhal_rtc_t *obj, cyhal_rtc_event_t event, uint8_t intrPriority, bool enable); #if defined(__cplusplus) } #endif #ifdef CYHAL_RTC_IMPL_HEADER #include CYHAL_RTC_IMPL_HEADER #endif /* CYHAL_RTC_IMPL_HEADER */ /** \} group_hal_rtc */
35.83125
108
0.704343
[ "object" ]
7ff4d140bb24a55a1d5a52fa30c674c3877d3600
1,660
h
C
generated-sources/cpp-restsdk/mojang-sessions/model/PlayerSkinURL.h
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
generated-sources/cpp-restsdk/mojang-sessions/model/PlayerSkinURL.h
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
generated-sources/cpp-restsdk/mojang-sessions/model/PlayerSkinURL.h
AsyncMC/Mojang-API-Libs
b01bbd2bce44bfa2b9ed705a128cf4ecda077916
[ "Apache-2.0" ]
null
null
null
/** * Mojang Session API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2020-06-05 * * NOTE: This class is auto generated by OpenAPI-Generator 3.3.4. * https://openapi-generator.tech * Do not edit the class manually. */ /* * PlayerSkinURL.h * * Wraps the URL to the texture and configures the player&#39;s model */ #ifndef COM_GITHUB_ASYNCMC_MOJANG_SESSIONS_CPP_RESTSDK_MODEL_PlayerSkinURL_H_ #define COM_GITHUB_ASYNCMC_MOJANG_SESSIONS_CPP_RESTSDK_MODEL_PlayerSkinURL_H_ #include <cpprest/details/basic_types.h> #include "PlayerTextureURL.h" namespace com { namespace github { namespace asyncmc { namespace mojang { namespace sessions { namespace cpp { namespace restsdk { namespace model { /// <summary> /// Wraps the URL to the texture and configures the player&#39;s model /// </summary> class PlayerSkinURL : public PlayerTextureURL { public: PlayerSkinURL(); virtual ~PlayerSkinURL(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; void fromJson(const web::json::value& json) override; void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override; ///////////////////////////////////////////// /// PlayerSkinURL members protected: }; } } } } } } } } #endif /* COM_GITHUB_ASYNCMC_MOJANG_SESSIONS_CPP_RESTSDK_MODEL_PlayerSkinURL_H_ */
23.055556
119
0.706024
[ "model" ]
7ff6d3c72233e6ecae04d9fb68d3f319cd869723
7,315
h
C
core/factory/WorkerFactory.h
critical27/aria
c0c7b5981e066e19728996488258ae59f899bf8e
[ "MIT" ]
44
2020-06-28T16:47:04.000Z
2022-03-23T08:51:59.000Z
core/factory/WorkerFactory.h
critical27/aria
c0c7b5981e066e19728996488258ae59f899bf8e
[ "MIT" ]
1
2021-12-27T00:45:04.000Z
2021-12-27T00:45:04.000Z
core/factory/WorkerFactory.h
critical27/aria
c0c7b5981e066e19728996488258ae59f899bf8e
[ "MIT" ]
9
2020-08-24T09:03:29.000Z
2022-03-23T04:09:39.000Z
// // Created by Yi Lu on 9/7/18. // #pragma once #include "core/Defs.h" #include "core/Executor.h" #include "core/Manager.h" #include "benchmark/tpcc/Workload.h" #include "benchmark/ycsb/Workload.h" #include "protocol/TwoPL/TwoPL.h" #include "protocol/TwoPL/TwoPLExecutor.h" #include "protocol/Calvin/Calvin.h" #include "protocol/Calvin/CalvinExecutor.h" #include "protocol/Calvin/CalvinManager.h" #include "protocol/Calvin/CalvinTransaction.h" #include "protocol/Bohm/Bohm.h" #include "protocol/Bohm/BohmExecutor.h" #include "protocol/Bohm/BohmManager.h" #include "protocol/Bohm/BohmTransaction.h" #include "protocol/Aria/Aria.h" #include "protocol/Aria/AriaExecutor.h" #include "protocol/Aria/AriaManager.h" #include "protocol/Aria/AriaTransaction.h" #include "protocol/AriaFB/AriaFB.h" #include "protocol/AriaFB/AriaFBExecutor.h" #include "protocol/AriaFB/AriaFBManager.h" #include "protocol/AriaFB/AriaFBTransaction.h" #include "protocol/Pwv/PwvExecutor.h" #include "protocol/Pwv/PwvManager.h" #include "protocol/Pwv/PwvTransaction.h" #include <unordered_set> namespace aria { template <class Context> class InferType {}; template <> class InferType<aria::tpcc::Context> { public: template <class Transaction> using WorkloadType = aria::tpcc::Workload<Transaction>; }; template <> class InferType<aria::ycsb::Context> { public: template <class Transaction> using WorkloadType = aria::ycsb::Workload<Transaction>; }; class WorkerFactory { public: template <class Database, class Context> static std::vector<std::shared_ptr<Worker>> create_workers(std::size_t coordinator_id, Database &db, const Context &context, std::atomic<bool> &stop_flag) { std::unordered_set<std::string> protocols = { "TwoPL", "Calvin", "Bohm", "Aria", "AriaFB", "Pwv"}; CHECK(protocols.count(context.protocol) == 1); std::vector<std::shared_ptr<Worker>> workers; if (context.protocol == "TwoPL") { using TransactionType = aria::TwoPLTransaction; using WorkloadType = typename InferType<Context>::template WorkloadType<TransactionType>; auto manager = std::make_shared<Manager>( coordinator_id, context.worker_num, context, stop_flag); for (auto i = 0u; i < context.worker_num; i++) { workers.push_back(std::make_shared<TwoPLExecutor<WorkloadType>>( coordinator_id, i, db, context, manager->worker_status, manager->n_completed_workers, manager->n_started_workers)); } workers.push_back(manager); } else if (context.protocol == "Calvin") { using TransactionType = aria::CalvinTransaction; using WorkloadType = typename InferType<Context>::template WorkloadType<TransactionType>; // create manager auto manager = std::make_shared<CalvinManager<WorkloadType>>( coordinator_id, context.worker_num, db, context, stop_flag); // create worker std::vector<CalvinExecutor<WorkloadType> *> all_executors; for (auto i = 0u; i < context.worker_num; i++) { auto w = std::make_shared<CalvinExecutor<WorkloadType>>( coordinator_id, i, db, context, manager->transactions, manager->storages, manager->lock_manager_status, manager->worker_status, manager->n_completed_workers, manager->n_started_workers); workers.push_back(w); manager->add_worker(w); all_executors.push_back(w.get()); } // push manager to workers workers.push_back(manager); for (auto i = 0u; i < context.worker_num; i++) { static_cast<CalvinExecutor<WorkloadType> *>(workers[i].get()) ->set_all_executors(all_executors); } } else if (context.protocol == "Bohm") { using TransactionType = aria::BohmTransaction; using WorkloadType = typename InferType<Context>::template WorkloadType<TransactionType>; // create manager auto manager = std::make_shared<BohmManager<WorkloadType>>( coordinator_id, context.worker_num, db, context, stop_flag); // create worker for (auto i = 0u; i < context.worker_num; i++) { workers.push_back(std::make_shared<BohmExecutor<WorkloadType>>( coordinator_id, i, db, context, manager->transactions, manager->storages, manager->epoch, manager->worker_status, manager->n_completed_workers, manager->n_started_workers)); } workers.push_back(manager); } else if (context.protocol == "Aria") { using TransactionType = aria::AriaTransaction; using WorkloadType = typename InferType<Context>::template WorkloadType<TransactionType>; // create manager auto manager = std::make_shared<AriaManager<WorkloadType>>( coordinator_id, context.worker_num, db, context, stop_flag); // create worker for (auto i = 0u; i < context.worker_num; i++) { workers.push_back(std::make_shared<AriaExecutor<WorkloadType>>( coordinator_id, i, db, context, manager->transactions, manager->storages, manager->epoch, manager->worker_status, manager->total_abort, manager->n_completed_workers, manager->n_started_workers)); } workers.push_back(manager); } else if (context.protocol == "AriaFB") { using TransactionType = aria::AriaFBTransaction; using WorkloadType = typename InferType<Context>::template WorkloadType<TransactionType>; // create manager auto manager = std::make_shared<AriaFBManager<WorkloadType>>( coordinator_id, context.worker_num, db, context, stop_flag); // create worker std::vector<AriaFBExecutor<WorkloadType> *> all_executors; for (auto i = 0u; i < context.worker_num; i++) { auto w = std::make_shared<AriaFBExecutor<WorkloadType>>( coordinator_id, i, db, context, manager->transactions, manager->partition_ids, manager->storages, manager->epoch, manager->lock_manager_status, manager->worker_status, manager->total_abort, manager->n_completed_workers, manager->n_started_workers); workers.push_back(w); manager->add_worker(w); all_executors.push_back(w.get()); } // push manager to workers workers.push_back(manager); for (auto i = 0u; i < context.worker_num; i++) { static_cast<AriaFBExecutor<WorkloadType> *>(workers[i].get()) ->set_all_executors(all_executors); } } else if (context.protocol == "Pwv") { // create manager auto manager = std::make_shared<PwvManager<Database>>( coordinator_id, context.worker_num, db, context, stop_flag); // create worker for (auto i = 0u; i < context.worker_num; i++) { workers.push_back(std::make_shared<PwvExecutor<Database>>( coordinator_id, i, db, context, manager->transactions, manager->storages, manager->epoch, manager->worker_status, manager->n_completed_workers, manager->n_started_workers)); } workers.push_back(manager); } else { CHECK(false) << "protocol: " << context.protocol << " is not supported."; } return workers; } }; } // namespace aria
32.802691
79
0.667806
[ "vector" ]
7ffb2a3a7ba10f1d03f6aa3021986cc58dd5c0c7
219,711
h
C
3rdParty/V8/v5.7.492.77/src/crankshaft/hydrogen-instructions.h
sita1999/arangodb
6a4f462fa209010cd064f99e63d85ce1d432c500
[ "Apache-2.0" ]
22
2016-07-28T03:25:31.000Z
2022-02-19T02:51:14.000Z
3rdParty/V8/v5.7.492.77/src/crankshaft/hydrogen-instructions.h
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
10
2016-09-30T14:57:49.000Z
2017-06-30T12:56:01.000Z
3rdParty/V8/v5.7.492.77/src/crankshaft/hydrogen-instructions.h
lipper/arangodb
66ea1fd4946668192e3f0d1060f0844f324ad7b8
[ "Apache-2.0" ]
23
2016-08-03T17:43:32.000Z
2021-03-04T17:09:00.000Z
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_CRANKSHAFT_HYDROGEN_INSTRUCTIONS_H_ #define V8_CRANKSHAFT_HYDROGEN_INSTRUCTIONS_H_ #include <cstring> #include <iosfwd> #include "src/allocation.h" #include "src/ast/ast.h" #include "src/base/bits.h" #include "src/bit-vector.h" #include "src/conversions.h" #include "src/crankshaft/hydrogen-types.h" #include "src/crankshaft/unique.h" #include "src/deoptimizer.h" #include "src/globals.h" #include "src/interface-descriptors.h" #include "src/small-pointer-list.h" #include "src/utils.h" #include "src/zone/zone.h" namespace v8 { namespace internal { // Forward declarations. struct ChangesOf; class HBasicBlock; class HDiv; class HEnvironment; class HInferRepresentationPhase; class HInstruction; class HLoopInformation; class HStoreNamedField; class HValue; class LInstruction; class LChunkBuilder; class SmallMapList; #define HYDROGEN_ABSTRACT_INSTRUCTION_LIST(V) \ V(ArithmeticBinaryOperation) \ V(BinaryOperation) \ V(BitwiseBinaryOperation) \ V(ControlInstruction) \ V(Instruction) #define HYDROGEN_CONCRETE_INSTRUCTION_LIST(V) \ V(AbnormalExit) \ V(AccessArgumentsAt) \ V(Add) \ V(Allocate) \ V(ApplyArguments) \ V(ArgumentsElements) \ V(ArgumentsLength) \ V(ArgumentsObject) \ V(Bitwise) \ V(BlockEntry) \ V(BoundsCheck) \ V(Branch) \ V(CallWithDescriptor) \ V(CallNewArray) \ V(CallRuntime) \ V(CapturedObject) \ V(Change) \ V(CheckArrayBufferNotNeutered) \ V(CheckHeapObject) \ V(CheckInstanceType) \ V(CheckMaps) \ V(CheckMapValue) \ V(CheckSmi) \ V(CheckValue) \ V(ClampToUint8) \ V(ClassOfTestAndBranch) \ V(CompareNumericAndBranch) \ V(CompareHoleAndBranch) \ V(CompareGeneric) \ V(CompareObjectEqAndBranch) \ V(CompareMap) \ V(Constant) \ V(Context) \ V(DebugBreak) \ V(DeclareGlobals) \ V(Deoptimize) \ V(Div) \ V(DummyUse) \ V(EnterInlined) \ V(EnvironmentMarker) \ V(ForceRepresentation) \ V(ForInCacheArray) \ V(ForInPrepareMap) \ V(Goto) \ V(HasInstanceTypeAndBranch) \ V(InnerAllocatedObject) \ V(InvokeFunction) \ V(HasInPrototypeChainAndBranch) \ V(IsStringAndBranch) \ V(IsSmiAndBranch) \ V(IsUndetectableAndBranch) \ V(LeaveInlined) \ V(LoadContextSlot) \ V(LoadFieldByIndex) \ V(LoadFunctionPrototype) \ V(LoadKeyed) \ V(LoadNamedField) \ V(LoadRoot) \ V(MathFloorOfDiv) \ V(MathMinMax) \ V(MaybeGrowElements) \ V(Mod) \ V(Mul) \ V(OsrEntry) \ V(Parameter) \ V(Power) \ V(Prologue) \ V(PushArguments) \ V(Return) \ V(Ror) \ V(Sar) \ V(SeqStringGetChar) \ V(SeqStringSetChar) \ V(Shl) \ V(Shr) \ V(Simulate) \ V(StackCheck) \ V(StoreCodeEntry) \ V(StoreContextSlot) \ V(StoreKeyed) \ V(StoreNamedField) \ V(StringAdd) \ V(StringCharCodeAt) \ V(StringCharFromCode) \ V(StringCompareAndBranch) \ V(Sub) \ V(ThisFunction) \ V(TransitionElementsKind) \ V(TrapAllocationMemento) \ V(Typeof) \ V(TypeofIsAndBranch) \ V(UnaryMathOperation) \ V(UnknownOSRValue) \ V(UseConst) \ V(WrapReceiver) #define GVN_TRACKED_FLAG_LIST(V) \ V(NewSpacePromotion) #define GVN_UNTRACKED_FLAG_LIST(V) \ V(ArrayElements) \ V(ArrayLengths) \ V(StringLengths) \ V(BackingStoreFields) \ V(Calls) \ V(ContextSlots) \ V(DoubleArrayElements) \ V(DoubleFields) \ V(ElementsKind) \ V(ElementsPointer) \ V(GlobalVars) \ V(InobjectFields) \ V(Maps) \ V(OsrEntries) \ V(ExternalMemory) \ V(StringChars) \ V(TypedArrayElements) #define DECLARE_ABSTRACT_INSTRUCTION(type) \ bool Is##type() const final { return true; } \ static H##type* cast(HValue* value) { \ DCHECK(value->Is##type()); \ return reinterpret_cast<H##type*>(value); \ } #define DECLARE_CONCRETE_INSTRUCTION(type) \ LInstruction* CompileToLithium(LChunkBuilder* builder) final; \ static H##type* cast(HValue* value) { \ DCHECK(value->Is##type()); \ return reinterpret_cast<H##type*>(value); \ } \ Opcode opcode() const final { return HValue::k##type; } enum PropertyAccessType { LOAD, STORE }; Representation RepresentationFromMachineType(MachineType type); class Range final : public ZoneObject { public: Range() : lower_(kMinInt), upper_(kMaxInt), next_(NULL), can_be_minus_zero_(false) { } Range(int32_t lower, int32_t upper) : lower_(lower), upper_(upper), next_(NULL), can_be_minus_zero_(false) { } int32_t upper() const { return upper_; } int32_t lower() const { return lower_; } Range* next() const { return next_; } Range* CopyClearLower(Zone* zone) const { return new(zone) Range(kMinInt, upper_); } Range* CopyClearUpper(Zone* zone) const { return new(zone) Range(lower_, kMaxInt); } Range* Copy(Zone* zone) const { Range* result = new(zone) Range(lower_, upper_); result->set_can_be_minus_zero(CanBeMinusZero()); return result; } int32_t Mask() const; void set_can_be_minus_zero(bool b) { can_be_minus_zero_ = b; } bool CanBeMinusZero() const { return CanBeZero() && can_be_minus_zero_; } bool CanBeZero() const { return upper_ >= 0 && lower_ <= 0; } bool CanBeNegative() const { return lower_ < 0; } bool CanBePositive() const { return upper_ > 0; } bool Includes(int value) const { return lower_ <= value && upper_ >= value; } bool IsMostGeneric() const { return lower_ == kMinInt && upper_ == kMaxInt && CanBeMinusZero(); } bool IsInSmiRange() const { return lower_ >= Smi::kMinValue && upper_ <= Smi::kMaxValue; } void ClampToSmi() { lower_ = Max(lower_, Smi::kMinValue); upper_ = Min(upper_, Smi::kMaxValue); } void Clear(); void KeepOrder(); #ifdef DEBUG void Verify() const; #endif void StackUpon(Range* other) { Intersect(other); next_ = other; } void Intersect(Range* other); void Union(Range* other); void CombinedMax(Range* other); void CombinedMin(Range* other); void AddConstant(int32_t value); void Sar(int32_t value); void Shl(int32_t value); bool AddAndCheckOverflow(const Representation& r, Range* other); bool SubAndCheckOverflow(const Representation& r, Range* other); bool MulAndCheckOverflow(const Representation& r, Range* other); private: int32_t lower_; int32_t upper_; Range* next_; bool can_be_minus_zero_; }; class HUseListNode: public ZoneObject { public: HUseListNode(HValue* value, int index, HUseListNode* tail) : tail_(tail), value_(value), index_(index) { } HUseListNode* tail(); HValue* value() const { return value_; } int index() const { return index_; } void set_tail(HUseListNode* list) { tail_ = list; } #ifdef DEBUG void Zap() { tail_ = reinterpret_cast<HUseListNode*>(1); value_ = NULL; index_ = -1; } #endif private: HUseListNode* tail_; HValue* value_; int index_; }; // We reuse use list nodes behind the scenes as uses are added and deleted. // This class is the safe way to iterate uses while deleting them. class HUseIterator final BASE_EMBEDDED { public: bool Done() { return current_ == NULL; } void Advance(); HValue* value() { DCHECK(!Done()); return value_; } int index() { DCHECK(!Done()); return index_; } private: explicit HUseIterator(HUseListNode* head); HUseListNode* current_; HUseListNode* next_; HValue* value_; int index_; friend class HValue; }; // All tracked flags should appear before untracked ones. enum GVNFlag { // Declare global value numbering flags. #define DECLARE_FLAG(Type) k##Type, GVN_TRACKED_FLAG_LIST(DECLARE_FLAG) GVN_UNTRACKED_FLAG_LIST(DECLARE_FLAG) #undef DECLARE_FLAG #define COUNT_FLAG(Type) + 1 kNumberOfTrackedSideEffects = 0 GVN_TRACKED_FLAG_LIST(COUNT_FLAG), kNumberOfUntrackedSideEffects = 0 GVN_UNTRACKED_FLAG_LIST(COUNT_FLAG), #undef COUNT_FLAG kNumberOfFlags = kNumberOfTrackedSideEffects + kNumberOfUntrackedSideEffects }; static inline GVNFlag GVNFlagFromInt(int i) { DCHECK(i >= 0); DCHECK(i < kNumberOfFlags); return static_cast<GVNFlag>(i); } class DecompositionResult final BASE_EMBEDDED { public: DecompositionResult() : base_(NULL), offset_(0), scale_(0) {} HValue* base() { return base_; } int offset() { return offset_; } int scale() { return scale_; } bool Apply(HValue* other_base, int other_offset, int other_scale = 0) { if (base_ == NULL) { base_ = other_base; offset_ = other_offset; scale_ = other_scale; return true; } else { if (scale_ == 0) { base_ = other_base; offset_ += other_offset; scale_ = other_scale; return true; } else { return false; } } } void SwapValues(HValue** other_base, int* other_offset, int* other_scale) { swap(&base_, other_base); swap(&offset_, other_offset); swap(&scale_, other_scale); } private: template <class T> void swap(T* a, T* b) { T c(*a); *a = *b; *b = c; } HValue* base_; int offset_; int scale_; }; typedef EnumSet<GVNFlag, int32_t> GVNFlagSet; class HValue : public ZoneObject { public: static const int kNoNumber = -1; enum Flag { kFlexibleRepresentation, kCannotBeTagged, // Participate in Global Value Numbering, i.e. elimination of // unnecessary recomputations. If an instruction sets this flag, it must // implement DataEquals(), which will be used to determine if other // occurrences of the instruction are indeed the same. kUseGVN, // Track instructions that are dominating side effects. If an instruction // sets this flag, it must implement HandleSideEffectDominator() and should // indicate which side effects to track by setting GVN flags. kTrackSideEffectDominators, kCanOverflow, kBailoutOnMinusZero, kCanBeDivByZero, kLeftCanBeMinInt, kLeftCanBeNegative, kLeftCanBePositive, kTruncatingToNumber, kIsArguments, kTruncatingToInt32, kAllUsesTruncatingToInt32, kTruncatingToSmi, kAllUsesTruncatingToSmi, // Set after an instruction is killed. kIsDead, // Instructions that are allowed to produce full range unsigned integer // values are marked with kUint32 flag. If arithmetic shift or a load from // EXTERNAL_UINT32_ELEMENTS array is not marked with this flag // it will deoptimize if result does not fit into signed integer range. // HGraph::ComputeSafeUint32Operations is responsible for setting this // flag. kUint32, kHasNoObservableSideEffects, // Indicates an instruction shouldn't be replaced by optimization, this flag // is useful to set in cases where recomputing a value is cheaper than // extending the value's live range and spilling it. kCantBeReplaced, // Indicates the instruction is live during dead code elimination. kIsLive, // HEnvironmentMarkers are deleted before dead code // elimination takes place, so they can repurpose the kIsLive flag: kEndsLiveRange = kIsLive, // TODO(everyone): Don't forget to update this! kLastFlag = kIsLive }; STATIC_ASSERT(kLastFlag < kBitsPerInt); static HValue* cast(HValue* value) { return value; } enum Opcode { // Declare a unique enum value for each hydrogen instruction. #define DECLARE_OPCODE(type) k##type, HYDROGEN_CONCRETE_INSTRUCTION_LIST(DECLARE_OPCODE) kPhi #undef DECLARE_OPCODE }; virtual Opcode opcode() const = 0; // Declare a non-virtual predicates for each concrete HInstruction or HValue. #define DECLARE_PREDICATE(type) \ bool Is##type() const { return opcode() == k##type; } HYDROGEN_CONCRETE_INSTRUCTION_LIST(DECLARE_PREDICATE) #undef DECLARE_PREDICATE bool IsPhi() const { return opcode() == kPhi; } // Declare virtual predicates for abstract HInstruction or HValue #define DECLARE_PREDICATE(type) \ virtual bool Is##type() const { return false; } HYDROGEN_ABSTRACT_INSTRUCTION_LIST(DECLARE_PREDICATE) #undef DECLARE_PREDICATE bool IsBitwiseBinaryShift() { return IsShl() || IsShr() || IsSar(); } explicit HValue(HType type = HType::Tagged()) : block_(NULL), id_(kNoNumber), type_(type), use_list_(NULL), range_(NULL), #ifdef DEBUG range_poisoned_(false), #endif flags_(0) {} virtual ~HValue() {} virtual SourcePosition position() const { return SourcePosition::Unknown(); } HBasicBlock* block() const { return block_; } void SetBlock(HBasicBlock* block); // Note: Never call this method for an unlinked value. Isolate* isolate() const; int id() const { return id_; } void set_id(int id) { id_ = id; } HUseIterator uses() const { return HUseIterator(use_list_); } virtual bool EmitAtUses() { return false; } Representation representation() const { return representation_; } void ChangeRepresentation(Representation r) { DCHECK(CheckFlag(kFlexibleRepresentation)); DCHECK(!CheckFlag(kCannotBeTagged) || !r.IsTagged()); RepresentationChanged(r); representation_ = r; if (r.IsTagged()) { // Tagged is the bottom of the lattice, don't go any further. ClearFlag(kFlexibleRepresentation); } } virtual void AssumeRepresentation(Representation r); virtual Representation KnownOptimalRepresentation() { Representation r = representation(); if (r.IsTagged()) { HType t = type(); if (t.IsSmi()) return Representation::Smi(); if (t.IsHeapNumber()) return Representation::Double(); if (t.IsHeapObject()) return r; return Representation::None(); } return r; } HType type() const { return type_; } void set_type(HType new_type) { DCHECK(new_type.IsSubtypeOf(type_)); type_ = new_type; } // There are HInstructions that do not really change a value, they // only add pieces of information to it (like bounds checks, map checks, // smi checks...). // We call these instructions "informative definitions", or "iDef". // One of the iDef operands is special because it is the value that is // "transferred" to the output, we call it the "redefined operand". // If an HValue is an iDef it must override RedefinedOperandIndex() so that // it does not return kNoRedefinedOperand; static const int kNoRedefinedOperand = -1; virtual int RedefinedOperandIndex() { return kNoRedefinedOperand; } bool IsInformativeDefinition() { return RedefinedOperandIndex() != kNoRedefinedOperand; } HValue* RedefinedOperand() { int index = RedefinedOperandIndex(); return index == kNoRedefinedOperand ? NULL : OperandAt(index); } bool CanReplaceWithDummyUses(); virtual int argument_delta() const { return 0; } // A purely informative definition is an idef that will not emit code and // should therefore be removed from the graph in the RestoreActualValues // phase (so that live ranges will be shorter). virtual bool IsPurelyInformativeDefinition() { return false; } // This method must always return the original HValue SSA definition, // regardless of any chain of iDefs of this value. HValue* ActualValue() { HValue* value = this; int index; while ((index = value->RedefinedOperandIndex()) != kNoRedefinedOperand) { value = value->OperandAt(index); } return value; } bool IsInteger32Constant(); int32_t GetInteger32Constant(); bool EqualsInteger32Constant(int32_t value); bool IsDefinedAfter(HBasicBlock* other) const; // Operands. virtual int OperandCount() const = 0; virtual HValue* OperandAt(int index) const = 0; void SetOperandAt(int index, HValue* value); void DeleteAndReplaceWith(HValue* other); void ReplaceAllUsesWith(HValue* other); bool HasNoUses() const { return use_list_ == NULL; } bool HasOneUse() const { return use_list_ != NULL && use_list_->tail() == NULL; } bool HasMultipleUses() const { return use_list_ != NULL && use_list_->tail() != NULL; } int UseCount() const; // Mark this HValue as dead and to be removed from other HValues' use lists. void Kill(); int flags() const { return flags_; } void SetFlag(Flag f) { flags_ |= (1 << f); } void ClearFlag(Flag f) { flags_ &= ~(1 << f); } bool CheckFlag(Flag f) const { return (flags_ & (1 << f)) != 0; } void CopyFlag(Flag f, HValue* other) { if (other->CheckFlag(f)) SetFlag(f); } // Returns true if the flag specified is set for all uses, false otherwise. bool CheckUsesForFlag(Flag f) const; // Same as before and the first one without the flag is returned in value. bool CheckUsesForFlag(Flag f, HValue** value) const; // Returns true if the flag specified is set for all uses, and this set // of uses is non-empty. bool HasAtLeastOneUseWithFlagAndNoneWithout(Flag f) const; GVNFlagSet ChangesFlags() const { return changes_flags_; } GVNFlagSet DependsOnFlags() const { return depends_on_flags_; } void SetChangesFlag(GVNFlag f) { changes_flags_.Add(f); } void SetDependsOnFlag(GVNFlag f) { depends_on_flags_.Add(f); } void ClearChangesFlag(GVNFlag f) { changes_flags_.Remove(f); } void ClearDependsOnFlag(GVNFlag f) { depends_on_flags_.Remove(f); } bool CheckChangesFlag(GVNFlag f) const { return changes_flags_.Contains(f); } bool CheckDependsOnFlag(GVNFlag f) const { return depends_on_flags_.Contains(f); } void SetAllSideEffects() { changes_flags_.Add(AllSideEffectsFlagSet()); } void ClearAllSideEffects() { changes_flags_.Remove(AllSideEffectsFlagSet()); } bool HasSideEffects() const { return changes_flags_.ContainsAnyOf(AllSideEffectsFlagSet()); } bool HasObservableSideEffects() const { return !CheckFlag(kHasNoObservableSideEffects) && changes_flags_.ContainsAnyOf(AllObservableSideEffectsFlagSet()); } GVNFlagSet SideEffectFlags() const { GVNFlagSet result = ChangesFlags(); result.Intersect(AllSideEffectsFlagSet()); return result; } GVNFlagSet ObservableChangesFlags() const { GVNFlagSet result = ChangesFlags(); result.Intersect(AllObservableSideEffectsFlagSet()); return result; } Range* range() const { DCHECK(!range_poisoned_); return range_; } bool HasRange() const { DCHECK(!range_poisoned_); return range_ != NULL; } #ifdef DEBUG void PoisonRange() { range_poisoned_ = true; } #endif void AddNewRange(Range* r, Zone* zone); void RemoveLastAddedRange(); void ComputeInitialRange(Zone* zone); // Escape analysis helpers. virtual bool HasEscapingOperandAt(int index) { return true; } virtual bool HasOutOfBoundsAccess(int size) { return false; } // Representation helpers. virtual Representation observed_input_representation(int index) { return Representation::None(); } virtual Representation RequiredInputRepresentation(int index) = 0; virtual void InferRepresentation(HInferRepresentationPhase* h_infer); // This gives the instruction an opportunity to replace itself with an // instruction that does the same in some better way. To replace an // instruction with a new one, first add the new instruction to the graph, // then return it. Return NULL to have the instruction deleted. virtual HValue* Canonicalize() { return this; } bool Equals(HValue* other); virtual intptr_t Hashcode(); // Compute unique ids upfront that is safe wrt GC and concurrent compilation. virtual void FinalizeUniqueness() { } // Printing support. virtual std::ostream& PrintTo(std::ostream& os) const = 0; // NOLINT const char* Mnemonic() const; // Type information helpers. bool HasMonomorphicJSObjectType(); // TODO(mstarzinger): For now instructions can override this function to // specify statically known types, once HType can convey more information // it should be based on the HType. virtual Handle<Map> GetMonomorphicJSObjectMap() { return Handle<Map>(); } // Updated the inferred type of this instruction and returns true if // it has changed. bool UpdateInferredType(); virtual HType CalculateInferredType(); // This function must be overridden for instructions which have the // kTrackSideEffectDominators flag set, to track instructions that are // dominating side effects. // It returns true if it removed an instruction which had side effects. virtual bool HandleSideEffectDominator(GVNFlag side_effect, HValue* dominator) { UNREACHABLE(); return false; } // Check if this instruction has some reason that prevents elimination. bool CannotBeEliminated() const { return HasObservableSideEffects() || !IsDeletable(); } #ifdef DEBUG virtual void Verify() = 0; #endif // Returns true conservatively if the program might be able to observe a // ToString() operation on this value. bool ToStringCanBeObserved() const { return ToStringOrToNumberCanBeObserved(); } // Returns true conservatively if the program might be able to observe a // ToNumber() operation on this value. bool ToNumberCanBeObserved() const { return ToStringOrToNumberCanBeObserved(); } MinusZeroMode GetMinusZeroMode() { return CheckFlag(kBailoutOnMinusZero) ? FAIL_ON_MINUS_ZERO : TREAT_MINUS_ZERO_AS_ZERO; } protected: // This function must be overridden for instructions with flag kUseGVN, to // compare the non-Operand parts of the instruction. virtual bool DataEquals(HValue* other) { UNREACHABLE(); return false; } bool ToStringOrToNumberCanBeObserved() const { if (type().IsTaggedPrimitive()) return false; if (type().IsJSReceiver()) return true; return !representation().IsSmiOrInteger32() && !representation().IsDouble(); } virtual Representation RepresentationFromInputs() { return representation(); } virtual Representation RepresentationFromUses(); Representation RepresentationFromUseRequirements(); bool HasNonSmiUse(); virtual void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason); void AddDependantsToWorklist(HInferRepresentationPhase* h_infer); virtual void RepresentationChanged(Representation to) { } virtual Range* InferRange(Zone* zone); virtual void DeleteFromGraph() = 0; virtual void InternalSetOperandAt(int index, HValue* value) = 0; void clear_block() { DCHECK(block_ != NULL); block_ = NULL; } void set_representation(Representation r) { DCHECK(representation_.IsNone() && !r.IsNone()); representation_ = r; } static GVNFlagSet AllFlagSet() { GVNFlagSet result; #define ADD_FLAG(Type) result.Add(k##Type); GVN_TRACKED_FLAG_LIST(ADD_FLAG) GVN_UNTRACKED_FLAG_LIST(ADD_FLAG) #undef ADD_FLAG return result; } // A flag mask to mark an instruction as having arbitrary side effects. static GVNFlagSet AllSideEffectsFlagSet() { GVNFlagSet result = AllFlagSet(); result.Remove(kOsrEntries); return result; } friend std::ostream& operator<<(std::ostream& os, const ChangesOf& v); // A flag mask of all side effects that can make observable changes in // an executing program (i.e. are not safe to repeat, move or remove); static GVNFlagSet AllObservableSideEffectsFlagSet() { GVNFlagSet result = AllFlagSet(); result.Remove(kNewSpacePromotion); result.Remove(kElementsKind); result.Remove(kElementsPointer); result.Remove(kMaps); return result; } // Remove the matching use from the use list if present. Returns the // removed list node or NULL. HUseListNode* RemoveUse(HValue* value, int index); void RegisterUse(int index, HValue* new_value); HBasicBlock* block_; // The id of this instruction in the hydrogen graph, assigned when first // added to the graph. Reflects creation order. int id_; Representation representation_; HType type_; HUseListNode* use_list_; Range* range_; #ifdef DEBUG bool range_poisoned_; #endif int flags_; GVNFlagSet changes_flags_; GVNFlagSet depends_on_flags_; private: virtual bool IsDeletable() const { return false; } DISALLOW_COPY_AND_ASSIGN(HValue); }; // Support for printing various aspects of an HValue. struct NameOf { explicit NameOf(const HValue* const v) : value(v) {} const HValue* value; }; struct TypeOf { explicit TypeOf(const HValue* const v) : value(v) {} const HValue* value; }; struct ChangesOf { explicit ChangesOf(const HValue* const v) : value(v) {} const HValue* value; }; std::ostream& operator<<(std::ostream& os, const HValue& v); std::ostream& operator<<(std::ostream& os, const NameOf& v); std::ostream& operator<<(std::ostream& os, const TypeOf& v); std::ostream& operator<<(std::ostream& os, const ChangesOf& v); #define DECLARE_INSTRUCTION_FACTORY_P0(I) \ static I* New(Isolate* isolate, Zone* zone, HValue* context) { \ return new (zone) I(); \ } #define DECLARE_INSTRUCTION_FACTORY_P1(I, P1) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1) { \ return new (zone) I(p1); \ } #define DECLARE_INSTRUCTION_FACTORY_P2(I, P1, P2) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2) { \ return new (zone) I(p1, p2); \ } #define DECLARE_INSTRUCTION_FACTORY_P3(I, P1, P2, P3) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2, \ P3 p3) { \ return new (zone) I(p1, p2, p3); \ } #define DECLARE_INSTRUCTION_FACTORY_P4(I, P1, P2, P3, P4) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2, \ P3 p3, P4 p4) { \ return new (zone) I(p1, p2, p3, p4); \ } #define DECLARE_INSTRUCTION_FACTORY_P5(I, P1, P2, P3, P4, P5) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2, \ P3 p3, P4 p4, P5 p5) { \ return new (zone) I(p1, p2, p3, p4, p5); \ } #define DECLARE_INSTRUCTION_FACTORY_P6(I, P1, P2, P3, P4, P5, P6) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2, \ P3 p3, P4 p4, P5 p5, P6 p6) { \ return new (zone) I(p1, p2, p3, p4, p5, p6); \ } #define DECLARE_INSTRUCTION_FACTORY_P7(I, P1, P2, P3, P4, P5, P6, P7) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2, \ P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) { \ return new (zone) I(p1, p2, p3, p4, p5, p6, p7); \ } #define DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P0(I) \ static I* New(Isolate* isolate, Zone* zone, HValue* context) { \ return new (zone) I(context); \ } #define DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P1(I, P1) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1) { \ return new (zone) I(context, p1); \ } #define DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P2(I, P1, P2) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2) { \ return new (zone) I(context, p1, p2); \ } #define DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P3(I, P1, P2, P3) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2, \ P3 p3) { \ return new (zone) I(context, p1, p2, p3); \ } #define DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P4(I, P1, P2, P3, P4) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2, \ P3 p3, P4 p4) { \ return new (zone) I(context, p1, p2, p3, p4); \ } #define DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P5(I, P1, P2, P3, P4, P5) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2, \ P3 p3, P4 p4, P5 p5) { \ return new (zone) I(context, p1, p2, p3, p4, p5); \ } #define DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P6(I, P1, P2, P3, P4, P5, P6) \ static I* New(Isolate* isolate, Zone* zone, HValue* context, P1 p1, P2 p2, \ P3 p3, P4 p4, P5 p5, P6 p6) { \ return new (zone) I(context, p1, p2, p3, p4, p5, p6); \ } class HInstruction : public HValue { public: HInstruction* next() const { return next_; } HInstruction* previous() const { return previous_; } std::ostream& PrintTo(std::ostream& os) const override; // NOLINT virtual std::ostream& PrintDataTo(std::ostream& os) const; // NOLINT bool IsLinked() const { return block() != NULL; } void Unlink(); void InsertBefore(HInstruction* next); template<class T> T* Prepend(T* instr) { instr->InsertBefore(this); return instr; } void InsertAfter(HInstruction* previous); template<class T> T* Append(T* instr) { instr->InsertAfter(this); return instr; } // The position is a write-once variable. SourcePosition position() const override { return position_; } bool has_position() const { return position_.IsKnown(); } void set_position(SourcePosition position) { DCHECK(position.IsKnown()); position_ = position; } bool Dominates(HInstruction* other); bool CanTruncateToSmi() const { return CheckFlag(kTruncatingToSmi); } bool CanTruncateToInt32() const { return CheckFlag(kTruncatingToInt32); } bool CanTruncateToNumber() const { return CheckFlag(kTruncatingToNumber); } virtual LInstruction* CompileToLithium(LChunkBuilder* builder) = 0; #ifdef DEBUG void Verify() override; #endif bool CanDeoptimize(); virtual bool HasStackCheck() { return false; } DECLARE_ABSTRACT_INSTRUCTION(Instruction) protected: explicit HInstruction(HType type = HType::Tagged()) : HValue(type), next_(NULL), previous_(NULL), position_(SourcePosition::Unknown()) { SetDependsOnFlag(kOsrEntries); } void DeleteFromGraph() override { Unlink(); } private: void InitializeAsFirst(HBasicBlock* block) { DCHECK(!IsLinked()); SetBlock(block); } HInstruction* next_; HInstruction* previous_; SourcePosition position_; friend class HBasicBlock; }; template<int V> class HTemplateInstruction : public HInstruction { public: int OperandCount() const final { return V; } HValue* OperandAt(int i) const final { return inputs_[i]; } protected: explicit HTemplateInstruction(HType type = HType::Tagged()) : HInstruction(type) {} void InternalSetOperandAt(int i, HValue* value) final { inputs_[i] = value; } private: EmbeddedContainer<HValue*, V> inputs_; }; class HControlInstruction : public HInstruction { public: virtual HBasicBlock* SuccessorAt(int i) const = 0; virtual int SuccessorCount() const = 0; virtual void SetSuccessorAt(int i, HBasicBlock* block) = 0; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT virtual bool KnownSuccessorBlock(HBasicBlock** block) { *block = NULL; return false; } HBasicBlock* FirstSuccessor() { return SuccessorCount() > 0 ? SuccessorAt(0) : NULL; } HBasicBlock* SecondSuccessor() { return SuccessorCount() > 1 ? SuccessorAt(1) : NULL; } void Not() { HBasicBlock* swap = SuccessorAt(0); SetSuccessorAt(0, SuccessorAt(1)); SetSuccessorAt(1, swap); } DECLARE_ABSTRACT_INSTRUCTION(ControlInstruction) }; class HSuccessorIterator final BASE_EMBEDDED { public: explicit HSuccessorIterator(const HControlInstruction* instr) : instr_(instr), current_(0) {} bool Done() { return current_ >= instr_->SuccessorCount(); } HBasicBlock* Current() { return instr_->SuccessorAt(current_); } void Advance() { current_++; } private: const HControlInstruction* instr_; int current_; }; template<int S, int V> class HTemplateControlInstruction : public HControlInstruction { public: int SuccessorCount() const override { return S; } HBasicBlock* SuccessorAt(int i) const override { return successors_[i]; } void SetSuccessorAt(int i, HBasicBlock* block) override { successors_[i] = block; } int OperandCount() const override { return V; } HValue* OperandAt(int i) const override { return inputs_[i]; } protected: void InternalSetOperandAt(int i, HValue* value) override { inputs_[i] = value; } private: EmbeddedContainer<HBasicBlock*, S> successors_; EmbeddedContainer<HValue*, V> inputs_; }; class HBlockEntry final : public HTemplateInstruction<0> { public: Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DECLARE_CONCRETE_INSTRUCTION(BlockEntry) }; class HDummyUse final : public HTemplateInstruction<1> { public: explicit HDummyUse(HValue* value) : HTemplateInstruction<1>(HType::Smi()) { SetOperandAt(0, value); // Pretend to be a Smi so that the HChange instructions inserted // before any use generate as little code as possible. set_representation(Representation::Tagged()); } HValue* value() const { return OperandAt(0); } bool HasEscapingOperandAt(int index) override { return false; } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(DummyUse); }; // Inserts an int3/stop break instruction for debugging purposes. class HDebugBreak final : public HTemplateInstruction<0> { public: DECLARE_INSTRUCTION_FACTORY_P0(HDebugBreak); Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DECLARE_CONCRETE_INSTRUCTION(DebugBreak) }; class HPrologue final : public HTemplateInstruction<0> { public: static HPrologue* New(Zone* zone) { return new (zone) HPrologue(); } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DECLARE_CONCRETE_INSTRUCTION(Prologue) }; class HGoto final : public HTemplateControlInstruction<1, 0> { public: explicit HGoto(HBasicBlock* target) { SetSuccessorAt(0, target); } bool KnownSuccessorBlock(HBasicBlock** block) override { *block = FirstSuccessor(); return true; } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(Goto) }; class HDeoptimize final : public HTemplateControlInstruction<1, 0> { public: static HDeoptimize* New(Isolate* isolate, Zone* zone, HValue* context, DeoptimizeReason reason, Deoptimizer::BailoutType type, HBasicBlock* unreachable_continuation) { return new(zone) HDeoptimize(reason, type, unreachable_continuation); } bool KnownSuccessorBlock(HBasicBlock** block) override { *block = NULL; return true; } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DeoptimizeReason reason() const { return reason_; } Deoptimizer::BailoutType type() { return type_; } DECLARE_CONCRETE_INSTRUCTION(Deoptimize) private: explicit HDeoptimize(DeoptimizeReason reason, Deoptimizer::BailoutType type, HBasicBlock* unreachable_continuation) : reason_(reason), type_(type) { SetSuccessorAt(0, unreachable_continuation); } DeoptimizeReason reason_; Deoptimizer::BailoutType type_; }; class HUnaryControlInstruction : public HTemplateControlInstruction<2, 1> { public: HUnaryControlInstruction(HValue* value, HBasicBlock* true_target, HBasicBlock* false_target) { SetOperandAt(0, value); SetSuccessorAt(0, true_target); SetSuccessorAt(1, false_target); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HValue* value() const { return OperandAt(0); } }; class HBranch final : public HUnaryControlInstruction { public: DECLARE_INSTRUCTION_FACTORY_P1(HBranch, HValue*); DECLARE_INSTRUCTION_FACTORY_P2(HBranch, HValue*, ToBooleanHints); DECLARE_INSTRUCTION_FACTORY_P4(HBranch, HValue*, ToBooleanHints, HBasicBlock*, HBasicBlock*); Representation RequiredInputRepresentation(int index) override { return Representation::None(); } Representation observed_input_representation(int index) override; bool KnownSuccessorBlock(HBasicBlock** block) override; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT ToBooleanHints expected_input_types() const { return expected_input_types_; } DECLARE_CONCRETE_INSTRUCTION(Branch) private: HBranch(HValue* value, ToBooleanHints expected_input_types = ToBooleanHint::kNone, HBasicBlock* true_target = NULL, HBasicBlock* false_target = NULL) : HUnaryControlInstruction(value, true_target, false_target), expected_input_types_(expected_input_types) {} ToBooleanHints expected_input_types_; }; class HCompareMap final : public HUnaryControlInstruction { public: DECLARE_INSTRUCTION_FACTORY_P2(HCompareMap, HValue*, Handle<Map>); DECLARE_INSTRUCTION_FACTORY_P4(HCompareMap, HValue*, Handle<Map>, HBasicBlock*, HBasicBlock*); bool KnownSuccessorBlock(HBasicBlock** block) override { if (known_successor_index() != kNoKnownSuccessorIndex) { *block = SuccessorAt(known_successor_index()); return true; } *block = NULL; return false; } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT static const int kNoKnownSuccessorIndex = -1; int known_successor_index() const { return KnownSuccessorIndexField::decode(bit_field_) - kInternalKnownSuccessorOffset; } void set_known_successor_index(int index) { DCHECK(index >= 0 - kInternalKnownSuccessorOffset); bit_field_ = KnownSuccessorIndexField::update( bit_field_, index + kInternalKnownSuccessorOffset); } Unique<Map> map() const { return map_; } bool map_is_stable() const { return MapIsStableField::decode(bit_field_); } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(CompareMap) protected: int RedefinedOperandIndex() override { return 0; } private: HCompareMap(HValue* value, Handle<Map> map, HBasicBlock* true_target = NULL, HBasicBlock* false_target = NULL) : HUnaryControlInstruction(value, true_target, false_target), bit_field_(KnownSuccessorIndexField::encode( kNoKnownSuccessorIndex + kInternalKnownSuccessorOffset) | MapIsStableField::encode(map->is_stable())), map_(Unique<Map>::CreateImmovable(map)) { set_representation(Representation::Tagged()); } // BitFields can only store unsigned values, so use an offset. // Adding kInternalKnownSuccessorOffset must yield an unsigned value. static const int kInternalKnownSuccessorOffset = 1; STATIC_ASSERT(kNoKnownSuccessorIndex + kInternalKnownSuccessorOffset >= 0); class KnownSuccessorIndexField : public BitField<int, 0, 31> {}; class MapIsStableField : public BitField<bool, 31, 1> {}; uint32_t bit_field_; Unique<Map> map_; }; class HContext final : public HTemplateInstruction<0> { public: static HContext* New(Zone* zone) { return new(zone) HContext(); } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DECLARE_CONCRETE_INSTRUCTION(Context) protected: bool DataEquals(HValue* other) override { return true; } private: HContext() { set_representation(Representation::Tagged()); SetFlag(kUseGVN); } bool IsDeletable() const override { return true; } }; class HReturn final : public HTemplateControlInstruction<0, 3> { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P2(HReturn, HValue*, HValue*); DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P1(HReturn, HValue*); Representation RequiredInputRepresentation(int index) override { // TODO(titzer): require an Int32 input for faster returns. if (index == 2) return Representation::Smi(); return Representation::Tagged(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HValue* value() const { return OperandAt(0); } HValue* context() const { return OperandAt(1); } HValue* parameter_count() const { return OperandAt(2); } DECLARE_CONCRETE_INSTRUCTION(Return) private: HReturn(HValue* context, HValue* value, HValue* parameter_count = 0) { SetOperandAt(0, value); SetOperandAt(1, context); SetOperandAt(2, parameter_count); } }; class HAbnormalExit final : public HTemplateControlInstruction<0, 0> { public: DECLARE_INSTRUCTION_FACTORY_P0(HAbnormalExit); Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DECLARE_CONCRETE_INSTRUCTION(AbnormalExit) private: HAbnormalExit() {} }; class HUnaryOperation : public HTemplateInstruction<1> { public: explicit HUnaryOperation(HValue* value, HType type = HType::Tagged()) : HTemplateInstruction<1>(type) { SetOperandAt(0, value); } static HUnaryOperation* cast(HValue* value) { return reinterpret_cast<HUnaryOperation*>(value); } HValue* value() const { return OperandAt(0); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT }; class HUseConst final : public HUnaryOperation { public: DECLARE_INSTRUCTION_FACTORY_P1(HUseConst, HValue*); Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DECLARE_CONCRETE_INSTRUCTION(UseConst) private: explicit HUseConst(HValue* old_value) : HUnaryOperation(old_value) { } }; class HForceRepresentation final : public HTemplateInstruction<1> { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* value, Representation required_representation); HValue* value() const { return OperandAt(0); } Representation observed_input_representation(int index) override { // We haven't actually *observed* this, but it's closer to the truth // than 'None'. return representation(); // Same as the output representation. } Representation RequiredInputRepresentation(int index) override { return representation(); // Same as the output representation. } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(ForceRepresentation) private: HForceRepresentation(HValue* value, Representation required_representation) { SetOperandAt(0, value); set_representation(required_representation); } }; class HChange final : public HUnaryOperation { public: HChange(HValue* value, Representation to, bool is_truncating_to_smi, bool is_truncating_to_int32, bool is_truncating_to_number) : HUnaryOperation(value) { DCHECK(!value->representation().IsNone()); DCHECK(!to.IsNone()); DCHECK(!value->representation().Equals(to)); set_representation(to); SetFlag(kUseGVN); SetFlag(kCanOverflow); if (is_truncating_to_smi && to.IsSmi()) { SetFlag(kTruncatingToSmi); SetFlag(kTruncatingToInt32); SetFlag(kTruncatingToNumber); } else if (is_truncating_to_int32) { SetFlag(kTruncatingToInt32); SetFlag(kTruncatingToNumber); } else if (is_truncating_to_number) { SetFlag(kTruncatingToNumber); } if (value->representation().IsSmi() || value->type().IsSmi()) { set_type(HType::Smi()); } else { set_type(HType::TaggedNumber()); if (to.IsTagged()) SetChangesFlag(kNewSpacePromotion); } } HType CalculateInferredType() override; HValue* Canonicalize() override; Representation from() const { return value()->representation(); } Representation to() const { return representation(); } bool deoptimize_on_minus_zero() const { return CheckFlag(kBailoutOnMinusZero); } Representation RequiredInputRepresentation(int index) override { return from(); } Range* InferRange(Zone* zone) override; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(Change) protected: bool DataEquals(HValue* other) override { return true; } private: bool IsDeletable() const override { return !from().IsTagged() || value()->type().IsSmi(); } }; class HClampToUint8 final : public HUnaryOperation { public: DECLARE_INSTRUCTION_FACTORY_P1(HClampToUint8, HValue*); Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DECLARE_CONCRETE_INSTRUCTION(ClampToUint8) protected: bool DataEquals(HValue* other) override { return true; } private: explicit HClampToUint8(HValue* value) : HUnaryOperation(value) { set_representation(Representation::Integer32()); SetFlag(kTruncatingToNumber); SetFlag(kUseGVN); } bool IsDeletable() const override { return true; } }; enum RemovableSimulate { REMOVABLE_SIMULATE, FIXED_SIMULATE }; class HSimulate final : public HInstruction { public: HSimulate(BailoutId ast_id, int pop_count, Zone* zone, RemovableSimulate removable) : ast_id_(ast_id), pop_count_(pop_count), values_(2, zone), assigned_indexes_(2, zone), zone_(zone), bit_field_(RemovableField::encode(removable) | DoneWithReplayField::encode(false)) {} ~HSimulate() {} std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT bool HasAstId() const { return !ast_id_.IsNone(); } BailoutId ast_id() const { return ast_id_; } void set_ast_id(BailoutId id) { DCHECK(!HasAstId()); ast_id_ = id; } int pop_count() const { return pop_count_; } const ZoneList<HValue*>* values() const { return &values_; } int GetAssignedIndexAt(int index) const { DCHECK(HasAssignedIndexAt(index)); return assigned_indexes_[index]; } bool HasAssignedIndexAt(int index) const { return assigned_indexes_[index] != kNoIndex; } void AddAssignedValue(int index, HValue* value) { AddValue(index, value); } void AddPushedValue(HValue* value) { AddValue(kNoIndex, value); } int ToOperandIndex(int environment_index) { for (int i = 0; i < assigned_indexes_.length(); ++i) { if (assigned_indexes_[i] == environment_index) return i; } return -1; } int OperandCount() const override { return values_.length(); } HValue* OperandAt(int index) const override { return values_[index]; } bool HasEscapingOperandAt(int index) override { return false; } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } void MergeWith(ZoneList<HSimulate*>* list); bool is_candidate_for_removal() { return RemovableField::decode(bit_field_) == REMOVABLE_SIMULATE; } // Replay effects of this instruction on the given environment. void ReplayEnvironment(HEnvironment* env); DECLARE_CONCRETE_INSTRUCTION(Simulate) #ifdef DEBUG void Verify() override; void set_closure(Handle<JSFunction> closure) { closure_ = closure; } Handle<JSFunction> closure() const { return closure_; } #endif protected: void InternalSetOperandAt(int index, HValue* value) override { values_[index] = value; } private: static const int kNoIndex = -1; void AddValue(int index, HValue* value) { assigned_indexes_.Add(index, zone_); // Resize the list of pushed values. values_.Add(NULL, zone_); // Set the operand through the base method in HValue to make sure that the // use lists are correctly updated. SetOperandAt(values_.length() - 1, value); } bool HasValueForIndex(int index) { for (int i = 0; i < assigned_indexes_.length(); ++i) { if (assigned_indexes_[i] == index) return true; } return false; } bool is_done_with_replay() const { return DoneWithReplayField::decode(bit_field_); } void set_done_with_replay() { bit_field_ = DoneWithReplayField::update(bit_field_, true); } class RemovableField : public BitField<RemovableSimulate, 0, 1> {}; class DoneWithReplayField : public BitField<bool, 1, 1> {}; BailoutId ast_id_; int pop_count_; ZoneList<HValue*> values_; ZoneList<int> assigned_indexes_; Zone* zone_; uint32_t bit_field_; #ifdef DEBUG Handle<JSFunction> closure_; #endif }; class HEnvironmentMarker final : public HTemplateInstruction<1> { public: enum Kind { BIND, LOOKUP }; DECLARE_INSTRUCTION_FACTORY_P2(HEnvironmentMarker, Kind, int); Kind kind() const { return kind_; } int index() const { return index_; } HSimulate* next_simulate() { return next_simulate_; } void set_next_simulate(HSimulate* simulate) { next_simulate_ = simulate; } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT #ifdef DEBUG void set_closure(Handle<JSFunction> closure) { DCHECK(closure_.is_null()); DCHECK(!closure.is_null()); closure_ = closure; } Handle<JSFunction> closure() const { return closure_; } #endif DECLARE_CONCRETE_INSTRUCTION(EnvironmentMarker); private: HEnvironmentMarker(Kind kind, int index) : kind_(kind), index_(index), next_simulate_(NULL) { } Kind kind_; int index_; HSimulate* next_simulate_; #ifdef DEBUG Handle<JSFunction> closure_; #endif }; class HStackCheck final : public HTemplateInstruction<1> { public: enum Type { kFunctionEntry, kBackwardsBranch }; DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P1(HStackCheck, Type); HValue* context() { return OperandAt(0); } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } void Eliminate() { // The stack check eliminator might try to eliminate the same stack // check instruction multiple times. if (IsLinked()) { DeleteAndReplaceWith(NULL); } } bool is_function_entry() { return type_ == kFunctionEntry; } bool is_backwards_branch() { return type_ == kBackwardsBranch; } DECLARE_CONCRETE_INSTRUCTION(StackCheck) private: HStackCheck(HValue* context, Type type) : type_(type) { SetOperandAt(0, context); SetChangesFlag(kNewSpacePromotion); } Type type_; }; enum InliningKind { NORMAL_RETURN, // Drop the function from the environment on return. CONSTRUCT_CALL_RETURN, // Either use allocated receiver or return value. GETTER_CALL_RETURN, // Returning from a getter, need to restore context. SETTER_CALL_RETURN // Use the RHS of the assignment as the return value. }; class HArgumentsObject; class HConstant; class HEnterInlined final : public HTemplateInstruction<0> { public: static HEnterInlined* New(Isolate* isolate, Zone* zone, HValue* context, BailoutId return_id, Handle<JSFunction> closure, HConstant* closure_context, int arguments_count, FunctionLiteral* function, InliningKind inlining_kind, Variable* arguments_var, HArgumentsObject* arguments_object, TailCallMode syntactic_tail_call_mode) { return new (zone) HEnterInlined(return_id, closure, closure_context, arguments_count, function, inlining_kind, arguments_var, arguments_object, syntactic_tail_call_mode, zone); } void RegisterReturnTarget(HBasicBlock* return_target, Zone* zone); ZoneList<HBasicBlock*>* return_targets() { return &return_targets_; } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Handle<SharedFunctionInfo> shared() const { return shared_; } Handle<JSFunction> closure() const { return closure_; } HConstant* closure_context() const { return closure_context_; } int arguments_count() const { return arguments_count_; } bool arguments_pushed() const { return arguments_pushed_; } void set_arguments_pushed() { arguments_pushed_ = true; } FunctionLiteral* function() const { return function_; } InliningKind inlining_kind() const { return inlining_kind_; } TailCallMode syntactic_tail_call_mode() const { return syntactic_tail_call_mode_; } BailoutId ReturnId() const { return return_id_; } int inlining_id() const { return inlining_id_; } void set_inlining_id(int inlining_id) { inlining_id_ = inlining_id; } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } Variable* arguments_var() { return arguments_var_; } HArgumentsObject* arguments_object() { return arguments_object_; } DECLARE_CONCRETE_INSTRUCTION(EnterInlined) private: HEnterInlined(BailoutId return_id, Handle<JSFunction> closure, HConstant* closure_context, int arguments_count, FunctionLiteral* function, InliningKind inlining_kind, Variable* arguments_var, HArgumentsObject* arguments_object, TailCallMode syntactic_tail_call_mode, Zone* zone) : return_id_(return_id), shared_(handle(closure->shared())), closure_(closure), closure_context_(closure_context), arguments_count_(arguments_count), arguments_pushed_(false), function_(function), inlining_kind_(inlining_kind), syntactic_tail_call_mode_(syntactic_tail_call_mode), inlining_id_(-1), arguments_var_(arguments_var), arguments_object_(arguments_object), return_targets_(2, zone) {} BailoutId return_id_; Handle<SharedFunctionInfo> shared_; Handle<JSFunction> closure_; HConstant* closure_context_; int arguments_count_; bool arguments_pushed_; FunctionLiteral* function_; InliningKind inlining_kind_; TailCallMode syntactic_tail_call_mode_; int inlining_id_; Variable* arguments_var_; HArgumentsObject* arguments_object_; ZoneList<HBasicBlock*> return_targets_; }; class HLeaveInlined final : public HTemplateInstruction<0> { public: HLeaveInlined(HEnterInlined* entry, int drop_count) : entry_(entry), drop_count_(drop_count) { } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } int argument_delta() const override { return entry_->arguments_pushed() ? -drop_count_ : 0; } DECLARE_CONCRETE_INSTRUCTION(LeaveInlined) private: HEnterInlined* entry_; int drop_count_; }; class HPushArguments final : public HInstruction { public: static HPushArguments* New(Isolate* isolate, Zone* zone, HValue* context) { return new(zone) HPushArguments(zone); } static HPushArguments* New(Isolate* isolate, Zone* zone, HValue* context, HValue* arg1) { HPushArguments* instr = new(zone) HPushArguments(zone); instr->AddInput(arg1); return instr; } static HPushArguments* New(Isolate* isolate, Zone* zone, HValue* context, HValue* arg1, HValue* arg2) { HPushArguments* instr = new(zone) HPushArguments(zone); instr->AddInput(arg1); instr->AddInput(arg2); return instr; } static HPushArguments* New(Isolate* isolate, Zone* zone, HValue* context, HValue* arg1, HValue* arg2, HValue* arg3) { HPushArguments* instr = new(zone) HPushArguments(zone); instr->AddInput(arg1); instr->AddInput(arg2); instr->AddInput(arg3); return instr; } static HPushArguments* New(Isolate* isolate, Zone* zone, HValue* context, HValue* arg1, HValue* arg2, HValue* arg3, HValue* arg4) { HPushArguments* instr = new(zone) HPushArguments(zone); instr->AddInput(arg1); instr->AddInput(arg2); instr->AddInput(arg3); instr->AddInput(arg4); return instr; } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } int argument_delta() const override { return inputs_.length(); } HValue* argument(int i) { return OperandAt(i); } int OperandCount() const final { return inputs_.length(); } HValue* OperandAt(int i) const final { return inputs_[i]; } void AddInput(HValue* value); DECLARE_CONCRETE_INSTRUCTION(PushArguments) protected: void InternalSetOperandAt(int i, HValue* value) final { inputs_[i] = value; } private: explicit HPushArguments(Zone* zone) : HInstruction(HType::Tagged()), inputs_(4, zone) { set_representation(Representation::Tagged()); } ZoneList<HValue*> inputs_; }; class HThisFunction final : public HTemplateInstruction<0> { public: DECLARE_INSTRUCTION_FACTORY_P0(HThisFunction); Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DECLARE_CONCRETE_INSTRUCTION(ThisFunction) protected: bool DataEquals(HValue* other) override { return true; } private: HThisFunction() { set_representation(Representation::Tagged()); SetFlag(kUseGVN); } bool IsDeletable() const override { return true; } }; class HDeclareGlobals final : public HUnaryOperation { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P3(HDeclareGlobals, Handle<FixedArray>, int, Handle<TypeFeedbackVector>); HValue* context() { return OperandAt(0); } Handle<FixedArray> declarations() const { return declarations_; } int flags() const { return flags_; } Handle<TypeFeedbackVector> feedback_vector() const { return feedback_vector_; } DECLARE_CONCRETE_INSTRUCTION(DeclareGlobals) Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } private: HDeclareGlobals(HValue* context, Handle<FixedArray> declarations, int flags, Handle<TypeFeedbackVector> feedback_vector) : HUnaryOperation(context), declarations_(declarations), feedback_vector_(feedback_vector), flags_(flags) { set_representation(Representation::Tagged()); SetAllSideEffects(); } Handle<FixedArray> declarations_; Handle<TypeFeedbackVector> feedback_vector_; int flags_; }; template <int V> class HCall : public HTemplateInstruction<V> { public: // The argument count includes the receiver. explicit HCall<V>(int argument_count) : argument_count_(argument_count) { this->set_representation(Representation::Tagged()); this->SetAllSideEffects(); } virtual int argument_count() const { return argument_count_; } int argument_delta() const override { return -argument_count(); } private: int argument_count_; }; class HUnaryCall : public HCall<1> { public: HUnaryCall(HValue* value, int argument_count) : HCall<1>(argument_count) { SetOperandAt(0, value); } Representation RequiredInputRepresentation(int index) final { return Representation::Tagged(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HValue* value() const { return OperandAt(0); } }; class HBinaryCall : public HCall<2> { public: HBinaryCall(HValue* first, HValue* second, int argument_count) : HCall<2>(argument_count) { SetOperandAt(0, first); SetOperandAt(1, second); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) final { return Representation::Tagged(); } HValue* first() const { return OperandAt(0); } HValue* second() const { return OperandAt(1); } }; class HCallWithDescriptor final : public HInstruction { public: static HCallWithDescriptor* New( Isolate* isolate, Zone* zone, HValue* context, HValue* target, int argument_count, CallInterfaceDescriptor descriptor, const Vector<HValue*>& operands, TailCallMode syntactic_tail_call_mode = TailCallMode::kDisallow, TailCallMode tail_call_mode = TailCallMode::kDisallow) { HCallWithDescriptor* res = new (zone) HCallWithDescriptor( Code::STUB, context, target, argument_count, descriptor, operands, syntactic_tail_call_mode, tail_call_mode, zone); return res; } static HCallWithDescriptor* New( Isolate* isolate, Zone* zone, HValue* context, Code::Kind kind, HValue* target, int argument_count, CallInterfaceDescriptor descriptor, const Vector<HValue*>& operands, TailCallMode syntactic_tail_call_mode = TailCallMode::kDisallow, TailCallMode tail_call_mode = TailCallMode::kDisallow) { HCallWithDescriptor* res = new (zone) HCallWithDescriptor( kind, context, target, argument_count, descriptor, operands, syntactic_tail_call_mode, tail_call_mode, zone); return res; } int OperandCount() const final { return values_.length(); } HValue* OperandAt(int index) const final { return values_[index]; } Representation RequiredInputRepresentation(int index) final { if (index == 0 || index == 1) { // Target + context return Representation::Tagged(); } else { int par_index = index - 2; DCHECK(par_index < GetParameterCount()); return RepresentationFromMachineType( descriptor_.GetParameterType(par_index)); } } DECLARE_CONCRETE_INSTRUCTION(CallWithDescriptor) // Defines whether this instruction corresponds to a JS call at tail position. TailCallMode syntactic_tail_call_mode() const { return SyntacticTailCallModeField::decode(bit_field_); } // Defines whether this call should be generated as a tail call. TailCallMode tail_call_mode() const { return TailCallModeField::decode(bit_field_); } bool IsTailCall() const { return tail_call_mode() == TailCallMode::kAllow; } Code::Kind kind() const { return KindField::decode(bit_field_); } virtual int argument_count() const { return argument_count_; } int argument_delta() const override { return -argument_count_; } CallInterfaceDescriptor descriptor() const { return descriptor_; } HValue* target() { return OperandAt(0); } HValue* context() { return OperandAt(1); } HValue* parameter(int index) { DCHECK_LT(index, GetParameterCount()); return OperandAt(index + 2); } HValue* Canonicalize() override; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT private: // The argument count includes the receiver. HCallWithDescriptor(Code::Kind kind, HValue* context, HValue* target, int argument_count, CallInterfaceDescriptor descriptor, const Vector<HValue*>& operands, TailCallMode syntactic_tail_call_mode, TailCallMode tail_call_mode, Zone* zone) : descriptor_(descriptor), values_(GetParameterCount() + 2, zone), // +2 for context and target. argument_count_(argument_count), bit_field_( TailCallModeField::encode(tail_call_mode) | SyntacticTailCallModeField::encode(syntactic_tail_call_mode) | KindField::encode(kind)) { DCHECK_EQ(operands.length(), GetParameterCount()); // We can only tail call without any stack arguments. DCHECK(tail_call_mode != TailCallMode::kAllow || argument_count == 0); AddOperand(target, zone); AddOperand(context, zone); for (int i = 0; i < operands.length(); i++) { AddOperand(operands[i], zone); } this->set_representation(Representation::Tagged()); this->SetAllSideEffects(); } void AddOperand(HValue* v, Zone* zone) { values_.Add(NULL, zone); SetOperandAt(values_.length() - 1, v); } int GetParameterCount() const { return descriptor_.GetParameterCount(); } void InternalSetOperandAt(int index, HValue* value) final { values_[index] = value; } CallInterfaceDescriptor descriptor_; ZoneList<HValue*> values_; int argument_count_; class TailCallModeField : public BitField<TailCallMode, 0, 1> {}; class SyntacticTailCallModeField : public BitField<TailCallMode, TailCallModeField::kNext, 1> {}; class KindField : public BitField<Code::Kind, SyntacticTailCallModeField::kNext, 5> {}; uint32_t bit_field_; }; class HInvokeFunction final : public HBinaryCall { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P5(HInvokeFunction, HValue*, Handle<JSFunction>, int, TailCallMode, TailCallMode); HValue* context() { return first(); } HValue* function() { return second(); } Handle<JSFunction> known_function() { return known_function_; } int formal_parameter_count() const { return formal_parameter_count_; } bool HasStackCheck() final { return HasStackCheckField::decode(bit_field_); } // Defines whether this instruction corresponds to a JS call at tail position. TailCallMode syntactic_tail_call_mode() const { return SyntacticTailCallModeField::decode(bit_field_); } // Defines whether this call should be generated as a tail call. TailCallMode tail_call_mode() const { return TailCallModeField::decode(bit_field_); } DECLARE_CONCRETE_INSTRUCTION(InvokeFunction) std::ostream& PrintTo(std::ostream& os) const override; // NOLINT std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT private: void set_has_stack_check(bool has_stack_check) { bit_field_ = HasStackCheckField::update(bit_field_, has_stack_check); } HInvokeFunction(HValue* context, HValue* function, Handle<JSFunction> known_function, int argument_count, TailCallMode syntactic_tail_call_mode, TailCallMode tail_call_mode) : HBinaryCall(context, function, argument_count), known_function_(known_function), bit_field_( TailCallModeField::encode(tail_call_mode) | SyntacticTailCallModeField::encode(syntactic_tail_call_mode)) { DCHECK(tail_call_mode != TailCallMode::kAllow || syntactic_tail_call_mode == TailCallMode::kAllow); formal_parameter_count_ = known_function.is_null() ? 0 : known_function->shared()->internal_formal_parameter_count(); set_has_stack_check( !known_function.is_null() && (known_function->code()->kind() == Code::FUNCTION || known_function->code()->kind() == Code::OPTIMIZED_FUNCTION)); } Handle<JSFunction> known_function_; int formal_parameter_count_; class HasStackCheckField : public BitField<bool, 0, 1> {}; class TailCallModeField : public BitField<TailCallMode, HasStackCheckField::kNext, 1> {}; class SyntacticTailCallModeField : public BitField<TailCallMode, TailCallModeField::kNext, 1> {}; uint32_t bit_field_; }; class HCallNewArray final : public HBinaryCall { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P4(HCallNewArray, HValue*, int, ElementsKind, Handle<AllocationSite>); HValue* context() { return first(); } HValue* constructor() { return second(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT ElementsKind elements_kind() const { return elements_kind_; } Handle<AllocationSite> site() const { return site_; } DECLARE_CONCRETE_INSTRUCTION(CallNewArray) private: HCallNewArray(HValue* context, HValue* constructor, int argument_count, ElementsKind elements_kind, Handle<AllocationSite> site) : HBinaryCall(context, constructor, argument_count), elements_kind_(elements_kind), site_(site) {} ElementsKind elements_kind_; Handle<AllocationSite> site_; }; class HCallRuntime final : public HCall<1> { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P2(HCallRuntime, const Runtime::Function*, int); std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HValue* context() { return OperandAt(0); } const Runtime::Function* function() const { return c_function_; } SaveFPRegsMode save_doubles() const { return save_doubles_; } void set_save_doubles(SaveFPRegsMode save_doubles) { save_doubles_ = save_doubles; } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(CallRuntime) private: HCallRuntime(HValue* context, const Runtime::Function* c_function, int argument_count) : HCall<1>(argument_count), c_function_(c_function), save_doubles_(kDontSaveFPRegs) { SetOperandAt(0, context); } const Runtime::Function* c_function_; SaveFPRegsMode save_doubles_; }; class HUnaryMathOperation final : public HTemplateInstruction<2> { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* value, BuiltinFunctionId op); HValue* context() const { return OperandAt(0); } HValue* value() const { return OperandAt(1); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) override { if (index == 0) { return Representation::Tagged(); } else { switch (op_) { case kMathCos: case kMathFloor: case kMathRound: case kMathFround: case kMathSin: case kMathSqrt: case kMathPowHalf: case kMathLog: case kMathExp: return Representation::Double(); case kMathAbs: return representation(); case kMathClz32: return Representation::Integer32(); default: UNREACHABLE(); return Representation::None(); } } } Range* InferRange(Zone* zone) override; HValue* Canonicalize() override; Representation RepresentationFromUses() override; Representation RepresentationFromInputs() override; BuiltinFunctionId op() const { return op_; } const char* OpName() const; DECLARE_CONCRETE_INSTRUCTION(UnaryMathOperation) protected: bool DataEquals(HValue* other) override { HUnaryMathOperation* b = HUnaryMathOperation::cast(other); return op_ == b->op(); } private: // Indicates if we support a double (and int32) output for Math.floor and // Math.round. bool SupportsFlexibleFloorAndRound() const { #if V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_PPC return true; #elif V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X64 return CpuFeatures::IsSupported(SSE4_1); #else return false; #endif } HUnaryMathOperation(HValue* context, HValue* value, BuiltinFunctionId op) : HTemplateInstruction<2>(HType::TaggedNumber()), op_(op) { SetOperandAt(0, context); SetOperandAt(1, value); switch (op) { case kMathFloor: case kMathRound: if (SupportsFlexibleFloorAndRound()) { SetFlag(kFlexibleRepresentation); } else { set_representation(Representation::Integer32()); } break; case kMathClz32: set_representation(Representation::Integer32()); break; case kMathAbs: // Not setting representation here: it is None intentionally. SetFlag(kFlexibleRepresentation); // TODO(svenpanne) This flag is actually only needed if representation() // is tagged, and not when it is an unboxed double or unboxed integer. SetChangesFlag(kNewSpacePromotion); break; case kMathCos: case kMathFround: case kMathLog: case kMathExp: case kMathSin: case kMathSqrt: case kMathPowHalf: set_representation(Representation::Double()); break; default: UNREACHABLE(); } SetFlag(kUseGVN); SetFlag(kTruncatingToNumber); } bool IsDeletable() const override { // TODO(crankshaft): This should be true, however the semantics of this // instruction also include the ToNumber conversion that is mentioned in the // spec, which is of course observable. return false; } HValue* SimplifiedDividendForMathFloorOfDiv(HDiv* hdiv); HValue* SimplifiedDivisorForMathFloorOfDiv(HDiv* hdiv); BuiltinFunctionId op_; }; class HLoadRoot final : public HTemplateInstruction<0> { public: DECLARE_INSTRUCTION_FACTORY_P1(HLoadRoot, Heap::RootListIndex); DECLARE_INSTRUCTION_FACTORY_P2(HLoadRoot, Heap::RootListIndex, HType); Representation RequiredInputRepresentation(int index) override { return Representation::None(); } Heap::RootListIndex index() const { return index_; } DECLARE_CONCRETE_INSTRUCTION(LoadRoot) protected: bool DataEquals(HValue* other) override { HLoadRoot* b = HLoadRoot::cast(other); return index_ == b->index_; } private: explicit HLoadRoot(Heap::RootListIndex index, HType type = HType::Tagged()) : HTemplateInstruction<0>(type), index_(index) { SetFlag(kUseGVN); // TODO(bmeurer): We'll need kDependsOnRoots once we add the // corresponding HStoreRoot instruction. SetDependsOnFlag(kCalls); set_representation(Representation::Tagged()); } bool IsDeletable() const override { return true; } const Heap::RootListIndex index_; }; class HCheckMaps final : public HTemplateInstruction<2> { public: static HCheckMaps* New(Isolate* isolate, Zone* zone, HValue* context, HValue* value, Handle<Map> map, HValue* typecheck = NULL) { return new(zone) HCheckMaps(value, new(zone) UniqueSet<Map>( Unique<Map>::CreateImmovable(map), zone), typecheck); } static HCheckMaps* New(Isolate* isolate, Zone* zone, HValue* context, HValue* value, SmallMapList* map_list, HValue* typecheck = NULL) { UniqueSet<Map>* maps = new(zone) UniqueSet<Map>(map_list->length(), zone); for (int i = 0; i < map_list->length(); ++i) { maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone); } return new(zone) HCheckMaps(value, maps, typecheck); } bool IsStabilityCheck() const { return IsStabilityCheckField::decode(bit_field_); } void MarkAsStabilityCheck() { bit_field_ = MapsAreStableField::encode(true) | HasMigrationTargetField::encode(false) | IsStabilityCheckField::encode(true); ClearChangesFlag(kNewSpacePromotion); ClearDependsOnFlag(kElementsKind); ClearDependsOnFlag(kMaps); } bool HasEscapingOperandAt(int index) override { return false; } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HType CalculateInferredType() override { if (value()->type().IsHeapObject()) return value()->type(); return HType::HeapObject(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HValue* value() const { return OperandAt(0); } HValue* typecheck() const { return OperandAt(1); } const UniqueSet<Map>* maps() const { return maps_; } void set_maps(const UniqueSet<Map>* maps) { maps_ = maps; } bool maps_are_stable() const { return MapsAreStableField::decode(bit_field_); } bool HasMigrationTarget() const { return HasMigrationTargetField::decode(bit_field_); } HValue* Canonicalize() override; static HCheckMaps* CreateAndInsertAfter(Zone* zone, HValue* value, Unique<Map> map, bool map_is_stable, HInstruction* instr) { return instr->Append(new(zone) HCheckMaps( value, new(zone) UniqueSet<Map>(map, zone), map_is_stable)); } static HCheckMaps* CreateAndInsertBefore(Zone* zone, HValue* value, const UniqueSet<Map>* maps, bool maps_are_stable, HInstruction* instr) { return instr->Prepend(new(zone) HCheckMaps(value, maps, maps_are_stable)); } DECLARE_CONCRETE_INSTRUCTION(CheckMaps) protected: bool DataEquals(HValue* other) override { return this->maps()->Equals(HCheckMaps::cast(other)->maps()); } int RedefinedOperandIndex() override { return 0; } private: HCheckMaps(HValue* value, const UniqueSet<Map>* maps, bool maps_are_stable) : HTemplateInstruction<2>(HType::HeapObject()), maps_(maps), bit_field_(HasMigrationTargetField::encode(false) | IsStabilityCheckField::encode(false) | MapsAreStableField::encode(maps_are_stable)) { DCHECK_NE(0, maps->size()); SetOperandAt(0, value); // Use the object value for the dependency. SetOperandAt(1, value); set_representation(Representation::Tagged()); SetFlag(kUseGVN); SetDependsOnFlag(kMaps); SetDependsOnFlag(kElementsKind); } HCheckMaps(HValue* value, const UniqueSet<Map>* maps, HValue* typecheck) : HTemplateInstruction<2>(HType::HeapObject()), maps_(maps), bit_field_(HasMigrationTargetField::encode(false) | IsStabilityCheckField::encode(false) | MapsAreStableField::encode(true)) { DCHECK_NE(0, maps->size()); SetOperandAt(0, value); // Use the object value for the dependency if NULL is passed. SetOperandAt(1, typecheck ? typecheck : value); set_representation(Representation::Tagged()); SetFlag(kUseGVN); SetDependsOnFlag(kMaps); SetDependsOnFlag(kElementsKind); for (int i = 0; i < maps->size(); ++i) { Handle<Map> map = maps->at(i).handle(); if (map->is_migration_target()) { bit_field_ = HasMigrationTargetField::update(bit_field_, true); } if (!map->is_stable()) { bit_field_ = MapsAreStableField::update(bit_field_, false); } } if (HasMigrationTarget()) SetChangesFlag(kNewSpacePromotion); } class HasMigrationTargetField : public BitField<bool, 0, 1> {}; class IsStabilityCheckField : public BitField<bool, 1, 1> {}; class MapsAreStableField : public BitField<bool, 2, 1> {}; const UniqueSet<Map>* maps_; uint32_t bit_field_; }; class HCheckValue final : public HUnaryOperation { public: static HCheckValue* New(Isolate* isolate, Zone* zone, HValue* context, HValue* value, Handle<JSFunction> func) { bool in_new_space = isolate->heap()->InNewSpace(*func); // NOTE: We create an uninitialized Unique and initialize it later. // This is because a JSFunction can move due to GC during graph creation. Unique<JSFunction> target = Unique<JSFunction>::CreateUninitialized(func); HCheckValue* check = new(zone) HCheckValue(value, target, in_new_space); return check; } static HCheckValue* New(Isolate* isolate, Zone* zone, HValue* context, HValue* value, Unique<HeapObject> target, bool object_in_new_space) { return new(zone) HCheckValue(value, target, object_in_new_space); } void FinalizeUniqueness() override { object_ = Unique<HeapObject>(object_.handle()); } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HValue* Canonicalize() override; #ifdef DEBUG void Verify() override; #endif Unique<HeapObject> object() const { return object_; } bool object_in_new_space() const { return object_in_new_space_; } DECLARE_CONCRETE_INSTRUCTION(CheckValue) protected: bool DataEquals(HValue* other) override { HCheckValue* b = HCheckValue::cast(other); return object_ == b->object_; } private: HCheckValue(HValue* value, Unique<HeapObject> object, bool object_in_new_space) : HUnaryOperation(value, value->type()), object_(object), object_in_new_space_(object_in_new_space) { set_representation(Representation::Tagged()); SetFlag(kUseGVN); } Unique<HeapObject> object_; bool object_in_new_space_; }; class HCheckInstanceType final : public HUnaryOperation { public: enum Check { IS_JS_RECEIVER, IS_JS_ARRAY, IS_JS_FUNCTION, IS_JS_DATE, IS_STRING, IS_INTERNALIZED_STRING, LAST_INTERVAL_CHECK = IS_JS_DATE }; DECLARE_INSTRUCTION_FACTORY_P2(HCheckInstanceType, HValue*, Check); std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HType CalculateInferredType() override { switch (check_) { case IS_JS_RECEIVER: return HType::JSReceiver(); case IS_JS_ARRAY: return HType::JSArray(); case IS_JS_FUNCTION: return HType::JSObject(); case IS_JS_DATE: return HType::JSObject(); case IS_STRING: return HType::String(); case IS_INTERNALIZED_STRING: return HType::String(); } UNREACHABLE(); return HType::Tagged(); } HValue* Canonicalize() override; bool is_interval_check() const { return check_ <= LAST_INTERVAL_CHECK; } void GetCheckInterval(InstanceType* first, InstanceType* last); void GetCheckMaskAndTag(uint8_t* mask, uint8_t* tag); Check check() const { return check_; } DECLARE_CONCRETE_INSTRUCTION(CheckInstanceType) protected: // TODO(ager): It could be nice to allow the ommision of instance // type checks if we have already performed an instance type check // with a larger range. bool DataEquals(HValue* other) override { HCheckInstanceType* b = HCheckInstanceType::cast(other); return check_ == b->check_; } int RedefinedOperandIndex() override { return 0; } private: const char* GetCheckName() const; HCheckInstanceType(HValue* value, Check check) : HUnaryOperation(value, HType::HeapObject()), check_(check) { set_representation(Representation::Tagged()); SetFlag(kUseGVN); } const Check check_; }; class HCheckSmi final : public HUnaryOperation { public: DECLARE_INSTRUCTION_FACTORY_P1(HCheckSmi, HValue*); Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HValue* Canonicalize() override { HType value_type = value()->type(); if (value_type.IsSmi()) { return NULL; } return this; } DECLARE_CONCRETE_INSTRUCTION(CheckSmi) protected: bool DataEquals(HValue* other) override { return true; } private: explicit HCheckSmi(HValue* value) : HUnaryOperation(value, HType::Smi()) { set_representation(Representation::Smi()); SetFlag(kUseGVN); } }; class HCheckArrayBufferNotNeutered final : public HUnaryOperation { public: DECLARE_INSTRUCTION_FACTORY_P1(HCheckArrayBufferNotNeutered, HValue*); bool HasEscapingOperandAt(int index) override { return false; } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HType CalculateInferredType() override { if (value()->type().IsHeapObject()) return value()->type(); return HType::HeapObject(); } DECLARE_CONCRETE_INSTRUCTION(CheckArrayBufferNotNeutered) protected: bool DataEquals(HValue* other) override { return true; } int RedefinedOperandIndex() override { return 0; } private: explicit HCheckArrayBufferNotNeutered(HValue* value) : HUnaryOperation(value) { set_representation(Representation::Tagged()); SetFlag(kUseGVN); SetDependsOnFlag(kCalls); } }; class HCheckHeapObject final : public HUnaryOperation { public: DECLARE_INSTRUCTION_FACTORY_P1(HCheckHeapObject, HValue*); bool HasEscapingOperandAt(int index) override { return false; } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HType CalculateInferredType() override { if (value()->type().IsHeapObject()) return value()->type(); return HType::HeapObject(); } #ifdef DEBUG void Verify() override; #endif HValue* Canonicalize() override { return value()->type().IsHeapObject() ? NULL : this; } DECLARE_CONCRETE_INSTRUCTION(CheckHeapObject) protected: bool DataEquals(HValue* other) override { return true; } private: explicit HCheckHeapObject(HValue* value) : HUnaryOperation(value) { set_representation(Representation::Tagged()); SetFlag(kUseGVN); } }; class HPhi final : public HValue { public: HPhi(int merged_index, Zone* zone) : inputs_(2, zone), merged_index_(merged_index) { DCHECK(merged_index >= 0 || merged_index == kInvalidMergedIndex); SetFlag(kFlexibleRepresentation); } Representation RepresentationFromInputs() override; Range* InferRange(Zone* zone) override; void InferRepresentation(HInferRepresentationPhase* h_infer) override; Representation RequiredInputRepresentation(int index) override { return representation(); } Representation KnownOptimalRepresentation() override { return representation(); } HType CalculateInferredType() override; int OperandCount() const override { return inputs_.length(); } HValue* OperandAt(int index) const override { return inputs_[index]; } HValue* GetRedundantReplacement(); void AddInput(HValue* value); bool HasRealUses(); bool IsReceiver() const { return merged_index_ == 0; } bool HasMergedIndex() const { return merged_index_ != kInvalidMergedIndex; } SourcePosition position() const override; int merged_index() const { return merged_index_; } std::ostream& PrintTo(std::ostream& os) const override; // NOLINT #ifdef DEBUG void Verify() override; #endif void InitRealUses(int id); void AddNonPhiUsesFrom(HPhi* other); Representation representation_from_indirect_uses() const { return representation_from_indirect_uses_; } bool has_type_feedback_from_uses() const { return has_type_feedback_from_uses_; } int phi_id() { return phi_id_; } static HPhi* cast(HValue* value) { DCHECK(value->IsPhi()); return reinterpret_cast<HPhi*>(value); } Opcode opcode() const override { return HValue::kPhi; } void SimplifyConstantInputs(); // Marker value representing an invalid merge index. static const int kInvalidMergedIndex = -1; protected: void DeleteFromGraph() override; void InternalSetOperandAt(int index, HValue* value) override { inputs_[index] = value; } private: Representation representation_from_non_phi_uses() const { return representation_from_non_phi_uses_; } ZoneList<HValue*> inputs_; int merged_index_ = 0; int phi_id_ = -1; Representation representation_from_indirect_uses_ = Representation::None(); Representation representation_from_non_phi_uses_ = Representation::None(); bool has_type_feedback_from_uses_ = false; bool IsDeletable() const override { return !IsReceiver(); } }; // Common base class for HArgumentsObject and HCapturedObject. class HDematerializedObject : public HInstruction { public: HDematerializedObject(int count, Zone* zone) : values_(count, zone) {} int OperandCount() const final { return values_.length(); } HValue* OperandAt(int index) const final { return values_[index]; } bool HasEscapingOperandAt(int index) final { return false; } Representation RequiredInputRepresentation(int index) final { return Representation::None(); } protected: void InternalSetOperandAt(int index, HValue* value) final { values_[index] = value; } // List of values tracked by this marker. ZoneList<HValue*> values_; }; class HArgumentsObject final : public HDematerializedObject { public: static HArgumentsObject* New(Isolate* isolate, Zone* zone, HValue* context, int count) { return new(zone) HArgumentsObject(count, zone); } // The values contain a list of all elements in the arguments object // including the receiver object, which is skipped when materializing. const ZoneList<HValue*>* arguments_values() const { return &values_; } int arguments_count() const { return values_.length(); } void AddArgument(HValue* argument, Zone* zone) { values_.Add(NULL, zone); // Resize list. SetOperandAt(values_.length() - 1, argument); } DECLARE_CONCRETE_INSTRUCTION(ArgumentsObject) private: HArgumentsObject(int count, Zone* zone) : HDematerializedObject(count, zone) { set_representation(Representation::Tagged()); SetFlag(kIsArguments); } }; class HCapturedObject final : public HDematerializedObject { public: HCapturedObject(int length, int id, Zone* zone) : HDematerializedObject(length, zone), capture_id_(id) { set_representation(Representation::Tagged()); values_.AddBlock(NULL, length, zone); // Resize list. } // The values contain a list of all in-object properties inside the // captured object and is index by field index. Properties in the // properties or elements backing store are not tracked here. const ZoneList<HValue*>* values() const { return &values_; } int length() const { return values_.length(); } int capture_id() const { return capture_id_; } // Shortcut for the map value of this captured object. HValue* map_value() const { return values()->first(); } void ReuseSideEffectsFromStore(HInstruction* store) { DCHECK(store->HasObservableSideEffects()); DCHECK(store->IsStoreNamedField()); changes_flags_.Add(store->ChangesFlags()); } // Replay effects of this instruction on the given environment. void ReplayEnvironment(HEnvironment* env); std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(CapturedObject) private: int capture_id_; // Note that we cannot DCE captured objects as they are used to replay // the environment. This method is here as an explicit reminder. // TODO(mstarzinger): Turn HSimulates into full snapshots maybe? bool IsDeletable() const final { return false; } }; class HConstant final : public HTemplateInstruction<0> { public: enum Special { kHoleNaN }; DECLARE_INSTRUCTION_FACTORY_P1(HConstant, Special); DECLARE_INSTRUCTION_FACTORY_P1(HConstant, int32_t); DECLARE_INSTRUCTION_FACTORY_P2(HConstant, int32_t, Representation); DECLARE_INSTRUCTION_FACTORY_P1(HConstant, double); DECLARE_INSTRUCTION_FACTORY_P1(HConstant, Handle<Object>); DECLARE_INSTRUCTION_FACTORY_P1(HConstant, ExternalReference); static HConstant* CreateAndInsertAfter(Isolate* isolate, Zone* zone, HValue* context, int32_t value, Representation representation, HInstruction* instruction) { return instruction->Append( HConstant::New(isolate, zone, context, value, representation)); } Handle<Map> GetMonomorphicJSObjectMap() override { Handle<Object> object = object_.handle(); if (!object.is_null() && object->IsHeapObject()) { return v8::internal::handle(HeapObject::cast(*object)->map()); } return Handle<Map>(); } static HConstant* CreateAndInsertBefore(Isolate* isolate, Zone* zone, HValue* context, int32_t value, Representation representation, HInstruction* instruction) { return instruction->Prepend( HConstant::New(isolate, zone, context, value, representation)); } static HConstant* CreateAndInsertBefore(Zone* zone, Unique<Map> map, bool map_is_stable, HInstruction* instruction) { return instruction->Prepend(new(zone) HConstant( map, Unique<Map>(Handle<Map>::null()), map_is_stable, Representation::Tagged(), HType::HeapObject(), true, false, false, MAP_TYPE)); } static HConstant* CreateAndInsertAfter(Zone* zone, Unique<Map> map, bool map_is_stable, HInstruction* instruction) { return instruction->Append(new(zone) HConstant( map, Unique<Map>(Handle<Map>::null()), map_is_stable, Representation::Tagged(), HType::HeapObject(), true, false, false, MAP_TYPE)); } Handle<Object> handle(Isolate* isolate) { if (object_.handle().is_null()) { // Default arguments to is_not_in_new_space depend on this heap number // to be tenured so that it's guaranteed not to be located in new space. object_ = Unique<Object>::CreateUninitialized( isolate->factory()->NewNumber(double_value_, TENURED)); } AllowDeferredHandleDereference smi_check; DCHECK(HasInteger32Value() || !object_.handle()->IsSmi()); return object_.handle(); } bool IsSpecialDouble() const { return HasDoubleValue() && (bit_cast<int64_t>(double_value_) == bit_cast<int64_t>(-0.0) || std::isnan(double_value_)); } bool NotInNewSpace() const { return IsNotInNewSpaceField::decode(bit_field_); } bool ImmortalImmovable() const; bool IsCell() const { InstanceType instance_type = GetInstanceType(); return instance_type == CELL_TYPE; } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } Representation KnownOptimalRepresentation() override { if (HasSmiValue() && SmiValuesAre31Bits()) return Representation::Smi(); if (HasInteger32Value()) return Representation::Integer32(); if (HasNumberValue()) return Representation::Double(); if (HasExternalReferenceValue()) return Representation::External(); return Representation::Tagged(); } bool EmitAtUses() override; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HConstant* CopyToRepresentation(Representation r, Zone* zone) const; Maybe<HConstant*> CopyToTruncatedInt32(Zone* zone); Maybe<HConstant*> CopyToTruncatedNumber(Isolate* isolate, Zone* zone); bool HasInteger32Value() const { return HasInt32ValueField::decode(bit_field_); } int32_t Integer32Value() const { DCHECK(HasInteger32Value()); return int32_value_; } bool HasSmiValue() const { return HasSmiValueField::decode(bit_field_); } bool HasDoubleValue() const { return HasDoubleValueField::decode(bit_field_); } double DoubleValue() const { DCHECK(HasDoubleValue()); return double_value_; } uint64_t DoubleValueAsBits() const { uint64_t bits; DCHECK(HasDoubleValue()); STATIC_ASSERT(sizeof(bits) == sizeof(double_value_)); std::memcpy(&bits, &double_value_, sizeof(bits)); return bits; } bool IsTheHole() const { if (HasDoubleValue() && DoubleValueAsBits() == kHoleNanInt64) { return true; } return object_.IsInitialized() && object_.IsKnownGlobal(isolate()->heap()->the_hole_value()); } bool HasNumberValue() const { return HasDoubleValue(); } int32_t NumberValueAsInteger32() const { DCHECK(HasNumberValue()); // Irrespective of whether a numeric HConstant can be safely // represented as an int32, we store the (in some cases lossy) // representation of the number in int32_value_. return int32_value_; } bool HasStringValue() const { if (HasNumberValue()) return false; DCHECK(!object_.handle().is_null()); return GetInstanceType() < FIRST_NONSTRING_TYPE; } Handle<String> StringValue() const { DCHECK(HasStringValue()); return Handle<String>::cast(object_.handle()); } bool HasInternalizedStringValue() const { return HasStringValue() && StringShape(GetInstanceType()).IsInternalized(); } bool HasExternalReferenceValue() const { return HasExternalReferenceValueField::decode(bit_field_); } ExternalReference ExternalReferenceValue() const { return external_reference_value_; } bool HasBooleanValue() const { return type_.IsBoolean(); } bool BooleanValue() const { return BooleanValueField::decode(bit_field_); } bool IsCallable() const { return IsCallableField::decode(bit_field_); } bool IsUndetectable() const { return IsUndetectableField::decode(bit_field_); } InstanceType GetInstanceType() const { return InstanceTypeField::decode(bit_field_); } bool HasMapValue() const { return GetInstanceType() == MAP_TYPE; } Unique<Map> MapValue() const { DCHECK(HasMapValue()); return Unique<Map>::cast(GetUnique()); } bool HasStableMapValue() const { DCHECK(HasMapValue() || !HasStableMapValueField::decode(bit_field_)); return HasStableMapValueField::decode(bit_field_); } bool HasObjectMap() const { return !object_map_.IsNull(); } Unique<Map> ObjectMap() const { DCHECK(HasObjectMap()); return object_map_; } intptr_t Hashcode() override { if (HasInteger32Value()) { return static_cast<intptr_t>(int32_value_); } else if (HasDoubleValue()) { uint64_t bits = DoubleValueAsBits(); if (sizeof(bits) > sizeof(intptr_t)) { bits ^= (bits >> 32); } return static_cast<intptr_t>(bits); } else if (HasExternalReferenceValue()) { return reinterpret_cast<intptr_t>(external_reference_value_.address()); } else { DCHECK(!object_.handle().is_null()); return object_.Hashcode(); } } void FinalizeUniqueness() override { if (!HasDoubleValue() && !HasExternalReferenceValue()) { DCHECK(!object_.handle().is_null()); object_ = Unique<Object>(object_.handle()); } } Unique<Object> GetUnique() const { return object_; } bool EqualsUnique(Unique<Object> other) const { return object_.IsInitialized() && object_ == other; } bool DataEquals(HValue* other) override { HConstant* other_constant = HConstant::cast(other); if (HasInteger32Value()) { return other_constant->HasInteger32Value() && int32_value_ == other_constant->int32_value_; } else if (HasDoubleValue()) { return other_constant->HasDoubleValue() && std::memcmp(&double_value_, &other_constant->double_value_, sizeof(double_value_)) == 0; } else if (HasExternalReferenceValue()) { return other_constant->HasExternalReferenceValue() && external_reference_value_ == other_constant->external_reference_value_; } else { if (other_constant->HasInteger32Value() || other_constant->HasDoubleValue() || other_constant->HasExternalReferenceValue()) { return false; } DCHECK(!object_.handle().is_null()); return other_constant->object_ == object_; } } #ifdef DEBUG void Verify() override {} #endif DECLARE_CONCRETE_INSTRUCTION(Constant) protected: Range* InferRange(Zone* zone) override; private: friend class HGraph; explicit HConstant(Special special); explicit HConstant(Handle<Object> handle, Representation r = Representation::None()); HConstant(int32_t value, Representation r = Representation::None(), bool is_not_in_new_space = true, Unique<Object> optional = Unique<Object>(Handle<Object>::null())); HConstant(double value, Representation r = Representation::None(), bool is_not_in_new_space = true, Unique<Object> optional = Unique<Object>(Handle<Object>::null())); HConstant(Unique<Object> object, Unique<Map> object_map, bool has_stable_map_value, Representation r, HType type, bool is_not_in_new_space, bool boolean_value, bool is_undetectable, InstanceType instance_type); explicit HConstant(ExternalReference reference); void Initialize(Representation r); bool IsDeletable() const override { return true; } // If object_ is a map, this indicates whether the map is stable. class HasStableMapValueField : public BitField<bool, 0, 1> {}; // We store the HConstant in the most specific form safely possible. // These flags tell us if the respective member fields hold valid, safe // representations of the constant. More specific flags imply more general // flags, but not the converse (i.e. smi => int32 => double). class HasSmiValueField : public BitField<bool, 1, 1> {}; class HasInt32ValueField : public BitField<bool, 2, 1> {}; class HasDoubleValueField : public BitField<bool, 3, 1> {}; class HasExternalReferenceValueField : public BitField<bool, 4, 1> {}; class IsNotInNewSpaceField : public BitField<bool, 5, 1> {}; class BooleanValueField : public BitField<bool, 6, 1> {}; class IsUndetectableField : public BitField<bool, 7, 1> {}; class IsCallableField : public BitField<bool, 8, 1> {}; static const InstanceType kUnknownInstanceType = FILLER_TYPE; class InstanceTypeField : public BitField<InstanceType, 16, 8> {}; // If this is a numerical constant, object_ either points to the // HeapObject the constant originated from or is null. If the // constant is non-numeric, object_ always points to a valid // constant HeapObject. Unique<Object> object_; // If object_ is a heap object, this points to the stable map of the object. Unique<Map> object_map_; uint32_t bit_field_; int32_t int32_value_; double double_value_; ExternalReference external_reference_value_; }; class HBinaryOperation : public HTemplateInstruction<3> { public: HBinaryOperation(HValue* context, HValue* left, HValue* right, HType type = HType::Tagged()) : HTemplateInstruction<3>(type), observed_output_representation_(Representation::None()) { DCHECK(left != NULL && right != NULL); SetOperandAt(0, context); SetOperandAt(1, left); SetOperandAt(2, right); observed_input_representation_[0] = Representation::None(); observed_input_representation_[1] = Representation::None(); } HValue* context() const { return OperandAt(0); } HValue* left() const { return OperandAt(1); } HValue* right() const { return OperandAt(2); } // True if switching left and right operands likely generates better code. bool AreOperandsBetterSwitched() { if (!IsCommutative()) return false; // Constant operands are better off on the right, they can be inlined in // many situations on most platforms. if (left()->IsConstant()) return true; if (right()->IsConstant()) return false; // Otherwise, if there is only one use of the right operand, it would be // better off on the left for platforms that only have 2-arg arithmetic // ops (e.g ia32, x64) that clobber the left operand. return right()->HasOneUse(); } HValue* BetterLeftOperand() { return AreOperandsBetterSwitched() ? right() : left(); } HValue* BetterRightOperand() { return AreOperandsBetterSwitched() ? left() : right(); } void set_observed_input_representation(int index, Representation rep) { DCHECK(index >= 1 && index <= 2); observed_input_representation_[index - 1] = rep; } virtual void initialize_output_representation(Representation observed) { observed_output_representation_ = observed; } Representation observed_input_representation(int index) override { if (index == 0) return Representation::Tagged(); return observed_input_representation_[index - 1]; } void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason) override { Representation rep = !FLAG_smi_binop && new_rep.IsSmi() ? Representation::Integer32() : new_rep; HValue::UpdateRepresentation(rep, h_infer, reason); } void InferRepresentation(HInferRepresentationPhase* h_infer) override; Representation RepresentationFromInputs() override; Representation RepresentationFromOutput(); void AssumeRepresentation(Representation r) override; virtual bool IsCommutative() const { return false; } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) override { if (index == 0) return Representation::Tagged(); return representation(); } bool RightIsPowerOf2() { if (!right()->IsInteger32Constant()) return false; int32_t value = right()->GetInteger32Constant(); if (value < 0) { return base::bits::IsPowerOfTwo32(static_cast<uint32_t>(-value)); } return base::bits::IsPowerOfTwo32(static_cast<uint32_t>(value)); } DECLARE_ABSTRACT_INSTRUCTION(BinaryOperation) private: bool IgnoreObservedOutputRepresentation(Representation current_rep); Representation observed_input_representation_[2]; Representation observed_output_representation_; }; class HWrapReceiver final : public HTemplateInstruction<2> { public: DECLARE_INSTRUCTION_FACTORY_P2(HWrapReceiver, HValue*, HValue*); bool DataEquals(HValue* other) override { return true; } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HValue* receiver() const { return OperandAt(0); } HValue* function() const { return OperandAt(1); } HValue* Canonicalize() override; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT bool known_function() const { return known_function_; } DECLARE_CONCRETE_INSTRUCTION(WrapReceiver) private: HWrapReceiver(HValue* receiver, HValue* function) { known_function_ = function->IsConstant() && HConstant::cast(function)->handle(function->isolate())->IsJSFunction(); set_representation(Representation::Tagged()); SetOperandAt(0, receiver); SetOperandAt(1, function); SetFlag(kUseGVN); } bool known_function_; }; class HApplyArguments final : public HTemplateInstruction<4> { public: DECLARE_INSTRUCTION_FACTORY_P5(HApplyArguments, HValue*, HValue*, HValue*, HValue*, TailCallMode); Representation RequiredInputRepresentation(int index) override { // The length is untagged, all other inputs are tagged. return (index == 2) ? Representation::Integer32() : Representation::Tagged(); } HValue* function() { return OperandAt(0); } HValue* receiver() { return OperandAt(1); } HValue* length() { return OperandAt(2); } HValue* elements() { return OperandAt(3); } TailCallMode tail_call_mode() const { return TailCallModeField::decode(bit_field_); } DECLARE_CONCRETE_INSTRUCTION(ApplyArguments) private: HApplyArguments(HValue* function, HValue* receiver, HValue* length, HValue* elements, TailCallMode tail_call_mode) : bit_field_(TailCallModeField::encode(tail_call_mode)) { set_representation(Representation::Tagged()); SetOperandAt(0, function); SetOperandAt(1, receiver); SetOperandAt(2, length); SetOperandAt(3, elements); SetAllSideEffects(); } class TailCallModeField : public BitField<TailCallMode, 0, 1> {}; uint32_t bit_field_; }; class HArgumentsElements final : public HTemplateInstruction<0> { public: DECLARE_INSTRUCTION_FACTORY_P1(HArgumentsElements, bool); DECLARE_INSTRUCTION_FACTORY_P2(HArgumentsElements, bool, bool); DECLARE_CONCRETE_INSTRUCTION(ArgumentsElements) Representation RequiredInputRepresentation(int index) override { return Representation::None(); } bool from_inlined() const { return from_inlined_; } bool arguments_adaptor() const { return arguments_adaptor_; } protected: bool DataEquals(HValue* other) override { return true; } private: explicit HArgumentsElements(bool from_inlined, bool arguments_adaptor = true) : from_inlined_(from_inlined), arguments_adaptor_(arguments_adaptor) { // The value produced by this instruction is a pointer into the stack // that looks as if it was a smi because of alignment. set_representation(Representation::Tagged()); SetFlag(kUseGVN); } bool IsDeletable() const override { return true; } bool from_inlined_; bool arguments_adaptor_; }; class HArgumentsLength final : public HUnaryOperation { public: DECLARE_INSTRUCTION_FACTORY_P1(HArgumentsLength, HValue*); Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(ArgumentsLength) protected: bool DataEquals(HValue* other) override { return true; } private: explicit HArgumentsLength(HValue* value) : HUnaryOperation(value) { set_representation(Representation::Integer32()); SetFlag(kUseGVN); } bool IsDeletable() const override { return true; } }; class HAccessArgumentsAt final : public HTemplateInstruction<3> { public: DECLARE_INSTRUCTION_FACTORY_P3(HAccessArgumentsAt, HValue*, HValue*, HValue*); std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) override { // The arguments elements is considered tagged. return index == 0 ? Representation::Tagged() : Representation::Integer32(); } HValue* arguments() const { return OperandAt(0); } HValue* length() const { return OperandAt(1); } HValue* index() const { return OperandAt(2); } DECLARE_CONCRETE_INSTRUCTION(AccessArgumentsAt) private: HAccessArgumentsAt(HValue* arguments, HValue* length, HValue* index) { set_representation(Representation::Tagged()); SetFlag(kUseGVN); SetOperandAt(0, arguments); SetOperandAt(1, length); SetOperandAt(2, index); } bool DataEquals(HValue* other) override { return true; } }; class HBoundsCheck final : public HTemplateInstruction<2> { public: DECLARE_INSTRUCTION_FACTORY_P2(HBoundsCheck, HValue*, HValue*); bool skip_check() const { return skip_check_; } void set_skip_check() { skip_check_ = true; } HValue* base() const { return base_; } int offset() const { return offset_; } int scale() const { return scale_; } Representation RequiredInputRepresentation(int index) override { return representation(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT void InferRepresentation(HInferRepresentationPhase* h_infer) override; HValue* index() const { return OperandAt(0); } HValue* length() const { return OperandAt(1); } bool allow_equality() const { return allow_equality_; } void set_allow_equality(bool v) { allow_equality_ = v; } int RedefinedOperandIndex() override { return 0; } bool IsPurelyInformativeDefinition() override { return skip_check(); } DECLARE_CONCRETE_INSTRUCTION(BoundsCheck) protected: Range* InferRange(Zone* zone) override; bool DataEquals(HValue* other) override { return true; } bool skip_check_; HValue* base_; int offset_; int scale_; bool allow_equality_; private: // Normally HBoundsCheck should be created using the // HGraphBuilder::AddBoundsCheck() helper. // However when building stubs, where we know that the arguments are Int32, // it makes sense to invoke this constructor directly. HBoundsCheck(HValue* index, HValue* length) : skip_check_(false), base_(NULL), offset_(0), scale_(0), allow_equality_(false) { SetOperandAt(0, index); SetOperandAt(1, length); SetFlag(kFlexibleRepresentation); SetFlag(kUseGVN); } bool IsDeletable() const override { return skip_check() && !FLAG_debug_code; } }; class HBitwiseBinaryOperation : public HBinaryOperation { public: HBitwiseBinaryOperation(HValue* context, HValue* left, HValue* right, HType type = HType::TaggedNumber()) : HBinaryOperation(context, left, right, type) { SetFlag(kFlexibleRepresentation); SetFlag(kTruncatingToInt32); SetFlag(kTruncatingToNumber); SetAllSideEffects(); } void RepresentationChanged(Representation to) override { if (to.IsTagged() && (left()->ToNumberCanBeObserved() || right()->ToNumberCanBeObserved())) { SetAllSideEffects(); ClearFlag(kUseGVN); } else { ClearAllSideEffects(); SetFlag(kUseGVN); } if (to.IsTagged()) SetChangesFlag(kNewSpacePromotion); } void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason) override { // We only generate either int32 or generic tagged bitwise operations. if (new_rep.IsDouble()) new_rep = Representation::Integer32(); HBinaryOperation::UpdateRepresentation(new_rep, h_infer, reason); } Representation observed_input_representation(int index) override { Representation r = HBinaryOperation::observed_input_representation(index); if (r.IsDouble()) return Representation::Integer32(); return r; } void initialize_output_representation(Representation observed) override { if (observed.IsDouble()) observed = Representation::Integer32(); HBinaryOperation::initialize_output_representation(observed); } DECLARE_ABSTRACT_INSTRUCTION(BitwiseBinaryOperation) private: bool IsDeletable() const override { return true; } }; class HMathFloorOfDiv final : public HBinaryOperation { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P2(HMathFloorOfDiv, HValue*, HValue*); DECLARE_CONCRETE_INSTRUCTION(MathFloorOfDiv) protected: bool DataEquals(HValue* other) override { return true; } private: HMathFloorOfDiv(HValue* context, HValue* left, HValue* right) : HBinaryOperation(context, left, right) { set_representation(Representation::Integer32()); SetFlag(kUseGVN); SetFlag(kCanOverflow); SetFlag(kCanBeDivByZero); SetFlag(kLeftCanBeMinInt); SetFlag(kLeftCanBeNegative); SetFlag(kLeftCanBePositive); SetFlag(kTruncatingToNumber); } Range* InferRange(Zone* zone) override; bool IsDeletable() const override { return true; } }; class HArithmeticBinaryOperation : public HBinaryOperation { public: HArithmeticBinaryOperation(HValue* context, HValue* left, HValue* right, HType type = HType::TaggedNumber()) : HBinaryOperation(context, left, right, type) { SetAllSideEffects(); SetFlag(kFlexibleRepresentation); SetFlag(kTruncatingToNumber); } void RepresentationChanged(Representation to) override { if (to.IsTagged() && (left()->ToNumberCanBeObserved() || right()->ToNumberCanBeObserved())) { SetAllSideEffects(); ClearFlag(kUseGVN); } else { ClearAllSideEffects(); SetFlag(kUseGVN); } if (to.IsTagged()) SetChangesFlag(kNewSpacePromotion); } DECLARE_ABSTRACT_INSTRUCTION(ArithmeticBinaryOperation) private: bool IsDeletable() const override { return true; } }; class HCompareGeneric final : public HBinaryOperation { public: static HCompareGeneric* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right, Token::Value token) { return new (zone) HCompareGeneric(context, left, right, token); } Representation RequiredInputRepresentation(int index) override { return index == 0 ? Representation::Tagged() : representation(); } Token::Value token() const { return token_; } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(CompareGeneric) private: HCompareGeneric(HValue* context, HValue* left, HValue* right, Token::Value token) : HBinaryOperation(context, left, right, HType::Boolean()), token_(token) { DCHECK(Token::IsCompareOp(token)); set_representation(Representation::Tagged()); SetAllSideEffects(); } Token::Value token_; }; class HCompareNumericAndBranch : public HTemplateControlInstruction<2, 2> { public: static HCompareNumericAndBranch* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right, Token::Value token, HBasicBlock* true_target = NULL, HBasicBlock* false_target = NULL) { return new (zone) HCompareNumericAndBranch(left, right, token, true_target, false_target); } HValue* left() const { return OperandAt(0); } HValue* right() const { return OperandAt(1); } Token::Value token() const { return token_; } void set_observed_input_representation(Representation left, Representation right) { observed_input_representation_[0] = left; observed_input_representation_[1] = right; } void InferRepresentation(HInferRepresentationPhase* h_infer) override; Representation RequiredInputRepresentation(int index) override { return representation(); } Representation observed_input_representation(int index) override { return observed_input_representation_[index]; } bool KnownSuccessorBlock(HBasicBlock** block) override; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(CompareNumericAndBranch) private: HCompareNumericAndBranch(HValue* left, HValue* right, Token::Value token, HBasicBlock* true_target, HBasicBlock* false_target) : token_(token) { SetFlag(kFlexibleRepresentation); DCHECK(Token::IsCompareOp(token)); SetOperandAt(0, left); SetOperandAt(1, right); SetSuccessorAt(0, true_target); SetSuccessorAt(1, false_target); } Representation observed_input_representation_[2]; Token::Value token_; }; class HCompareHoleAndBranch final : public HUnaryControlInstruction { public: DECLARE_INSTRUCTION_FACTORY_P1(HCompareHoleAndBranch, HValue*); DECLARE_INSTRUCTION_FACTORY_P3(HCompareHoleAndBranch, HValue*, HBasicBlock*, HBasicBlock*); void InferRepresentation(HInferRepresentationPhase* h_infer) override; Representation RequiredInputRepresentation(int index) override { return representation(); } DECLARE_CONCRETE_INSTRUCTION(CompareHoleAndBranch) private: HCompareHoleAndBranch(HValue* value, HBasicBlock* true_target = NULL, HBasicBlock* false_target = NULL) : HUnaryControlInstruction(value, true_target, false_target) { SetFlag(kFlexibleRepresentation); } }; class HCompareObjectEqAndBranch : public HTemplateControlInstruction<2, 2> { public: DECLARE_INSTRUCTION_FACTORY_P2(HCompareObjectEqAndBranch, HValue*, HValue*); DECLARE_INSTRUCTION_FACTORY_P4(HCompareObjectEqAndBranch, HValue*, HValue*, HBasicBlock*, HBasicBlock*); bool KnownSuccessorBlock(HBasicBlock** block) override; static const int kNoKnownSuccessorIndex = -1; int known_successor_index() const { return known_successor_index_; } void set_known_successor_index(int known_successor_index) { known_successor_index_ = known_successor_index; } HValue* left() const { return OperandAt(0); } HValue* right() const { return OperandAt(1); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } Representation observed_input_representation(int index) override { return Representation::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(CompareObjectEqAndBranch) private: HCompareObjectEqAndBranch(HValue* left, HValue* right, HBasicBlock* true_target = NULL, HBasicBlock* false_target = NULL) : known_successor_index_(kNoKnownSuccessorIndex) { SetOperandAt(0, left); SetOperandAt(1, right); SetSuccessorAt(0, true_target); SetSuccessorAt(1, false_target); } int known_successor_index_; }; class HIsStringAndBranch final : public HUnaryControlInstruction { public: DECLARE_INSTRUCTION_FACTORY_P1(HIsStringAndBranch, HValue*); DECLARE_INSTRUCTION_FACTORY_P3(HIsStringAndBranch, HValue*, HBasicBlock*, HBasicBlock*); Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } bool KnownSuccessorBlock(HBasicBlock** block) override; static const int kNoKnownSuccessorIndex = -1; int known_successor_index() const { return known_successor_index_; } void set_known_successor_index(int known_successor_index) { known_successor_index_ = known_successor_index; } DECLARE_CONCRETE_INSTRUCTION(IsStringAndBranch) protected: int RedefinedOperandIndex() override { return 0; } private: HIsStringAndBranch(HValue* value, HBasicBlock* true_target = NULL, HBasicBlock* false_target = NULL) : HUnaryControlInstruction(value, true_target, false_target), known_successor_index_(kNoKnownSuccessorIndex) { set_representation(Representation::Tagged()); } int known_successor_index_; }; class HIsSmiAndBranch final : public HUnaryControlInstruction { public: DECLARE_INSTRUCTION_FACTORY_P1(HIsSmiAndBranch, HValue*); DECLARE_INSTRUCTION_FACTORY_P3(HIsSmiAndBranch, HValue*, HBasicBlock*, HBasicBlock*); DECLARE_CONCRETE_INSTRUCTION(IsSmiAndBranch) Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } protected: bool DataEquals(HValue* other) override { return true; } int RedefinedOperandIndex() override { return 0; } private: HIsSmiAndBranch(HValue* value, HBasicBlock* true_target = NULL, HBasicBlock* false_target = NULL) : HUnaryControlInstruction(value, true_target, false_target) { set_representation(Representation::Tagged()); } }; class HIsUndetectableAndBranch final : public HUnaryControlInstruction { public: DECLARE_INSTRUCTION_FACTORY_P1(HIsUndetectableAndBranch, HValue*); DECLARE_INSTRUCTION_FACTORY_P3(HIsUndetectableAndBranch, HValue*, HBasicBlock*, HBasicBlock*); Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } bool KnownSuccessorBlock(HBasicBlock** block) override; DECLARE_CONCRETE_INSTRUCTION(IsUndetectableAndBranch) private: HIsUndetectableAndBranch(HValue* value, HBasicBlock* true_target = NULL, HBasicBlock* false_target = NULL) : HUnaryControlInstruction(value, true_target, false_target) {} }; class HStringCompareAndBranch final : public HTemplateControlInstruction<2, 3> { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P3(HStringCompareAndBranch, HValue*, HValue*, Token::Value); HValue* context() const { return OperandAt(0); } HValue* left() const { return OperandAt(1); } HValue* right() const { return OperandAt(2); } Token::Value token() const { return token_; } std::ostream& PrintDataTo(std::ostream& os) const final; // NOLINT Representation RequiredInputRepresentation(int index) final { return Representation::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(StringCompareAndBranch) private: HStringCompareAndBranch(HValue* context, HValue* left, HValue* right, Token::Value token) : token_(token) { DCHECK(Token::IsCompareOp(token)); SetOperandAt(0, context); SetOperandAt(1, left); SetOperandAt(2, right); set_representation(Representation::Tagged()); SetChangesFlag(kNewSpacePromotion); SetDependsOnFlag(kStringChars); SetDependsOnFlag(kStringLengths); } Token::Value const token_; }; class HHasInstanceTypeAndBranch final : public HUnaryControlInstruction { public: DECLARE_INSTRUCTION_FACTORY_P2( HHasInstanceTypeAndBranch, HValue*, InstanceType); DECLARE_INSTRUCTION_FACTORY_P3( HHasInstanceTypeAndBranch, HValue*, InstanceType, InstanceType); InstanceType from() { return from_; } InstanceType to() { return to_; } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } bool KnownSuccessorBlock(HBasicBlock** block) override; DECLARE_CONCRETE_INSTRUCTION(HasInstanceTypeAndBranch) private: HHasInstanceTypeAndBranch(HValue* value, InstanceType type) : HUnaryControlInstruction(value, NULL, NULL), from_(type), to_(type) { } HHasInstanceTypeAndBranch(HValue* value, InstanceType from, InstanceType to) : HUnaryControlInstruction(value, NULL, NULL), from_(from), to_(to) { DCHECK(to == LAST_TYPE); // Others not implemented yet in backend. } InstanceType from_; InstanceType to_; // Inclusive range, not all combinations work. }; class HClassOfTestAndBranch final : public HUnaryControlInstruction { public: DECLARE_INSTRUCTION_FACTORY_P2(HClassOfTestAndBranch, HValue*, Handle<String>); DECLARE_CONCRETE_INSTRUCTION(ClassOfTestAndBranch) Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Handle<String> class_name() const { return class_name_; } private: HClassOfTestAndBranch(HValue* value, Handle<String> class_name) : HUnaryControlInstruction(value, NULL, NULL), class_name_(class_name) { } Handle<String> class_name_; }; class HTypeofIsAndBranch final : public HUnaryControlInstruction { public: DECLARE_INSTRUCTION_FACTORY_P2(HTypeofIsAndBranch, HValue*, Handle<String>); Handle<String> type_literal() const { return type_literal_.handle(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(TypeofIsAndBranch) Representation RequiredInputRepresentation(int index) override { return Representation::None(); } bool KnownSuccessorBlock(HBasicBlock** block) override; void FinalizeUniqueness() override { type_literal_ = Unique<String>(type_literal_.handle()); } private: HTypeofIsAndBranch(HValue* value, Handle<String> type_literal) : HUnaryControlInstruction(value, NULL, NULL), type_literal_(Unique<String>::CreateUninitialized(type_literal)) { } Unique<String> type_literal_; }; class HHasInPrototypeChainAndBranch final : public HTemplateControlInstruction<2, 2> { public: DECLARE_INSTRUCTION_FACTORY_P2(HHasInPrototypeChainAndBranch, HValue*, HValue*); HValue* object() const { return OperandAt(0); } HValue* prototype() const { return OperandAt(1); } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } bool ObjectNeedsSmiCheck() const { return !object()->type().IsHeapObject() && !object()->representation().IsHeapObject(); } DECLARE_CONCRETE_INSTRUCTION(HasInPrototypeChainAndBranch) private: HHasInPrototypeChainAndBranch(HValue* object, HValue* prototype) { SetOperandAt(0, object); SetOperandAt(1, prototype); SetDependsOnFlag(kCalls); } }; class HPower final : public HTemplateInstruction<2> { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right); HValue* left() { return OperandAt(0); } HValue* right() const { return OperandAt(1); } Representation RequiredInputRepresentation(int index) override { return index == 0 ? Representation::Double() : Representation::None(); } Representation observed_input_representation(int index) override { return RequiredInputRepresentation(index); } DECLARE_CONCRETE_INSTRUCTION(Power) protected: bool DataEquals(HValue* other) override { return true; } private: HPower(HValue* left, HValue* right) { SetOperandAt(0, left); SetOperandAt(1, right); set_representation(Representation::Double()); SetFlag(kUseGVN); SetChangesFlag(kNewSpacePromotion); } bool IsDeletable() const override { return !right()->representation().IsTagged(); } }; enum ExternalAddType { AddOfExternalAndTagged, AddOfExternalAndInt32, NoExternalAdd }; class HAdd final : public HArithmeticBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right); static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right, ExternalAddType external_add_type); // Add is only commutative if two integer values are added and not if two // tagged values are added (because it might be a String concatenation). // We also do not commute (pointer + offset). bool IsCommutative() const override { return !representation().IsTagged() && !representation().IsExternal(); } HValue* Canonicalize() override; void RepresentationChanged(Representation to) override { if (to.IsTagged() && (left()->ToNumberCanBeObserved() || right()->ToNumberCanBeObserved() || left()->ToStringCanBeObserved() || right()->ToStringCanBeObserved())) { SetAllSideEffects(); ClearFlag(kUseGVN); } else { ClearAllSideEffects(); SetFlag(kUseGVN); } if (to.IsTagged()) { SetChangesFlag(kNewSpacePromotion); ClearFlag(kTruncatingToNumber); } if (!right()->type().IsTaggedNumber() && !right()->representation().IsDouble() && !right()->representation().IsSmiOrInteger32()) { ClearFlag(kTruncatingToNumber); } } Representation RepresentationFromInputs() override; Representation RequiredInputRepresentation(int index) override; bool IsConsistentExternalRepresentation() { return left()->representation().IsExternal() && ((external_add_type_ == AddOfExternalAndInt32 && right()->representation().IsInteger32()) || (external_add_type_ == AddOfExternalAndTagged && right()->representation().IsTagged())); } ExternalAddType external_add_type() const { return external_add_type_; } DECLARE_CONCRETE_INSTRUCTION(Add) protected: bool DataEquals(HValue* other) override { return true; } Range* InferRange(Zone* zone) override; private: HAdd(HValue* context, HValue* left, HValue* right, ExternalAddType external_add_type = NoExternalAdd) : HArithmeticBinaryOperation(context, left, right, HType::Tagged()), external_add_type_(external_add_type) { SetFlag(kCanOverflow); switch (external_add_type_) { case AddOfExternalAndTagged: DCHECK(left->representation().IsExternal()); DCHECK(right->representation().IsTagged()); SetDependsOnFlag(kNewSpacePromotion); ClearFlag(HValue::kCanOverflow); SetFlag(kHasNoObservableSideEffects); break; case NoExternalAdd: // This is a bit of a hack: The call to this constructor is generated // by a macro that also supports sub and mul, so it doesn't pass in // a value for external_add_type but uses the default. if (left->representation().IsExternal()) { external_add_type_ = AddOfExternalAndInt32; } break; case AddOfExternalAndInt32: // See comment above. UNREACHABLE(); break; } } ExternalAddType external_add_type_; }; class HSub final : public HArithmeticBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right); HValue* Canonicalize() override; DECLARE_CONCRETE_INSTRUCTION(Sub) protected: bool DataEquals(HValue* other) override { return true; } Range* InferRange(Zone* zone) override; private: HSub(HValue* context, HValue* left, HValue* right) : HArithmeticBinaryOperation(context, left, right) { SetFlag(kCanOverflow); } }; class HMul final : public HArithmeticBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right); static HInstruction* NewImul(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right) { HInstruction* instr = HMul::New(isolate, zone, context, left, right); if (!instr->IsMul()) return instr; HMul* mul = HMul::cast(instr); // TODO(mstarzinger): Prevent bailout on minus zero for imul. mul->AssumeRepresentation(Representation::Integer32()); mul->ClearFlag(HValue::kCanOverflow); return mul; } HValue* Canonicalize() override; // Only commutative if it is certain that not two objects are multiplicated. bool IsCommutative() const override { return !representation().IsTagged(); } void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason) override { HArithmeticBinaryOperation::UpdateRepresentation(new_rep, h_infer, reason); } bool MulMinusOne(); DECLARE_CONCRETE_INSTRUCTION(Mul) protected: bool DataEquals(HValue* other) override { return true; } Range* InferRange(Zone* zone) override; private: HMul(HValue* context, HValue* left, HValue* right) : HArithmeticBinaryOperation(context, left, right) { SetFlag(kCanOverflow); } }; class HMod final : public HArithmeticBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right); HValue* Canonicalize() override; void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason) override { if (new_rep.IsSmi()) new_rep = Representation::Integer32(); HArithmeticBinaryOperation::UpdateRepresentation(new_rep, h_infer, reason); } DECLARE_CONCRETE_INSTRUCTION(Mod) protected: bool DataEquals(HValue* other) override { return true; } Range* InferRange(Zone* zone) override; private: HMod(HValue* context, HValue* left, HValue* right) : HArithmeticBinaryOperation(context, left, right) { SetFlag(kCanBeDivByZero); SetFlag(kCanOverflow); SetFlag(kLeftCanBeNegative); } }; class HDiv final : public HArithmeticBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right); HValue* Canonicalize() override; void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason) override { if (new_rep.IsSmi()) new_rep = Representation::Integer32(); HArithmeticBinaryOperation::UpdateRepresentation(new_rep, h_infer, reason); } DECLARE_CONCRETE_INSTRUCTION(Div) protected: bool DataEquals(HValue* other) override { return true; } Range* InferRange(Zone* zone) override; private: HDiv(HValue* context, HValue* left, HValue* right) : HArithmeticBinaryOperation(context, left, right) { SetFlag(kCanBeDivByZero); SetFlag(kCanOverflow); } }; class HMathMinMax final : public HArithmeticBinaryOperation { public: enum Operation { kMathMin, kMathMax }; static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right, Operation op); Representation observed_input_representation(int index) override { return RequiredInputRepresentation(index); } void InferRepresentation(HInferRepresentationPhase* h_infer) override; Representation RepresentationFromInputs() override { Representation left_rep = left()->representation(); Representation right_rep = right()->representation(); Representation result = Representation::Smi(); result = result.generalize(left_rep); result = result.generalize(right_rep); if (result.IsTagged()) return Representation::Double(); return result; } bool IsCommutative() const override { return true; } Operation operation() { return operation_; } DECLARE_CONCRETE_INSTRUCTION(MathMinMax) protected: bool DataEquals(HValue* other) override { return other->IsMathMinMax() && HMathMinMax::cast(other)->operation_ == operation_; } Range* InferRange(Zone* zone) override; private: HMathMinMax(HValue* context, HValue* left, HValue* right, Operation op) : HArithmeticBinaryOperation(context, left, right), operation_(op) {} Operation operation_; }; class HBitwise final : public HBitwiseBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, Token::Value op, HValue* left, HValue* right); Token::Value op() const { return op_; } bool IsCommutative() const override { return true; } HValue* Canonicalize() override; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(Bitwise) protected: bool DataEquals(HValue* other) override { return op() == HBitwise::cast(other)->op(); } Range* InferRange(Zone* zone) override; private: HBitwise(HValue* context, Token::Value op, HValue* left, HValue* right) : HBitwiseBinaryOperation(context, left, right), op_(op) { DCHECK(op == Token::BIT_AND || op == Token::BIT_OR || op == Token::BIT_XOR); // BIT_AND with a smi-range positive value will always unset the // entire sign-extension of the smi-sign. if (op == Token::BIT_AND && ((left->IsConstant() && left->representation().IsSmi() && HConstant::cast(left)->Integer32Value() >= 0) || (right->IsConstant() && right->representation().IsSmi() && HConstant::cast(right)->Integer32Value() >= 0))) { SetFlag(kTruncatingToSmi); SetFlag(kTruncatingToInt32); // BIT_OR with a smi-range negative value will always set the entire // sign-extension of the smi-sign. } else if (op == Token::BIT_OR && ((left->IsConstant() && left->representation().IsSmi() && HConstant::cast(left)->Integer32Value() < 0) || (right->IsConstant() && right->representation().IsSmi() && HConstant::cast(right)->Integer32Value() < 0))) { SetFlag(kTruncatingToSmi); SetFlag(kTruncatingToInt32); } } Token::Value op_; }; class HShl final : public HBitwiseBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right); Range* InferRange(Zone* zone) override; void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason) override { if (new_rep.IsSmi() && !(right()->IsInteger32Constant() && right()->GetInteger32Constant() >= 0)) { new_rep = Representation::Integer32(); } HBitwiseBinaryOperation::UpdateRepresentation(new_rep, h_infer, reason); } DECLARE_CONCRETE_INSTRUCTION(Shl) protected: bool DataEquals(HValue* other) override { return true; } private: HShl(HValue* context, HValue* left, HValue* right) : HBitwiseBinaryOperation(context, left, right) {} }; class HShr final : public HBitwiseBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right); Range* InferRange(Zone* zone) override; void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason) override { if (new_rep.IsSmi()) new_rep = Representation::Integer32(); HBitwiseBinaryOperation::UpdateRepresentation(new_rep, h_infer, reason); } DECLARE_CONCRETE_INSTRUCTION(Shr) protected: bool DataEquals(HValue* other) override { return true; } private: HShr(HValue* context, HValue* left, HValue* right) : HBitwiseBinaryOperation(context, left, right) {} }; class HSar final : public HBitwiseBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right); Range* InferRange(Zone* zone) override; void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason) override { if (new_rep.IsSmi()) new_rep = Representation::Integer32(); HBitwiseBinaryOperation::UpdateRepresentation(new_rep, h_infer, reason); } DECLARE_CONCRETE_INSTRUCTION(Sar) protected: bool DataEquals(HValue* other) override { return true; } private: HSar(HValue* context, HValue* left, HValue* right) : HBitwiseBinaryOperation(context, left, right) {} }; class HRor final : public HBitwiseBinaryOperation { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right) { return new (zone) HRor(context, left, right); } void UpdateRepresentation(Representation new_rep, HInferRepresentationPhase* h_infer, const char* reason) override { if (new_rep.IsSmi()) new_rep = Representation::Integer32(); HBitwiseBinaryOperation::UpdateRepresentation(new_rep, h_infer, reason); } DECLARE_CONCRETE_INSTRUCTION(Ror) protected: bool DataEquals(HValue* other) override { return true; } private: HRor(HValue* context, HValue* left, HValue* right) : HBitwiseBinaryOperation(context, left, right) { ChangeRepresentation(Representation::Integer32()); } }; class HOsrEntry final : public HTemplateInstruction<0> { public: DECLARE_INSTRUCTION_FACTORY_P1(HOsrEntry, BailoutId); BailoutId ast_id() const { return ast_id_; } Representation RequiredInputRepresentation(int index) override { return Representation::None(); } DECLARE_CONCRETE_INSTRUCTION(OsrEntry) private: explicit HOsrEntry(BailoutId ast_id) : ast_id_(ast_id) { SetChangesFlag(kOsrEntries); SetChangesFlag(kNewSpacePromotion); } BailoutId ast_id_; }; class HParameter final : public HTemplateInstruction<0> { public: enum ParameterKind { STACK_PARAMETER, REGISTER_PARAMETER }; DECLARE_INSTRUCTION_FACTORY_P1(HParameter, unsigned); DECLARE_INSTRUCTION_FACTORY_P2(HParameter, unsigned, ParameterKind); DECLARE_INSTRUCTION_FACTORY_P3(HParameter, unsigned, ParameterKind, Representation); unsigned index() const { return index_; } ParameterKind kind() const { return kind_; } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) override { return Representation::None(); } Representation KnownOptimalRepresentation() override { // If a parameter is an input to a phi, that phi should not // choose any more optimistic representation than Tagged. return Representation::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(Parameter) private: explicit HParameter(unsigned index, ParameterKind kind = STACK_PARAMETER) : index_(index), kind_(kind) { set_representation(Representation::Tagged()); } explicit HParameter(unsigned index, ParameterKind kind, Representation r) : index_(index), kind_(kind) { set_representation(r); } unsigned index_; ParameterKind kind_; }; class HUnknownOSRValue final : public HTemplateInstruction<0> { public: DECLARE_INSTRUCTION_FACTORY_P2(HUnknownOSRValue, HEnvironment*, int); std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) override { return Representation::None(); } void set_incoming_value(HPhi* value) { incoming_value_ = value; } HPhi* incoming_value() { return incoming_value_; } HEnvironment *environment() { return environment_; } int index() { return index_; } Representation KnownOptimalRepresentation() override { if (incoming_value_ == NULL) return Representation::None(); return incoming_value_->KnownOptimalRepresentation(); } DECLARE_CONCRETE_INSTRUCTION(UnknownOSRValue) private: HUnknownOSRValue(HEnvironment* environment, int index) : environment_(environment), index_(index), incoming_value_(NULL) { set_representation(Representation::Tagged()); } HEnvironment* environment_; int index_; HPhi* incoming_value_; }; class HAllocate final : public HTemplateInstruction<3> { public: static bool CompatibleInstanceTypes(InstanceType type1, InstanceType type2) { return ComputeFlags(TENURED, type1) == ComputeFlags(TENURED, type2) && ComputeFlags(NOT_TENURED, type1) == ComputeFlags(NOT_TENURED, type2); } static HAllocate* New( Isolate* isolate, Zone* zone, HValue* context, HValue* size, HType type, PretenureFlag pretenure_flag, InstanceType instance_type, HValue* dominator, Handle<AllocationSite> allocation_site = Handle<AllocationSite>::null()) { return new (zone) HAllocate(context, size, type, pretenure_flag, instance_type, dominator, allocation_site); } // Maximum instance size for which allocations will be inlined. static const int kMaxInlineSize = 64 * kPointerSize; HValue* context() const { return OperandAt(0); } HValue* size() const { return OperandAt(1); } HValue* allocation_folding_dominator() const { return OperandAt(2); } Representation RequiredInputRepresentation(int index) override { if (index == 0) { return Representation::Tagged(); } else { return Representation::Integer32(); } } Handle<Map> GetMonomorphicJSObjectMap() override { return known_initial_map_; } void set_known_initial_map(Handle<Map> known_initial_map) { known_initial_map_ = known_initial_map; } bool IsNewSpaceAllocation() const { return (flags_ & ALLOCATE_IN_NEW_SPACE) != 0; } bool IsOldSpaceAllocation() const { return (flags_ & ALLOCATE_IN_OLD_SPACE) != 0; } bool MustAllocateDoubleAligned() const { return (flags_ & ALLOCATE_DOUBLE_ALIGNED) != 0; } bool MustPrefillWithFiller() const { return (flags_ & PREFILL_WITH_FILLER) != 0; } void MakePrefillWithFiller() { flags_ = static_cast<HAllocate::Flags>(flags_ | PREFILL_WITH_FILLER); } void MakeDoubleAligned() { flags_ = static_cast<HAllocate::Flags>(flags_ | ALLOCATE_DOUBLE_ALIGNED); } void MakeAllocationFoldingDominator() { flags_ = static_cast<HAllocate::Flags>(flags_ | ALLOCATION_FOLDING_DOMINATOR); } bool IsAllocationFoldingDominator() const { return (flags_ & ALLOCATION_FOLDING_DOMINATOR) != 0; } void MakeFoldedAllocation(HAllocate* dominator) { flags_ = static_cast<HAllocate::Flags>(flags_ | ALLOCATION_FOLDED); ClearFlag(kTrackSideEffectDominators); ClearChangesFlag(kNewSpacePromotion); SetOperandAt(2, dominator); } bool IsAllocationFolded() const { return (flags_ & ALLOCATION_FOLDED) != 0; } bool HandleSideEffectDominator(GVNFlag side_effect, HValue* dominator) override; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(Allocate) private: enum Flags { ALLOCATE_IN_NEW_SPACE = 1 << 0, ALLOCATE_IN_OLD_SPACE = 1 << 2, ALLOCATE_DOUBLE_ALIGNED = 1 << 3, PREFILL_WITH_FILLER = 1 << 4, ALLOCATION_FOLDING_DOMINATOR = 1 << 5, ALLOCATION_FOLDED = 1 << 6 }; HAllocate( HValue* context, HValue* size, HType type, PretenureFlag pretenure_flag, InstanceType instance_type, HValue* dominator, Handle<AllocationSite> allocation_site = Handle<AllocationSite>::null()) : HTemplateInstruction<3>(type), flags_(ComputeFlags(pretenure_flag, instance_type)) { SetOperandAt(0, context); UpdateSize(size); SetOperandAt(2, dominator); set_representation(Representation::Tagged()); SetFlag(kTrackSideEffectDominators); SetChangesFlag(kNewSpacePromotion); SetDependsOnFlag(kNewSpacePromotion); if (FLAG_trace_pretenuring) { PrintF("HAllocate with AllocationSite %p %s\n", allocation_site.is_null() ? static_cast<void*>(NULL) : static_cast<void*>(*allocation_site), pretenure_flag == TENURED ? "tenured" : "not tenured"); } } static Flags ComputeFlags(PretenureFlag pretenure_flag, InstanceType instance_type) { Flags flags = pretenure_flag == TENURED ? ALLOCATE_IN_OLD_SPACE : ALLOCATE_IN_NEW_SPACE; if (instance_type == FIXED_DOUBLE_ARRAY_TYPE) { flags = static_cast<Flags>(flags | ALLOCATE_DOUBLE_ALIGNED); } // We have to fill the allocated object with one word fillers if we do // not use allocation folding since some allocations may depend on each // other, i.e., have a pointer to each other. A GC in between these // allocations may leave such objects behind in a not completely initialized // state. if (!FLAG_use_gvn || !FLAG_use_allocation_folding) { flags = static_cast<Flags>(flags | PREFILL_WITH_FILLER); } return flags; } void UpdateSize(HValue* size) { SetOperandAt(1, size); } bool IsFoldable(HAllocate* allocate) { return (IsNewSpaceAllocation() && allocate->IsNewSpaceAllocation()) || (IsOldSpaceAllocation() && allocate->IsOldSpaceAllocation()); } Flags flags_; Handle<Map> known_initial_map_; }; class HStoreCodeEntry final : public HTemplateInstruction<2> { public: static HStoreCodeEntry* New(Isolate* isolate, Zone* zone, HValue* context, HValue* function, HValue* code) { return new(zone) HStoreCodeEntry(function, code); } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HValue* function() { return OperandAt(0); } HValue* code_object() { return OperandAt(1); } DECLARE_CONCRETE_INSTRUCTION(StoreCodeEntry) private: HStoreCodeEntry(HValue* function, HValue* code) { SetOperandAt(0, function); SetOperandAt(1, code); } }; class HInnerAllocatedObject final : public HTemplateInstruction<2> { public: static HInnerAllocatedObject* New(Isolate* isolate, Zone* zone, HValue* context, HValue* value, HValue* offset, HType type) { return new(zone) HInnerAllocatedObject(value, offset, type); } HValue* base_object() const { return OperandAt(0); } HValue* offset() const { return OperandAt(1); } Representation RequiredInputRepresentation(int index) override { return index == 0 ? Representation::Tagged() : Representation::Integer32(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(InnerAllocatedObject) private: HInnerAllocatedObject(HValue* value, HValue* offset, HType type) : HTemplateInstruction<2>(type) { DCHECK(value->IsAllocate()); DCHECK(type.IsHeapObject()); SetOperandAt(0, value); SetOperandAt(1, offset); set_representation(Representation::Tagged()); } }; inline bool StoringValueNeedsWriteBarrier(HValue* value) { return !value->type().IsSmi() && !value->type().IsNull() && !value->type().IsBoolean() && !value->type().IsUndefined() && !(value->IsConstant() && HConstant::cast(value)->ImmortalImmovable()); } inline bool ReceiverObjectNeedsWriteBarrier(HValue* object, HValue* value, HValue* dominator) { // There may be multiple inner allocates dominated by one allocate. while (object->IsInnerAllocatedObject()) { object = HInnerAllocatedObject::cast(object)->base_object(); } if (object->IsAllocate()) { HAllocate* allocate = HAllocate::cast(object); if (allocate->IsAllocationFolded()) { HValue* dominator = allocate->allocation_folding_dominator(); // There is no guarantee that all allocations are folded together because // GVN performs a fixpoint. if (HAllocate::cast(dominator)->IsAllocationFoldingDominator()) { object = dominator; } } } if (object->IsConstant() && HConstant::cast(object)->HasExternalReferenceValue()) { // Stores to external references require no write barriers return false; } // We definitely need a write barrier unless the object is the allocation // dominator. if (object == dominator && object->IsAllocate()) { // Stores to new space allocations require no write barriers. if (HAllocate::cast(object)->IsNewSpaceAllocation()) { return false; } } return true; } inline PointersToHereCheck PointersToHereCheckForObject(HValue* object, HValue* dominator) { while (object->IsInnerAllocatedObject()) { object = HInnerAllocatedObject::cast(object)->base_object(); } if (object == dominator && object->IsAllocate() && HAllocate::cast(object)->IsNewSpaceAllocation()) { return kPointersToHereAreAlwaysInteresting; } return kPointersToHereMaybeInteresting; } class HLoadContextSlot final : public HUnaryOperation { public: enum Mode { // Perform a normal load of the context slot without checking its value. kNoCheck, // Load and check the value of the context slot. Deoptimize if it's the // hole value. This is used for checking for loading of uninitialized // harmony bindings where we deoptimize into full-codegen generated code // which will subsequently throw a reference error. kCheckDeoptimize }; HLoadContextSlot(HValue* context, int slot_index, Mode mode) : HUnaryOperation(context), slot_index_(slot_index), mode_(mode) { set_representation(Representation::Tagged()); SetFlag(kUseGVN); SetDependsOnFlag(kContextSlots); } int slot_index() const { return slot_index_; } Mode mode() const { return mode_; } bool DeoptimizesOnHole() { return mode_ == kCheckDeoptimize; } bool RequiresHoleCheck() const { return mode_ != kNoCheck; } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(LoadContextSlot) protected: bool DataEquals(HValue* other) override { HLoadContextSlot* b = HLoadContextSlot::cast(other); return (slot_index() == b->slot_index()); } private: bool IsDeletable() const override { return !RequiresHoleCheck(); } int slot_index_; Mode mode_; }; class HStoreContextSlot final : public HTemplateInstruction<2> { public: enum Mode { // Perform a normal store to the context slot without checking its previous // value. kNoCheck, // Check the previous value of the context slot and deoptimize if it's the // hole value. This is used for checking for assignments to uninitialized // harmony bindings where we deoptimize into full-codegen generated code // which will subsequently throw a reference error. kCheckDeoptimize }; DECLARE_INSTRUCTION_FACTORY_P4(HStoreContextSlot, HValue*, int, Mode, HValue*); HValue* context() const { return OperandAt(0); } HValue* value() const { return OperandAt(1); } int slot_index() const { return slot_index_; } Mode mode() const { return mode_; } bool NeedsWriteBarrier() { return StoringValueNeedsWriteBarrier(value()); } bool DeoptimizesOnHole() { return mode_ == kCheckDeoptimize; } bool RequiresHoleCheck() { return mode_ != kNoCheck; } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(StoreContextSlot) private: HStoreContextSlot(HValue* context, int slot_index, Mode mode, HValue* value) : slot_index_(slot_index), mode_(mode) { SetOperandAt(0, context); SetOperandAt(1, value); SetChangesFlag(kContextSlots); } int slot_index_; Mode mode_; }; // Represents an access to a portion of an object, such as the map pointer, // array elements pointer, etc, but not accesses to array elements themselves. class HObjectAccess final { public: inline bool IsInobject() const { return portion() != kBackingStore && portion() != kExternalMemory; } inline bool IsExternalMemory() const { return portion() == kExternalMemory; } inline bool IsStringLength() const { return portion() == kStringLengths; } inline bool IsMap() const { return portion() == kMaps; } inline int offset() const { return OffsetField::decode(value_); } inline Representation representation() const { return Representation::FromKind(RepresentationField::decode(value_)); } inline Handle<Name> name() const { return name_; } inline bool immutable() const { return ImmutableField::decode(value_); } // Returns true if access is being made to an in-object property that // was already added to the object. inline bool existing_inobject_property() const { return ExistingInobjectPropertyField::decode(value_); } inline HObjectAccess WithRepresentation(Representation representation) { return HObjectAccess(portion(), offset(), representation, name(), immutable(), existing_inobject_property()); } static HObjectAccess ForHeapNumberValue() { return HObjectAccess( kDouble, HeapNumber::kValueOffset, Representation::Double()); } static HObjectAccess ForHeapNumberValueLowestBits() { return HObjectAccess(kDouble, HeapNumber::kValueOffset, Representation::Integer32()); } static HObjectAccess ForHeapNumberValueHighestBits() { return HObjectAccess(kDouble, HeapNumber::kValueOffset + kIntSize, Representation::Integer32()); } static HObjectAccess ForOddballToNumber( Representation representation = Representation::Tagged()) { return HObjectAccess(kInobject, Oddball::kToNumberOffset, representation); } static HObjectAccess ForOddballTypeOf() { return HObjectAccess(kInobject, Oddball::kTypeOfOffset, Representation::HeapObject()); } static HObjectAccess ForElementsPointer() { return HObjectAccess(kElementsPointer, JSObject::kElementsOffset); } static HObjectAccess ForLiteralsPointer() { return HObjectAccess(kInobject, JSFunction::kLiteralsOffset); } static HObjectAccess ForNextFunctionLinkPointer() { return HObjectAccess(kInobject, JSFunction::kNextFunctionLinkOffset); } static HObjectAccess ForArrayLength(ElementsKind elements_kind) { return HObjectAccess( kArrayLengths, JSArray::kLengthOffset, IsFastElementsKind(elements_kind) ? Representation::Smi() : Representation::Tagged()); } static HObjectAccess ForAllocationSiteOffset(int offset); static HObjectAccess ForAllocationSiteList() { return HObjectAccess(kExternalMemory, 0, Representation::Tagged(), Handle<Name>::null(), false, false); } static HObjectAccess ForFixedArrayLength() { return HObjectAccess( kArrayLengths, FixedArray::kLengthOffset, Representation::Smi()); } static HObjectAccess ForFixedTypedArrayBaseBasePointer() { return HObjectAccess(kInobject, FixedTypedArrayBase::kBasePointerOffset, Representation::Tagged()); } static HObjectAccess ForFixedTypedArrayBaseExternalPointer() { return HObjectAccess::ForObservableJSObjectOffset( FixedTypedArrayBase::kExternalPointerOffset, Representation::External()); } static HObjectAccess ForStringHashField() { return HObjectAccess(kInobject, String::kHashFieldOffset, Representation::Integer32()); } static HObjectAccess ForStringLength() { STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue); return HObjectAccess( kStringLengths, String::kLengthOffset, Representation::Smi()); } static HObjectAccess ForConsStringFirst() { return HObjectAccess(kInobject, ConsString::kFirstOffset); } static HObjectAccess ForConsStringSecond() { return HObjectAccess(kInobject, ConsString::kSecondOffset); } static HObjectAccess ForPropertiesPointer() { return HObjectAccess(kInobject, JSObject::kPropertiesOffset); } static HObjectAccess ForPrototypeOrInitialMap() { return HObjectAccess(kInobject, JSFunction::kPrototypeOrInitialMapOffset); } static HObjectAccess ForSharedFunctionInfoPointer() { return HObjectAccess(kInobject, JSFunction::kSharedFunctionInfoOffset); } static HObjectAccess ForCodeEntryPointer() { return HObjectAccess(kInobject, JSFunction::kCodeEntryOffset); } static HObjectAccess ForCodeOffset() { return HObjectAccess(kInobject, SharedFunctionInfo::kCodeOffset); } static HObjectAccess ForOptimizedCodeMap() { return HObjectAccess(kInobject, SharedFunctionInfo::kOptimizedCodeMapOffset); } static HObjectAccess ForFunctionContextPointer() { return HObjectAccess(kInobject, JSFunction::kContextOffset); } static HObjectAccess ForMap() { return HObjectAccess(kMaps, JSObject::kMapOffset); } static HObjectAccess ForPrototype() { return HObjectAccess(kMaps, Map::kPrototypeOffset); } static HObjectAccess ForMapAsInteger32() { return HObjectAccess(kMaps, JSObject::kMapOffset, Representation::Integer32()); } static HObjectAccess ForMapInObjectPropertiesOrConstructorFunctionIndex() { return HObjectAccess( kInobject, Map::kInObjectPropertiesOrConstructorFunctionIndexOffset, Representation::UInteger8()); } static HObjectAccess ForMapInstanceType() { return HObjectAccess(kInobject, Map::kInstanceTypeOffset, Representation::UInteger8()); } static HObjectAccess ForMapInstanceSize() { return HObjectAccess(kInobject, Map::kInstanceSizeOffset, Representation::UInteger8()); } static HObjectAccess ForMapBitField() { return HObjectAccess(kInobject, Map::kBitFieldOffset, Representation::UInteger8()); } static HObjectAccess ForMapBitField2() { return HObjectAccess(kInobject, Map::kBitField2Offset, Representation::UInteger8()); } static HObjectAccess ForMapBitField3() { return HObjectAccess(kInobject, Map::kBitField3Offset, Representation::Integer32()); } static HObjectAccess ForMapDescriptors() { return HObjectAccess(kInobject, Map::kDescriptorsOffset); } static HObjectAccess ForNameHashField() { return HObjectAccess(kInobject, Name::kHashFieldOffset, Representation::Integer32()); } static HObjectAccess ForMapInstanceTypeAndBitField() { STATIC_ASSERT((Map::kInstanceTypeAndBitFieldOffset & 1) == 0); // Ensure the two fields share one 16-bit word, endian-independent. STATIC_ASSERT((Map::kBitFieldOffset & ~1) == (Map::kInstanceTypeOffset & ~1)); return HObjectAccess(kInobject, Map::kInstanceTypeAndBitFieldOffset, Representation::UInteger16()); } static HObjectAccess ForPropertyCellValue() { return HObjectAccess(kInobject, PropertyCell::kValueOffset); } static HObjectAccess ForPropertyCellDetails() { return HObjectAccess(kInobject, PropertyCell::kDetailsOffset, Representation::Smi()); } static HObjectAccess ForCellValue() { return HObjectAccess(kInobject, Cell::kValueOffset); } static HObjectAccess ForWeakCellValue() { return HObjectAccess(kInobject, WeakCell::kValueOffset); } static HObjectAccess ForWeakCellNext() { return HObjectAccess(kInobject, WeakCell::kNextOffset); } static HObjectAccess ForAllocationMementoSite() { return HObjectAccess(kInobject, AllocationMemento::kAllocationSiteOffset); } static HObjectAccess ForCounter() { return HObjectAccess(kExternalMemory, 0, Representation::Integer32(), Handle<Name>::null(), false, false); } static HObjectAccess ForExternalUInteger8() { return HObjectAccess(kExternalMemory, 0, Representation::UInteger8(), Handle<Name>::null(), false, false); } static HObjectAccess ForBoundTargetFunction() { return HObjectAccess(kInobject, JSBoundFunction::kBoundTargetFunctionOffset); } static HObjectAccess ForBoundThis() { return HObjectAccess(kInobject, JSBoundFunction::kBoundThisOffset); } static HObjectAccess ForBoundArguments() { return HObjectAccess(kInobject, JSBoundFunction::kBoundArgumentsOffset); } // Create an access to an offset in a fixed array header. static HObjectAccess ForFixedArrayHeader(int offset); // Create an access to an in-object property in a JSObject. // This kind of access must be used when the object |map| is known and // in-object properties are being accessed. Accesses of the in-object // properties can have different semantics depending on whether corresponding // property was added to the map or not. static HObjectAccess ForMapAndOffset(Handle<Map> map, int offset, Representation representation = Representation::Tagged()); // Create an access to an in-object property in a JSObject. // This kind of access can be used for accessing object header fields or // in-object properties if the map of the object is not known. static HObjectAccess ForObservableJSObjectOffset(int offset, Representation representation = Representation::Tagged()) { return ForMapAndOffset(Handle<Map>::null(), offset, representation); } // Create an access to an in-object property in a JSArray. static HObjectAccess ForJSArrayOffset(int offset); static HObjectAccess ForContextSlot(int index); static HObjectAccess ForScriptContext(int index); // Create an access to the backing store of an object. static HObjectAccess ForBackingStoreOffset(int offset, Representation representation = Representation::Tagged()); // Create an access to a resolved field (in-object or backing store). static HObjectAccess ForField(Handle<Map> map, int index, Representation representation, Handle<Name> name); static HObjectAccess ForJSTypedArrayLength() { return HObjectAccess::ForObservableJSObjectOffset( JSTypedArray::kLengthOffset); } static HObjectAccess ForJSArrayBufferBackingStore() { return HObjectAccess::ForObservableJSObjectOffset( JSArrayBuffer::kBackingStoreOffset, Representation::External()); } static HObjectAccess ForJSArrayBufferByteLength() { return HObjectAccess::ForObservableJSObjectOffset( JSArrayBuffer::kByteLengthOffset, Representation::Tagged()); } static HObjectAccess ForJSArrayBufferBitField() { return HObjectAccess::ForObservableJSObjectOffset( JSArrayBuffer::kBitFieldOffset, Representation::Integer32()); } static HObjectAccess ForJSArrayBufferBitFieldSlot() { return HObjectAccess::ForObservableJSObjectOffset( JSArrayBuffer::kBitFieldSlot, Representation::Smi()); } static HObjectAccess ForJSArrayBufferViewBuffer() { return HObjectAccess::ForObservableJSObjectOffset( JSArrayBufferView::kBufferOffset); } static HObjectAccess ForJSArrayBufferViewByteOffset() { return HObjectAccess::ForObservableJSObjectOffset( JSArrayBufferView::kByteOffsetOffset); } static HObjectAccess ForJSArrayBufferViewByteLength() { return HObjectAccess::ForObservableJSObjectOffset( JSArrayBufferView::kByteLengthOffset); } static HObjectAccess ForJSGlobalObjectNativeContext() { return HObjectAccess(kInobject, JSGlobalObject::kNativeContextOffset); } static HObjectAccess ForJSRegExpFlags() { return HObjectAccess(kInobject, JSRegExp::kFlagsOffset); } static HObjectAccess ForJSRegExpSource() { return HObjectAccess(kInobject, JSRegExp::kSourceOffset); } static HObjectAccess ForJSCollectionTable() { return HObjectAccess::ForObservableJSObjectOffset( JSCollection::kTableOffset); } template <typename CollectionType> static HObjectAccess ForOrderedHashTableNumberOfBuckets() { return HObjectAccess(kInobject, CollectionType::kNumberOfBucketsOffset, Representation::Smi()); } template <typename CollectionType> static HObjectAccess ForOrderedHashTableNumberOfElements() { return HObjectAccess(kInobject, CollectionType::kNumberOfElementsOffset, Representation::Smi()); } template <typename CollectionType> static HObjectAccess ForOrderedHashTableNumberOfDeletedElements() { return HObjectAccess(kInobject, CollectionType::kNumberOfDeletedElementsOffset, Representation::Smi()); } template <typename CollectionType> static HObjectAccess ForOrderedHashTableNextTable() { return HObjectAccess(kInobject, CollectionType::kNextTableOffset); } template <typename CollectionType> static HObjectAccess ForOrderedHashTableBucket(int bucket) { return HObjectAccess(kInobject, CollectionType::kHashTableStartOffset + (bucket * kPointerSize), Representation::Smi()); } // Access into the data table of an OrderedHashTable with a // known-at-compile-time bucket count. template <typename CollectionType, int kBucketCount> static HObjectAccess ForOrderedHashTableDataTableIndex(int index) { return HObjectAccess(kInobject, CollectionType::kHashTableStartOffset + (kBucketCount * kPointerSize) + (index * kPointerSize)); } inline bool Equals(HObjectAccess that) const { return value_ == that.value_; // portion and offset must match } protected: void SetGVNFlags(HValue *instr, PropertyAccessType access_type); private: // internal use only; different parts of an object or array enum Portion { kMaps, // map of an object kArrayLengths, // the length of an array kStringLengths, // the length of a string kElementsPointer, // elements pointer kBackingStore, // some field in the backing store kDouble, // some double field kInobject, // some other in-object field kExternalMemory // some field in external memory }; HObjectAccess() : value_(0) {} HObjectAccess(Portion portion, int offset, Representation representation = Representation::Tagged(), Handle<Name> name = Handle<Name>::null(), bool immutable = false, bool existing_inobject_property = true) : value_(PortionField::encode(portion) | RepresentationField::encode(representation.kind()) | ImmutableField::encode(immutable ? 1 : 0) | ExistingInobjectPropertyField::encode( existing_inobject_property ? 1 : 0) | OffsetField::encode(offset)), name_(name) { // assert that the fields decode correctly DCHECK(this->offset() == offset); DCHECK(this->portion() == portion); DCHECK(this->immutable() == immutable); DCHECK(this->existing_inobject_property() == existing_inobject_property); DCHECK(RepresentationField::decode(value_) == representation.kind()); DCHECK(!this->existing_inobject_property() || IsInobject()); } class PortionField : public BitField<Portion, 0, 3> {}; class RepresentationField : public BitField<Representation::Kind, 3, 4> {}; class ImmutableField : public BitField<bool, 7, 1> {}; class ExistingInobjectPropertyField : public BitField<bool, 8, 1> {}; class OffsetField : public BitField<int, 9, 23> {}; uint32_t value_; // encodes portion, representation, immutable, and offset Handle<Name> name_; friend class HLoadNamedField; friend class HStoreNamedField; friend class SideEffectsTracker; friend std::ostream& operator<<(std::ostream& os, const HObjectAccess& access); inline Portion portion() const { return PortionField::decode(value_); } }; std::ostream& operator<<(std::ostream& os, const HObjectAccess& access); class HLoadNamedField final : public HTemplateInstruction<2> { public: DECLARE_INSTRUCTION_FACTORY_P3(HLoadNamedField, HValue*, HValue*, HObjectAccess); DECLARE_INSTRUCTION_FACTORY_P5(HLoadNamedField, HValue*, HValue*, HObjectAccess, const UniqueSet<Map>*, HType); HValue* object() const { return OperandAt(0); } HValue* dependency() const { DCHECK(HasDependency()); return OperandAt(1); } bool HasDependency() const { return OperandAt(0) != OperandAt(1); } HObjectAccess access() const { return access_; } Representation field_representation() const { return access_.representation(); } const UniqueSet<Map>* maps() const { return maps_; } bool HasEscapingOperandAt(int index) override { return false; } bool HasOutOfBoundsAccess(int size) override { return !access().IsInobject() || access().offset() >= size; } Representation RequiredInputRepresentation(int index) override { if (index == 0) { // object must be external in case of external memory access return access().IsExternalMemory() ? Representation::External() : Representation::Tagged(); } DCHECK(index == 1); return Representation::None(); } Range* InferRange(Zone* zone) override; std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT bool CanBeReplacedWith(HValue* other) const { if (!CheckFlag(HValue::kCantBeReplaced)) return false; if (!type().Equals(other->type())) return false; if (!representation().Equals(other->representation())) return false; if (!other->IsLoadNamedField()) return true; HLoadNamedField* that = HLoadNamedField::cast(other); if (this->maps_ == that->maps_) return true; if (this->maps_ == NULL || that->maps_ == NULL) return false; return this->maps_->IsSubset(that->maps_); } DECLARE_CONCRETE_INSTRUCTION(LoadNamedField) protected: bool DataEquals(HValue* other) override { HLoadNamedField* that = HLoadNamedField::cast(other); if (!this->access_.Equals(that->access_)) return false; if (this->maps_ == that->maps_) return true; return (this->maps_ != NULL && that->maps_ != NULL && this->maps_->Equals(that->maps_)); } private: HLoadNamedField(HValue* object, HValue* dependency, HObjectAccess access) : access_(access), maps_(NULL) { DCHECK_NOT_NULL(object); SetOperandAt(0, object); SetOperandAt(1, dependency ? dependency : object); Representation representation = access.representation(); if (representation.IsInteger8() || representation.IsUInteger8() || representation.IsInteger16() || representation.IsUInteger16()) { set_representation(Representation::Integer32()); } else if (representation.IsSmi()) { set_type(HType::Smi()); if (SmiValuesAre32Bits()) { set_representation(Representation::Integer32()); } else { set_representation(representation); } } else if (representation.IsDouble() || representation.IsExternal() || representation.IsInteger32()) { set_representation(representation); } else if (representation.IsHeapObject()) { set_type(HType::HeapObject()); set_representation(Representation::Tagged()); } else { set_representation(Representation::Tagged()); } access.SetGVNFlags(this, LOAD); } HLoadNamedField(HValue* object, HValue* dependency, HObjectAccess access, const UniqueSet<Map>* maps, HType type) : HTemplateInstruction<2>(type), access_(access), maps_(maps) { DCHECK_NOT_NULL(maps); DCHECK_NE(0, maps->size()); DCHECK_NOT_NULL(object); SetOperandAt(0, object); SetOperandAt(1, dependency ? dependency : object); DCHECK(access.representation().IsHeapObject()); DCHECK(type.IsHeapObject()); set_representation(Representation::Tagged()); access.SetGVNFlags(this, LOAD); } bool IsDeletable() const override { return true; } HObjectAccess access_; const UniqueSet<Map>* maps_; }; class HLoadFunctionPrototype final : public HUnaryOperation { public: DECLARE_INSTRUCTION_FACTORY_P1(HLoadFunctionPrototype, HValue*); HValue* function() { return OperandAt(0); } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(LoadFunctionPrototype) protected: bool DataEquals(HValue* other) override { return true; } private: explicit HLoadFunctionPrototype(HValue* function) : HUnaryOperation(function) { set_representation(Representation::Tagged()); SetFlag(kUseGVN); SetDependsOnFlag(kCalls); } }; class ArrayInstructionInterface { public: virtual HValue* GetKey() = 0; virtual void SetKey(HValue* key) = 0; virtual ElementsKind elements_kind() const = 0; // TryIncreaseBaseOffset returns false if overflow would result. virtual bool TryIncreaseBaseOffset(uint32_t increase_by_value) = 0; virtual bool IsDehoisted() const = 0; virtual void SetDehoisted(bool is_dehoisted) = 0; virtual ~ArrayInstructionInterface() { } static Representation KeyedAccessIndexRequirement(Representation r) { return r.IsInteger32() || SmiValuesAre32Bits() ? Representation::Integer32() : Representation::Smi(); } }; static const int kDefaultKeyedHeaderOffsetSentinel = -1; enum LoadKeyedHoleMode { NEVER_RETURN_HOLE, ALLOW_RETURN_HOLE, CONVERT_HOLE_TO_UNDEFINED }; class HLoadKeyed final : public HTemplateInstruction<4>, public ArrayInstructionInterface { public: DECLARE_INSTRUCTION_FACTORY_P5(HLoadKeyed, HValue*, HValue*, HValue*, HValue*, ElementsKind); DECLARE_INSTRUCTION_FACTORY_P6(HLoadKeyed, HValue*, HValue*, HValue*, HValue*, ElementsKind, LoadKeyedHoleMode); DECLARE_INSTRUCTION_FACTORY_P7(HLoadKeyed, HValue*, HValue*, HValue*, HValue*, ElementsKind, LoadKeyedHoleMode, int); bool is_fixed_typed_array() const { return IsFixedTypedArrayElementsKind(elements_kind()); } HValue* elements() const { return OperandAt(0); } HValue* key() const { return OperandAt(1); } HValue* dependency() const { DCHECK(HasDependency()); return OperandAt(2); } bool HasDependency() const { return OperandAt(0) != OperandAt(2); } HValue* backing_store_owner() const { DCHECK(HasBackingStoreOwner()); return OperandAt(3); } bool HasBackingStoreOwner() const { return OperandAt(0) != OperandAt(3); } uint32_t base_offset() const { return BaseOffsetField::decode(bit_field_); } bool TryIncreaseBaseOffset(uint32_t increase_by_value) override; HValue* GetKey() override { return key(); } void SetKey(HValue* key) override { SetOperandAt(1, key); } bool IsDehoisted() const override { return IsDehoistedField::decode(bit_field_); } void SetDehoisted(bool is_dehoisted) override { bit_field_ = IsDehoistedField::update(bit_field_, is_dehoisted); } ElementsKind elements_kind() const override { return ElementsKindField::decode(bit_field_); } LoadKeyedHoleMode hole_mode() const { return HoleModeField::decode(bit_field_); } Representation RequiredInputRepresentation(int index) override { // kind_fast: tagged[int32] (none) // kind_double: tagged[int32] (none) // kind_fixed_typed_array: external[int32] (none) // kind_external: external[int32] (none) if (index == 0) { return is_fixed_typed_array() ? Representation::External() : Representation::Tagged(); } if (index == 1) { return ArrayInstructionInterface::KeyedAccessIndexRequirement( OperandAt(1)->representation()); } if (index == 2) { return Representation::None(); } DCHECK_EQ(3, index); return HasBackingStoreOwner() ? Representation::Tagged() : Representation::None(); } Representation observed_input_representation(int index) override { return RequiredInputRepresentation(index); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT bool UsesMustHandleHole() const; bool AllUsesCanTreatHoleAsNaN() const; bool RequiresHoleCheck() const; Range* InferRange(Zone* zone) override; DECLARE_CONCRETE_INSTRUCTION(LoadKeyed) protected: bool DataEquals(HValue* other) override { if (!other->IsLoadKeyed()) return false; HLoadKeyed* other_load = HLoadKeyed::cast(other); if (base_offset() != other_load->base_offset()) return false; return elements_kind() == other_load->elements_kind(); } private: HLoadKeyed(HValue* obj, HValue* key, HValue* dependency, HValue* backing_store_owner, ElementsKind elements_kind, LoadKeyedHoleMode mode = NEVER_RETURN_HOLE, int offset = kDefaultKeyedHeaderOffsetSentinel) : bit_field_(0) { offset = offset == kDefaultKeyedHeaderOffsetSentinel ? GetDefaultHeaderSizeForElementsKind(elements_kind) : offset; bit_field_ = ElementsKindField::encode(elements_kind) | HoleModeField::encode(mode) | BaseOffsetField::encode(offset); SetOperandAt(0, obj); SetOperandAt(1, key); SetOperandAt(2, dependency != nullptr ? dependency : obj); SetOperandAt(3, backing_store_owner != nullptr ? backing_store_owner : obj); DCHECK_EQ(HasBackingStoreOwner(), is_fixed_typed_array()); if (!is_fixed_typed_array()) { // I can detect the case between storing double (holey and fast) and // smi/object by looking at elements_kind_. DCHECK(IsFastSmiOrObjectElementsKind(elements_kind) || IsFastDoubleElementsKind(elements_kind)); if (IsFastSmiOrObjectElementsKind(elements_kind)) { if (IsFastSmiElementsKind(elements_kind) && (!IsHoleyElementsKind(elements_kind) || mode == NEVER_RETURN_HOLE)) { set_type(HType::Smi()); if (SmiValuesAre32Bits() && !RequiresHoleCheck()) { set_representation(Representation::Integer32()); } else { set_representation(Representation::Smi()); } } else { set_representation(Representation::Tagged()); } SetDependsOnFlag(kArrayElements); } else { set_representation(Representation::Double()); SetDependsOnFlag(kDoubleArrayElements); } } else { if (elements_kind == FLOAT32_ELEMENTS || elements_kind == FLOAT64_ELEMENTS) { set_representation(Representation::Double()); } else { set_representation(Representation::Integer32()); } if (is_fixed_typed_array()) { SetDependsOnFlag(kExternalMemory); SetDependsOnFlag(kTypedArrayElements); } else { UNREACHABLE(); } // Native code could change the specialized array. SetDependsOnFlag(kCalls); } SetFlag(kUseGVN); } bool IsDeletable() const override { return !RequiresHoleCheck(); } // Establish some checks around our packed fields enum LoadKeyedBits { kBitsForElementsKind = 5, kBitsForHoleMode = 2, kBitsForBaseOffset = 24, kBitsForIsDehoisted = 1, kStartElementsKind = 0, kStartHoleMode = kStartElementsKind + kBitsForElementsKind, kStartBaseOffset = kStartHoleMode + kBitsForHoleMode, kStartIsDehoisted = kStartBaseOffset + kBitsForBaseOffset }; STATIC_ASSERT((kBitsForElementsKind + kBitsForHoleMode + kBitsForBaseOffset + kBitsForIsDehoisted) <= sizeof(uint32_t) * 8); STATIC_ASSERT(kElementsKindCount <= (1 << kBitsForElementsKind)); class ElementsKindField: public BitField<ElementsKind, kStartElementsKind, kBitsForElementsKind> {}; // NOLINT class HoleModeField: public BitField<LoadKeyedHoleMode, kStartHoleMode, kBitsForHoleMode> {}; // NOLINT class BaseOffsetField: public BitField<uint32_t, kStartBaseOffset, kBitsForBaseOffset> {}; // NOLINT class IsDehoistedField: public BitField<bool, kStartIsDehoisted, kBitsForIsDehoisted> {}; // NOLINT uint32_t bit_field_; }; // Indicates whether the store is a store to an entry that was previously // initialized or not. enum StoreFieldOrKeyedMode { // The entry could be either previously initialized or not. INITIALIZING_STORE, // At the time of this store it is guaranteed that the entry is already // initialized. STORE_TO_INITIALIZED_ENTRY }; class HStoreNamedField final : public HTemplateInstruction<3> { public: DECLARE_INSTRUCTION_FACTORY_P3(HStoreNamedField, HValue*, HObjectAccess, HValue*); DECLARE_INSTRUCTION_FACTORY_P4(HStoreNamedField, HValue*, HObjectAccess, HValue*, StoreFieldOrKeyedMode); DECLARE_CONCRETE_INSTRUCTION(StoreNamedField) bool HasEscapingOperandAt(int index) override { return index == 1; } bool HasOutOfBoundsAccess(int size) override { return !access().IsInobject() || access().offset() >= size; } Representation RequiredInputRepresentation(int index) override { if (index == 0 && access().IsExternalMemory()) { // object must be external in case of external memory access return Representation::External(); } else if (index == 1) { if (field_representation().IsInteger8() || field_representation().IsUInteger8() || field_representation().IsInteger16() || field_representation().IsUInteger16() || field_representation().IsInteger32()) { return Representation::Integer32(); } else if (field_representation().IsDouble()) { return field_representation(); } else if (field_representation().IsSmi()) { if (SmiValuesAre32Bits() && store_mode() == STORE_TO_INITIALIZED_ENTRY) { return Representation::Integer32(); } return field_representation(); } else if (field_representation().IsExternal()) { return Representation::External(); } } return Representation::Tagged(); } bool HandleSideEffectDominator(GVNFlag side_effect, HValue* dominator) override { DCHECK(side_effect == kNewSpacePromotion); if (!FLAG_use_write_barrier_elimination) return false; dominator_ = dominator; return false; } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HValue* object() const { return OperandAt(0); } HValue* value() const { return OperandAt(1); } HValue* transition() const { return OperandAt(2); } HObjectAccess access() const { return access_; } HValue* dominator() const { return dominator_; } bool has_transition() const { return HasTransitionField::decode(bit_field_); } StoreFieldOrKeyedMode store_mode() const { return StoreModeField::decode(bit_field_); } Handle<Map> transition_map() const { if (has_transition()) { return Handle<Map>::cast( HConstant::cast(transition())->handle(isolate())); } else { return Handle<Map>(); } } void SetTransition(HConstant* transition) { DCHECK(!has_transition()); // Only set once. SetOperandAt(2, transition); bit_field_ = HasTransitionField::update(bit_field_, true); SetChangesFlag(kMaps); } bool NeedsWriteBarrier() const { DCHECK(!field_representation().IsDouble() || (FLAG_unbox_double_fields && access_.IsInobject()) || !has_transition()); if (field_representation().IsDouble()) return false; if (field_representation().IsSmi()) return false; if (field_representation().IsInteger32()) return false; if (field_representation().IsExternal()) return false; return StoringValueNeedsWriteBarrier(value()) && ReceiverObjectNeedsWriteBarrier(object(), value(), dominator()); } bool NeedsWriteBarrierForMap() { return ReceiverObjectNeedsWriteBarrier(object(), transition(), dominator()); } SmiCheck SmiCheckForWriteBarrier() const { if (field_representation().IsHeapObject()) return OMIT_SMI_CHECK; if (value()->type().IsHeapObject()) return OMIT_SMI_CHECK; return INLINE_SMI_CHECK; } PointersToHereCheck PointersToHereCheckForValue() const { return PointersToHereCheckForObject(value(), dominator()); } Representation field_representation() const { return access_.representation(); } void UpdateValue(HValue* value) { SetOperandAt(1, value); } bool CanBeReplacedWith(HStoreNamedField* that) const { if (!this->access().Equals(that->access())) return false; if (SmiValuesAre32Bits() && this->field_representation().IsSmi() && this->store_mode() == INITIALIZING_STORE && that->store_mode() == STORE_TO_INITIALIZED_ENTRY) { // We cannot replace an initializing store to a smi field with a store to // an initialized entry on 64-bit architectures (with 32-bit smis). return false; } return true; } private: HStoreNamedField(HValue* obj, HObjectAccess access, HValue* val, StoreFieldOrKeyedMode store_mode = INITIALIZING_STORE) : access_(access), dominator_(NULL), bit_field_(HasTransitionField::encode(false) | StoreModeField::encode(store_mode)) { // Stores to a non existing in-object property are allowed only to the // newly allocated objects (via HAllocate or HInnerAllocatedObject). DCHECK(!access.IsInobject() || access.existing_inobject_property() || obj->IsAllocate() || obj->IsInnerAllocatedObject()); SetOperandAt(0, obj); SetOperandAt(1, val); SetOperandAt(2, obj); access.SetGVNFlags(this, STORE); } class HasTransitionField : public BitField<bool, 0, 1> {}; class StoreModeField : public BitField<StoreFieldOrKeyedMode, 1, 1> {}; HObjectAccess access_; HValue* dominator_; uint32_t bit_field_; }; class HStoreKeyed final : public HTemplateInstruction<4>, public ArrayInstructionInterface { public: DECLARE_INSTRUCTION_FACTORY_P5(HStoreKeyed, HValue*, HValue*, HValue*, HValue*, ElementsKind); DECLARE_INSTRUCTION_FACTORY_P6(HStoreKeyed, HValue*, HValue*, HValue*, HValue*, ElementsKind, StoreFieldOrKeyedMode); DECLARE_INSTRUCTION_FACTORY_P7(HStoreKeyed, HValue*, HValue*, HValue*, HValue*, ElementsKind, StoreFieldOrKeyedMode, int); Representation RequiredInputRepresentation(int index) override { // kind_fast: tagged[int32] = tagged // kind_double: tagged[int32] = double // kind_smi : tagged[int32] = smi // kind_fixed_typed_array: tagged[int32] = (double | int32) // kind_external: external[int32] = (double | int32) if (index == 0) { return is_fixed_typed_array() ? Representation::External() : Representation::Tagged(); } else if (index == 1) { return ArrayInstructionInterface::KeyedAccessIndexRequirement( OperandAt(1)->representation()); } else if (index == 2) { return RequiredValueRepresentation(elements_kind(), store_mode()); } DCHECK_EQ(3, index); return HasBackingStoreOwner() ? Representation::Tagged() : Representation::None(); } static Representation RequiredValueRepresentation( ElementsKind kind, StoreFieldOrKeyedMode mode) { if (IsDoubleOrFloatElementsKind(kind)) { return Representation::Double(); } if (kind == FAST_SMI_ELEMENTS && SmiValuesAre32Bits() && mode == STORE_TO_INITIALIZED_ENTRY) { return Representation::Integer32(); } if (IsFastSmiElementsKind(kind)) { return Representation::Smi(); } if (IsFixedTypedArrayElementsKind(kind)) { return Representation::Integer32(); } return Representation::Tagged(); } bool is_fixed_typed_array() const { return IsFixedTypedArrayElementsKind(elements_kind()); } Representation observed_input_representation(int index) override { if (index != 2) return RequiredInputRepresentation(index); if (IsUninitialized()) { return Representation::None(); } Representation r = RequiredValueRepresentation(elements_kind(), store_mode()); // For fast object elements kinds, don't assume anything. if (r.IsTagged()) return Representation::None(); return r; } HValue* elements() const { return OperandAt(0); } HValue* key() const { return OperandAt(1); } HValue* value() const { return OperandAt(2); } HValue* backing_store_owner() const { DCHECK(HasBackingStoreOwner()); return OperandAt(3); } bool HasBackingStoreOwner() const { return OperandAt(0) != OperandAt(3); } bool value_is_smi() const { return IsFastSmiElementsKind(elements_kind()); } StoreFieldOrKeyedMode store_mode() const { return StoreModeField::decode(bit_field_); } ElementsKind elements_kind() const override { return ElementsKindField::decode(bit_field_); } uint32_t base_offset() const { return base_offset_; } bool TryIncreaseBaseOffset(uint32_t increase_by_value) override; HValue* GetKey() override { return key(); } void SetKey(HValue* key) override { SetOperandAt(1, key); } bool IsDehoisted() const override { return IsDehoistedField::decode(bit_field_); } void SetDehoisted(bool is_dehoisted) override { bit_field_ = IsDehoistedField::update(bit_field_, is_dehoisted); } bool IsUninitialized() { return IsUninitializedField::decode(bit_field_); } void SetUninitialized(bool is_uninitialized) { bit_field_ = IsUninitializedField::update(bit_field_, is_uninitialized); } bool IsConstantHoleStore() { return value()->IsConstant() && HConstant::cast(value())->IsTheHole(); } bool HandleSideEffectDominator(GVNFlag side_effect, HValue* dominator) override { DCHECK(side_effect == kNewSpacePromotion); dominator_ = dominator; return false; } HValue* dominator() const { return dominator_; } bool NeedsWriteBarrier() { if (value_is_smi()) { return false; } else { return StoringValueNeedsWriteBarrier(value()) && ReceiverObjectNeedsWriteBarrier(elements(), value(), dominator()); } } PointersToHereCheck PointersToHereCheckForValue() const { return PointersToHereCheckForObject(value(), dominator()); } bool NeedsCanonicalization(); std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(StoreKeyed) private: HStoreKeyed(HValue* obj, HValue* key, HValue* val, HValue* backing_store_owner, ElementsKind elements_kind, StoreFieldOrKeyedMode store_mode = INITIALIZING_STORE, int offset = kDefaultKeyedHeaderOffsetSentinel) : base_offset_(offset == kDefaultKeyedHeaderOffsetSentinel ? GetDefaultHeaderSizeForElementsKind(elements_kind) : offset), bit_field_(IsDehoistedField::encode(false) | IsUninitializedField::encode(false) | StoreModeField::encode(store_mode) | ElementsKindField::encode(elements_kind)), dominator_(NULL) { SetOperandAt(0, obj); SetOperandAt(1, key); SetOperandAt(2, val); SetOperandAt(3, backing_store_owner != nullptr ? backing_store_owner : obj); DCHECK_EQ(HasBackingStoreOwner(), is_fixed_typed_array()); if (IsFastObjectElementsKind(elements_kind)) { SetFlag(kTrackSideEffectDominators); SetDependsOnFlag(kNewSpacePromotion); } if (IsFastDoubleElementsKind(elements_kind)) { SetChangesFlag(kDoubleArrayElements); } else if (IsFastSmiElementsKind(elements_kind)) { SetChangesFlag(kArrayElements); } else if (is_fixed_typed_array()) { SetChangesFlag(kTypedArrayElements); SetChangesFlag(kExternalMemory); SetFlag(kTruncatingToNumber); } else { SetChangesFlag(kArrayElements); } // {UNSIGNED_,}{BYTE,SHORT,INT}_ELEMENTS are truncating. if (elements_kind >= UINT8_ELEMENTS && elements_kind <= INT32_ELEMENTS) { SetFlag(kTruncatingToInt32); } } class IsDehoistedField : public BitField<bool, 0, 1> {}; class IsUninitializedField : public BitField<bool, 1, 1> {}; class StoreModeField : public BitField<StoreFieldOrKeyedMode, 2, 1> {}; class ElementsKindField : public BitField<ElementsKind, 3, 5> {}; uint32_t base_offset_; uint32_t bit_field_; HValue* dominator_; }; class HTransitionElementsKind final : public HTemplateInstruction<2> { public: inline static HTransitionElementsKind* New(Isolate* isolate, Zone* zone, HValue* context, HValue* object, Handle<Map> original_map, Handle<Map> transitioned_map) { return new(zone) HTransitionElementsKind(context, object, original_map, transitioned_map); } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HValue* object() const { return OperandAt(0); } HValue* context() const { return OperandAt(1); } Unique<Map> original_map() const { return original_map_; } Unique<Map> transitioned_map() const { return transitioned_map_; } ElementsKind from_kind() const { return FromElementsKindField::decode(bit_field_); } ElementsKind to_kind() const { return ToElementsKindField::decode(bit_field_); } bool map_is_stable() const { return MapIsStableField::decode(bit_field_); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(TransitionElementsKind) protected: bool DataEquals(HValue* other) override { HTransitionElementsKind* instr = HTransitionElementsKind::cast(other); return original_map_ == instr->original_map_ && transitioned_map_ == instr->transitioned_map_; } int RedefinedOperandIndex() override { return 0; } private: HTransitionElementsKind(HValue* context, HValue* object, Handle<Map> original_map, Handle<Map> transitioned_map) : original_map_(Unique<Map>(original_map)), transitioned_map_(Unique<Map>(transitioned_map)), bit_field_( FromElementsKindField::encode(original_map->elements_kind()) | ToElementsKindField::encode(transitioned_map->elements_kind()) | MapIsStableField::encode(transitioned_map->is_stable())) { SetOperandAt(0, object); SetOperandAt(1, context); SetFlag(kUseGVN); SetChangesFlag(kElementsKind); if (!IsSimpleMapChangeTransition(from_kind(), to_kind())) { SetChangesFlag(kElementsPointer); SetChangesFlag(kNewSpacePromotion); } set_representation(Representation::Tagged()); } class FromElementsKindField : public BitField<ElementsKind, 0, 5> {}; class ToElementsKindField : public BitField<ElementsKind, 5, 5> {}; class MapIsStableField : public BitField<bool, 10, 1> {}; Unique<Map> original_map_; Unique<Map> transitioned_map_; uint32_t bit_field_; }; class HStringAdd final : public HBinaryOperation { public: static HInstruction* New( Isolate* isolate, Zone* zone, HValue* context, HValue* left, HValue* right, PretenureFlag pretenure_flag = NOT_TENURED, StringAddFlags flags = STRING_ADD_CHECK_BOTH, Handle<AllocationSite> allocation_site = Handle<AllocationSite>::null()); StringAddFlags flags() const { return flags_; } PretenureFlag pretenure_flag() const { return pretenure_flag_; } Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT DECLARE_CONCRETE_INSTRUCTION(StringAdd) protected: bool DataEquals(HValue* other) override { return flags_ == HStringAdd::cast(other)->flags_ && pretenure_flag_ == HStringAdd::cast(other)->pretenure_flag_; } private: HStringAdd(HValue* context, HValue* left, HValue* right, PretenureFlag pretenure_flag, StringAddFlags flags, Handle<AllocationSite> allocation_site) : HBinaryOperation(context, left, right, HType::String()), flags_(flags), pretenure_flag_(pretenure_flag) { set_representation(Representation::Tagged()); if ((flags & STRING_ADD_CONVERT) == STRING_ADD_CONVERT) { SetAllSideEffects(); ClearFlag(kUseGVN); } else { SetChangesFlag(kNewSpacePromotion); SetFlag(kUseGVN); } SetDependsOnFlag(kMaps); if (FLAG_trace_pretenuring) { PrintF("HStringAdd with AllocationSite %p %s\n", allocation_site.is_null() ? static_cast<void*>(NULL) : static_cast<void*>(*allocation_site), pretenure_flag == TENURED ? "tenured" : "not tenured"); } } bool IsDeletable() const final { return (flags_ & STRING_ADD_CONVERT) != STRING_ADD_CONVERT; } const StringAddFlags flags_; const PretenureFlag pretenure_flag_; }; class HStringCharCodeAt final : public HTemplateInstruction<3> { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P2(HStringCharCodeAt, HValue*, HValue*); Representation RequiredInputRepresentation(int index) override { // The index is supposed to be Integer32. return index == 2 ? Representation::Integer32() : Representation::Tagged(); } HValue* context() const { return OperandAt(0); } HValue* string() const { return OperandAt(1); } HValue* index() const { return OperandAt(2); } DECLARE_CONCRETE_INSTRUCTION(StringCharCodeAt) protected: bool DataEquals(HValue* other) override { return true; } Range* InferRange(Zone* zone) override { return new(zone) Range(0, String::kMaxUtf16CodeUnit); } private: HStringCharCodeAt(HValue* context, HValue* string, HValue* index) { SetOperandAt(0, context); SetOperandAt(1, string); SetOperandAt(2, index); set_representation(Representation::Integer32()); SetFlag(kUseGVN); SetDependsOnFlag(kMaps); SetDependsOnFlag(kStringChars); SetChangesFlag(kNewSpacePromotion); } // No side effects: runtime function assumes string + number inputs. bool IsDeletable() const override { return true; } }; class HStringCharFromCode final : public HTemplateInstruction<2> { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, HValue* char_code); Representation RequiredInputRepresentation(int index) override { return index == 0 ? Representation::Tagged() : Representation::Integer32(); } HValue* context() const { return OperandAt(0); } HValue* value() const { return OperandAt(1); } bool DataEquals(HValue* other) override { return true; } DECLARE_CONCRETE_INSTRUCTION(StringCharFromCode) private: HStringCharFromCode(HValue* context, HValue* char_code) : HTemplateInstruction<2>(HType::String()) { SetOperandAt(0, context); SetOperandAt(1, char_code); set_representation(Representation::Tagged()); SetFlag(kUseGVN); SetChangesFlag(kNewSpacePromotion); } bool IsDeletable() const override { return !value()->ToNumberCanBeObserved(); } }; class HTypeof final : public HTemplateInstruction<2> { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P1(HTypeof, HValue*); HValue* context() const { return OperandAt(0); } HValue* value() const { return OperandAt(1); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(Typeof) private: explicit HTypeof(HValue* context, HValue* value) { SetOperandAt(0, context); SetOperandAt(1, value); set_representation(Representation::Tagged()); } bool IsDeletable() const override { return true; } }; class HTrapAllocationMemento final : public HTemplateInstruction<1> { public: DECLARE_INSTRUCTION_FACTORY_P1(HTrapAllocationMemento, HValue*); Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HValue* object() { return OperandAt(0); } DECLARE_CONCRETE_INSTRUCTION(TrapAllocationMemento) private: explicit HTrapAllocationMemento(HValue* obj) { SetOperandAt(0, obj); } }; class HMaybeGrowElements final : public HTemplateInstruction<5> { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P6(HMaybeGrowElements, HValue*, HValue*, HValue*, HValue*, bool, ElementsKind); Representation RequiredInputRepresentation(int index) override { if (index < 3) { return Representation::Tagged(); } DCHECK(index == 3 || index == 4); return Representation::Integer32(); } HValue* context() const { return OperandAt(0); } HValue* object() const { return OperandAt(1); } HValue* elements() const { return OperandAt(2); } HValue* key() const { return OperandAt(3); } HValue* current_capacity() const { return OperandAt(4); } bool is_js_array() const { return is_js_array_; } ElementsKind kind() const { return kind_; } DECLARE_CONCRETE_INSTRUCTION(MaybeGrowElements) protected: bool DataEquals(HValue* other) override { return true; } private: explicit HMaybeGrowElements(HValue* context, HValue* object, HValue* elements, HValue* key, HValue* current_capacity, bool is_js_array, ElementsKind kind) { is_js_array_ = is_js_array; kind_ = kind; SetOperandAt(0, context); SetOperandAt(1, object); SetOperandAt(2, elements); SetOperandAt(3, key); SetOperandAt(4, current_capacity); SetFlag(kUseGVN); SetChangesFlag(kElementsPointer); SetChangesFlag(kNewSpacePromotion); set_representation(Representation::Tagged()); } bool is_js_array_; ElementsKind kind_; }; class HSeqStringGetChar final : public HTemplateInstruction<2> { public: static HInstruction* New(Isolate* isolate, Zone* zone, HValue* context, String::Encoding encoding, HValue* string, HValue* index); Representation RequiredInputRepresentation(int index) override { return (index == 0) ? Representation::Tagged() : Representation::Integer32(); } String::Encoding encoding() const { return encoding_; } HValue* string() const { return OperandAt(0); } HValue* index() const { return OperandAt(1); } DECLARE_CONCRETE_INSTRUCTION(SeqStringGetChar) protected: bool DataEquals(HValue* other) override { return encoding() == HSeqStringGetChar::cast(other)->encoding(); } Range* InferRange(Zone* zone) override { if (encoding() == String::ONE_BYTE_ENCODING) { return new(zone) Range(0, String::kMaxOneByteCharCode); } else { DCHECK_EQ(String::TWO_BYTE_ENCODING, encoding()); return new(zone) Range(0, String::kMaxUtf16CodeUnit); } } private: HSeqStringGetChar(String::Encoding encoding, HValue* string, HValue* index) : encoding_(encoding) { SetOperandAt(0, string); SetOperandAt(1, index); set_representation(Representation::Integer32()); SetFlag(kUseGVN); SetDependsOnFlag(kStringChars); } bool IsDeletable() const override { return true; } String::Encoding encoding_; }; class HSeqStringSetChar final : public HTemplateInstruction<4> { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P4( HSeqStringSetChar, String::Encoding, HValue*, HValue*, HValue*); String::Encoding encoding() { return encoding_; } HValue* context() { return OperandAt(0); } HValue* string() { return OperandAt(1); } HValue* index() { return OperandAt(2); } HValue* value() { return OperandAt(3); } Representation RequiredInputRepresentation(int index) override { return (index <= 1) ? Representation::Tagged() : Representation::Integer32(); } DECLARE_CONCRETE_INSTRUCTION(SeqStringSetChar) private: HSeqStringSetChar(HValue* context, String::Encoding encoding, HValue* string, HValue* index, HValue* value) : encoding_(encoding) { SetOperandAt(0, context); SetOperandAt(1, string); SetOperandAt(2, index); SetOperandAt(3, value); set_representation(Representation::Tagged()); SetChangesFlag(kStringChars); } String::Encoding encoding_; }; class HCheckMapValue final : public HTemplateInstruction<2> { public: DECLARE_INSTRUCTION_FACTORY_P2(HCheckMapValue, HValue*, HValue*); Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HType CalculateInferredType() override { if (value()->type().IsHeapObject()) return value()->type(); return HType::HeapObject(); } HValue* value() const { return OperandAt(0); } HValue* map() const { return OperandAt(1); } HValue* Canonicalize() override; DECLARE_CONCRETE_INSTRUCTION(CheckMapValue) protected: int RedefinedOperandIndex() override { return 0; } bool DataEquals(HValue* other) override { return true; } private: HCheckMapValue(HValue* value, HValue* map) : HTemplateInstruction<2>(HType::HeapObject()) { SetOperandAt(0, value); SetOperandAt(1, map); set_representation(Representation::Tagged()); SetFlag(kUseGVN); SetDependsOnFlag(kMaps); SetDependsOnFlag(kElementsKind); } }; class HForInPrepareMap final : public HTemplateInstruction<2> { public: DECLARE_INSTRUCTION_WITH_CONTEXT_FACTORY_P1(HForInPrepareMap, HValue*); Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HValue* context() const { return OperandAt(0); } HValue* enumerable() const { return OperandAt(1); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HType CalculateInferredType() override { return HType::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(ForInPrepareMap); private: HForInPrepareMap(HValue* context, HValue* object) { SetOperandAt(0, context); SetOperandAt(1, object); set_representation(Representation::Tagged()); SetAllSideEffects(); } }; class HForInCacheArray final : public HTemplateInstruction<2> { public: DECLARE_INSTRUCTION_FACTORY_P3(HForInCacheArray, HValue*, HValue*, int); Representation RequiredInputRepresentation(int index) override { return Representation::Tagged(); } HValue* enumerable() const { return OperandAt(0); } HValue* map() const { return OperandAt(1); } int idx() const { return idx_; } HForInCacheArray* index_cache() { return index_cache_; } void set_index_cache(HForInCacheArray* index_cache) { index_cache_ = index_cache; } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HType CalculateInferredType() override { return HType::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(ForInCacheArray); private: HForInCacheArray(HValue* enumerable, HValue* keys, int idx) : idx_(idx) { SetOperandAt(0, enumerable); SetOperandAt(1, keys); set_representation(Representation::Tagged()); } int idx_; HForInCacheArray* index_cache_; }; class HLoadFieldByIndex final : public HTemplateInstruction<2> { public: DECLARE_INSTRUCTION_FACTORY_P2(HLoadFieldByIndex, HValue*, HValue*); HLoadFieldByIndex(HValue* object, HValue* index) { SetOperandAt(0, object); SetOperandAt(1, index); SetChangesFlag(kNewSpacePromotion); set_representation(Representation::Tagged()); } Representation RequiredInputRepresentation(int index) override { if (index == 1) { return Representation::Smi(); } else { return Representation::Tagged(); } } HValue* object() const { return OperandAt(0); } HValue* index() const { return OperandAt(1); } std::ostream& PrintDataTo(std::ostream& os) const override; // NOLINT HType CalculateInferredType() override { return HType::Tagged(); } DECLARE_CONCRETE_INSTRUCTION(LoadFieldByIndex); private: bool IsDeletable() const override { return true; } }; #undef DECLARE_INSTRUCTION #undef DECLARE_CONCRETE_INSTRUCTION } // namespace internal } // namespace v8 #endif // V8_CRANKSHAFT_HYDROGEN_INSTRUCTIONS_H_
32.458413
80
0.677144
[ "object", "vector" ]
3d01383a1352d6dea36d6a2e6d8263e8d6b3ed94
6,723
h
C
dependencies/include/cgal/CGAL/RS/ugcd/ugcd.h
rosecodym/space-boundary-tool
300db4084cd19b092bdf2e8432da065daeaa7c55
[ "FSFAP" ]
6
2016-11-01T11:09:00.000Z
2022-02-15T06:31:58.000Z
dependencies/include/cgal/CGAL/RS/ugcd/ugcd.h
rosecodym/space-boundary-tool
300db4084cd19b092bdf2e8432da065daeaa7c55
[ "FSFAP" ]
null
null
null
dependencies/include/cgal/CGAL/RS/ugcd/ugcd.h
rosecodym/space-boundary-tool
300db4084cd19b092bdf2e8432da065daeaa7c55
[ "FSFAP" ]
null
null
null
// Copyright (c) 2007 Inria Lorraine (France). All rights reserved. // // This file is part of CGAL (www.cgal.org); you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 3 of the License, // or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL: svn+ssh://scm.gforge.inria.fr/svn/cgal/branches/releases/CGAL-4.1-branch/Algebraic_kernel_d/include/CGAL/RS/ugcd/ugcd.h $ // $Id: ugcd.h 70626 2012-07-19 15:46:15Z penarand $ // // Author: Luis Peñaranda <luis.penaranda@gmx.com> #ifndef CGAL_RS__UGCD_H #define CGAL_RS__UGCD_H #include <gmp.h> #include "primes.h" // let's assume that 300 is enough for degree 500 gcds #define CGALRS_MOD_QTY 300 namespace CGAL{ namespace RS_MGCD{ class Ugcd:public Primes{ public: static int ugcd (mpz_t *gcd,mpz_t *Anp,int degA,mpz_t *Bnp,int degB){ mpz_t *A,*B; mpz_t lcgcd,cA,cB; mpz_ptr m,bound; // dG is initialized to zero only to avoid compiler complaints int dA,dB,dG=0,maxd,i,maxA,maxB; size_t modsize,modalloc; std::vector<CGALRS_PN* > p; CGALRS_PN *mA,*mB,*mG,*mod; CGALRS_PN lc=0,scaleG; if(degB>degA){ if(!degA){ mpz_set_ui(gcd[0],1); return 0; }else return ugcd(gcd,Bnp,degB,Anp,degA); } if(!degB){ mpz_set_ui(gcd[0],1); return 0; } // initialize the memory meminit(); A=(mpz_t*)malloc((1+degA)*sizeof(mpz_t)); B=(mpz_t*)malloc((1+degB)*sizeof(mpz_t)); mpz_init_set(cA,Anp[degA]); for(i=0;i<degA;++i) mpz_gcd(cA,cA,Anp[i]); mpz_init_set(cB,Bnp[degB]); for(i=0;i<degB;++i) mpz_gcd(cB,cB,Bnp[i]); for(i=0;i<=degA;++i){ mpz_init(A[i]); mpz_divexact(A[i],Anp[i],cA); } for(i=0;i<=degB;++i){ mpz_init(B[i]); mpz_divexact(B[i],Bnp[i],cB); } // calculate the gcd of the principal coefficients mpz_init(lcgcd); mpz_gcd(lcgcd,A[degA],B[degB]); // find the limit of modular image computation maxA=degA; for(i=0;i<degA;++i) if(mpz_cmpabs(A[i],A[maxA])>0) maxA=i; maxB=degB; for(i=0;i<degB;++i) if(mpz_cmpabs(B[i],B[maxB])>0) maxB=i; mpz_pow_ui(cA,A[maxA],2); mpz_mul_ui(cA,cA,degA+1); mpz_mul_2exp(cA,cA,2*degA); mpz_sqrt(cA,cA); mpz_pow_ui(cB,B[maxB],2); mpz_mul_ui(cB,cB,degB+1); mpz_mul_2exp(cB,cB,2*degB); mpz_sqrt(cB,cB); if(mpz_cmp(cA,cB)<0){ bound=(mpz_ptr)cA; m=(mpz_ptr)cB; }else{ bound=(mpz_ptr)cB; m=(mpz_ptr)cA; } mpz_mul(bound,bound,lcgcd); mpz_mul_2exp(bound,bound,1); mpz_setbit(bound,0); mA=(CGALRS_PN*)palloc((1+degA)*sizeof(CGALRS_PN)); mB=(CGALRS_PN*)palloc((1+degB)*sizeof(CGALRS_PN)); maxd=degA; // we know that degA>=degB mG=(CGALRS_PN*)palloc((1+maxd)*sizeof(CGALRS_PN)); pr_init(); mpz_set_ui(m,1); mod=(CGALRS_PN*)palloc(CGALRS_MOD_QTY*sizeof(CGALRS_PN)); modalloc=CGALRS_MOD_QTY; modsize=0; while(mpz_cmp(m,bound)<=0){ do{ p_set_prime(pr_next()); dA=pp_from_poly(mA,A,degA); if(dA!=-1){ dB=pp_from_poly(mB,B,degB); if(dB!=-1) lc=mpz_fdiv_ui(lcgcd,p_prime()); // lc is the image of the principal coefficient } }while(dA==-1||dB==-1||!lc ||mpz_divisible_ui_p(A[degA],p_prime()) ||mpz_divisible_ui_p(B[degB],p_prime())); // now we calculate the gcd mod p_prime dG=pp_gcd(mG,mA,degA,mB,degB); scaleG=CGALRS_P_DIV(lc,mG[dG]); mG[dG]=lc; for(i=0;i<dG;++i) mG[i]=p_mul(mG[i],scaleG); if(!dG){ // done, we know that the gcd is constant mpz_set_ui(gcd[0],1); dG=0; goto cleanandexit; } if(dG<maxd){ CGALRS_mpz_set_pn(m,p_prime()); maxd=dG; p.clear(); p.push_back(mG); mod[0]=p_prime(); modsize=1; mG=(CGALRS_PN*)palloc((1+maxd)*sizeof(CGALRS_PN)); // TODO: clean the CGALRS_PN* that are in p }else{ if(dG==maxd){ CGALRS_mpz_mul_pn(m,m,p_prime()); if(modsize==modalloc){ modalloc*=2; mod=(CGALRS_PN*) prealloc(mod,modalloc*sizeof(CGALRS_PN)); } mod[modsize]=p_prime(); ++modsize; p.push_back(mG); mG=(CGALRS_PN*)palloc((1+maxd)*sizeof(CGALRS_PN)); } } } pcra(gcd,mod,p,maxd,modsize); cleanandexit: CGALRS_PFREE(mA); CGALRS_PFREE(mB); CGALRS_PFREE(mG); CGALRS_PFREE(mod); // TODO: clean the CGALRS_PN* that are in p for(i=0;i<=degA;++i) mpz_clear(A[i]); for(i=0;i<=degB;++i) mpz_clear(B[i]); mpz_clear(m); mpz_clear(bound); mpz_clear(lcgcd); free(A); free(B); memrelease(); return dG; }; }; // class Ugcd } // namespace RS_MGCD } // namespace CGAL #endif // CGAL_RS__UGCD_H
33.954545
130
0.470326
[ "vector" ]
3d05301fc50cfd4bc49fe46f2b0d0a2da51b6571
1,659
h
C
WinBGI/stdafx.h
nirin/WinBGI
3aa4c6b17e6c4af0899d1837450a69010673e896
[ "MIT" ]
17
2016-12-12T07:13:02.000Z
2022-03-26T23:46:39.000Z
WinBGI/stdafx.h
nirin/WinBGI
3aa4c6b17e6c4af0899d1837450a69010673e896
[ "MIT" ]
null
null
null
WinBGI/stdafx.h
nirin/WinBGI
3aa4c6b17e6c4af0899d1837450a69010673e896
[ "MIT" ]
4
2019-12-02T01:10:35.000Z
2021-10-17T19:43:17.000Z
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #define STDAFX_H_ #define STRICT // enable strict type checking #define _USE_MATH_DEFINES // Actually use the definitions in math.h //#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Default #include "targetver.h" // C #include <stdio.h> #include <stdlib.h> #include <io.h> #include <limits.h> // Provides INT_MAX #include <math.h> // Provides math functions #include <string.h> // Provides string functions #include <assert.h> #include <direct.h> #include <windows.h> // Provides Win32 API #include <windowsx.h> // Provides GDI helper macros #include <ocidl.h> // IPicture #include <OleCtl.h> // Support for IPicture // C++ #include <string> // Standard String Library #include <iostream> // Standard IO Stream Library #include <sstream> // Standard String Stream Library #include <vector> // Added for BGI__WindowTable #include <queue> // Provides queue<POINTS> using namespace std; // Shims #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef min #define min(a,b) ((a) < (b) ? (a) : (b)) #endif #ifndef max #define max(a,b) ((a) > (b) ? (a) : (b)) #endif #ifndef SC_US #define SC_US(value) static_cast<unsigned short>(value) #endif // Graphics #include "dibapi.h" #include "dibutil.h" #include "winbgi.h" #include "winbgitypes.h" // TODO: reference additional headers your program requires here
27.196721
80
0.667269
[ "vector" ]
3d0ebbc9b8805bde030da71ea6b652eec2a5e3a3
3,379
h
C
framework/src/st_things/things_stack/fota/fmwup_util_data.h
Taejun-Kwon/TizenRT
6ece6242c75653f50c345a1253133f45fb630b77
[ "Apache-2.0" ]
1
2018-04-23T12:39:01.000Z
2018-04-23T12:39:01.000Z
framework/src/st_things/things_stack/fota/fmwup_util_data.h
Taejun-Kwon/TizenRT
6ece6242c75653f50c345a1253133f45fb630b77
[ "Apache-2.0" ]
1
2018-04-19T05:06:48.000Z
2018-04-19T05:06:48.000Z
framework/src/st_things/things_stack/fota/fmwup_util_data.h
Taejun-Kwon/TizenRT
6ece6242c75653f50c345a1253133f45fb630b77
[ "Apache-2.0" ]
null
null
null
/* **************************************************************** * * Copyright 2018 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ #ifndef FMWUP_UTIL_DATA_H_ #define FMWUP_UTIL_DATA_H_ #include <stdbool.h> #define FIRMWARE_URI "/firmware" /* save to key manager(ckmc) with update */ #define FIRMWARE_PROPERTY_UPDATE "update" #define FIRMWARE_PROPERTY_UPDATE_TIME "updatetime" #define FIRMWARE_PROPERTY_DESCRIPTION "description" #define FIRMWARE_PROPERTY_STATE "state" #define FIRMWARE_PROPERTY_RESULT "result" #define FIRMWARE_PROPERTY_PROGRESS "progress" /* save to key manager(ckmc) with pacakage */ #define FIRMWARE_PROPERTY_NEW_VERSION "newversion" #define FIRMWARE_PROPERTY_PACKAGE_URI "packageuri" /* platform information */ #define FIRMWARE_PROPERTY_CURRENT_VERSION "version" #define FIRMWARE_PROPERTY_VENDER "vender" #define FIRMWARE_PROPERTY_MODEL "model" #define KEY_MANAGER_MAX_DATA_LENGTH 200 #define KEY_MANAGER_INT_DEFAULT_DATA "0" #define KEY_MANAGER_STR_DEFAULT_DATA " " #define KEY_MANAGER_BOL_DEFAULT_DATA "0" #define FIRMWARE_PROPERTY_UPDATE_INIT "Init" #define FIRMWARE_PROPERTY_UPDATE_CHECK "Check" #define FIRMWARE_PROPERTY_UPDATE_DOWNLOAD "Download" #define FIRMWARE_PROPERTY_UPDATE_UPDATE "Update" #define FIRMWARE_PROPERTY_UPDATE_DOWNLOADUPDATE "DownloadUpdate" typedef struct { /* Update Property */ int64_t state; //[R][M] fmwup_state_e - 0: Idle, 1: Downloading, 2: Downloaded, 3: Updating int64_t result; //[R][M] 0: Initial, 1: Success, 2: Not enough space, 3: Out of ram, 4: Connection lost, 5: Invalid binary, 6: Invalid uri, 7: Update failed, 8: Unsupported protocol int64_t update; //[RW][M] 0: Initial, 1: Download Image, 2: Upgrade Image, 3:Dwonload and Upgrade, 4 Scheduled Upgrade char *update_time; //[RW][O] case of (4 – update) (scheduled) TODO: ISO 8601 /* Package Information */ char *new_version; //[RW][M] New Version of the firmware package char *package_uri; //[RW][M] Firmware package URI where the package located /* Device Information */ char *manufacturer; //[R][O] Device vendor identifier char *model_name; //[R][O] Device model identifier char *current_version; //[R][M] Current firmware version } fmwup_data_s; int64_t fmwup_data_get_update_int64(const char *); char *fmwup_data_get_update_string(int64_t); fmwup_data_s *fmwup_data_get_properties(); int fmwup_data_set_property_int64(const char *name, int64_t data); int fmwup_data_set_property(const char *name, char *data); char *fmwup_data_get_property(const char *name); int key_manager_init(); int key_manager_save_data(); char *key_manager_set_default_data(const char *name); int key_manager_reset_data(); #endif /* FMWUP_UTIL_DATA_H_ */
39.290698
185
0.732169
[ "model" ]
3d0edbceb9b1b0f6cc260099bc6d825fbae85b4e
1,632
h
C
src/shogun/converter/ica/SOBI.h
ShankarNara/shogun
8ab196de16b8d8917e5c84770924c8d0f5a3d17c
[ "BSD-3-Clause" ]
1
2020-03-13T11:07:42.000Z
2020-03-13T11:07:42.000Z
src/shogun/converter/ica/SOBI.h
ShankarNara/shogun
8ab196de16b8d8917e5c84770924c8d0f5a3d17c
[ "BSD-3-Clause" ]
null
null
null
src/shogun/converter/ica/SOBI.h
ShankarNara/shogun
8ab196de16b8d8917e5c84770924c8d0f5a3d17c
[ "BSD-3-Clause" ]
null
null
null
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Kevin Hughes, Heiko Strathmann, Bjoern Esser */ #ifndef SOBI_H_ #define SOBI_H_ #include <shogun/lib/config.h> #include <shogun/lib/SGNDArray.h> #include <shogun/features/Features.h> #include <shogun/converter/ica/ICAConverter.h> namespace shogun { class Features; /** @brief class SOBI * * Implements the Second Order Blind Identification (SOBI) * algorithm for Independent Component Analysis (ICA) and * Blind Source Separation (BSS). This algorithm is also * sometime refered to as Temporal Decorrelation Separation * (TDSep). * * Belouchrani, A., Abed-Meraim, K., Cardoso, J. F., & Moulines, E. (1997). * A blind source separation technique using second-order statistics. * Signal Processing, IEEE Transactions on, 45(2), 434-444. * */ class SOBI: public ICAConverter { public: /** constructor */ SOBI(); /** destructor */ virtual ~SOBI(); /** getter for tau parameter * @return tau vector */ SGVector<float64_t> get_tau() const; /** setter for tau parameter * @param tau vector */ void set_tau(SGVector<float64_t> tau); /** getter for time sep cov matrices * @return cov matrices */ SGNDArray<float64_t> get_covs() const; /** @return object name */ virtual const char* get_name() const { return "SOBI"; }; protected: /** init */ void init(); virtual void fit_dense(std::shared_ptr<DenseFeatures<float64_t>> features); private: /** tau vector */ SGVector<float64_t> m_tau; /** cov matrices */ SGNDArray<float64_t> m_covs; }; } #endif // SOBI
20.923077
78
0.6875
[ "object", "vector" ]
3d0fdeb84092c6e405f00a3d0a5f386dc7c6f122
4,536
h
C
shell/platform/darwin/ios/framework/Source/accessibility_bridge.h
ekasetiawans/engine
5585f2ece87ca14cd4a6bae11109427202d8ec11
[ "BSD-3-Clause" ]
2
2020-07-17T03:54:44.000Z
2020-09-11T14:35:47.000Z
shell/platform/darwin/ios/framework/Source/accessibility_bridge.h
ekasetiawans/engine
5585f2ece87ca14cd4a6bae11109427202d8ec11
[ "BSD-3-Clause" ]
3
2021-01-11T00:21:02.000Z
2021-05-26T01:35:54.000Z
shell/platform/darwin/ios/framework/Source/accessibility_bridge.h
ekasetiawans/engine
5585f2ece87ca14cd4a6bae11109427202d8ec11
[ "BSD-3-Clause" ]
1
2021-07-12T18:52:55.000Z
2021-07-12T18:52:55.000Z
// Copyright 2013 The Flutter 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 SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_ #define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_ #include <memory> #include <unordered_map> #include <unordered_set> #include <vector> #import <UIKit/UIKit.h> #include "flutter/fml/macros.h" #include "flutter/fml/memory/weak_ptr.h" #include "flutter/fml/platform/darwin/scoped_nsobject.h" #include "flutter/lib/ui/semantics/custom_accessibility_action.h" #include "flutter/lib/ui/semantics/semantics_node.h" #include "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" #include "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" #include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" #include "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" #include "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h" #include "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h" #include "third_party/skia/include/core/SkRect.h" namespace flutter { class PlatformViewIOS; /** * An accessibility instance is bound to one `FlutterViewController` and * `FlutterView` instance. * * It helps populate the UIView's accessibilityElements property from Flutter's * semantics nodes. */ class AccessibilityBridge final : public AccessibilityBridgeIos { public: /** Delegate for handling iOS operations. */ class IosDelegate { public: virtual ~IosDelegate() = default; /// Returns true when the FlutterViewController associated with the `view` /// is presenting a modal view controller. virtual bool IsFlutterViewControllerPresentingModalViewController( FlutterViewController* view_controller) = 0; virtual void PostAccessibilityNotification(UIAccessibilityNotifications notification, id argument) = 0; }; AccessibilityBridge(FlutterViewController* view_controller, PlatformViewIOS* platform_view, FlutterPlatformViewsController* platform_views_controller, std::unique_ptr<IosDelegate> ios_delegate = nullptr); ~AccessibilityBridge(); void UpdateSemantics(flutter::SemanticsNodeUpdates nodes, flutter::CustomAccessibilityActionUpdates actions); void DispatchSemanticsAction(int32_t id, flutter::SemanticsAction action) override; void DispatchSemanticsAction(int32_t id, flutter::SemanticsAction action, std::vector<uint8_t> args) override; void AccessibilityObjectDidBecomeFocused(int32_t id) override; void AccessibilityObjectDidLoseFocus(int32_t id) override; UIView<UITextInput>* textInputView() override; UIView* view() const override { return view_controller_.view; } fml::WeakPtr<AccessibilityBridge> GetWeakPtr(); FlutterPlatformViewsController* GetPlatformViewsController() const override { return platform_views_controller_; }; void clearState(); private: SemanticsObject* GetOrCreateObject(int32_t id, flutter::SemanticsNodeUpdates& updates); SemanticsObject* FindFirstFocusable(SemanticsObject* object); void VisitObjectsRecursivelyAndRemove(SemanticsObject* object, NSMutableArray<NSNumber*>* doomed_uids); void HandleEvent(NSDictionary<NSString*, id>* annotatedEvent); FlutterViewController* view_controller_; PlatformViewIOS* platform_view_; FlutterPlatformViewsController* platform_views_controller_; // If the this id is kSemanticObjectIdInvalid, it means either nothing has // been focused or the focus is currently outside of the flutter application // (i.e. the status bar or keyboard) int32_t last_focused_semantics_object_id_; fml::scoped_nsobject<NSMutableDictionary<NSNumber*, SemanticsObject*>> objects_; fml::scoped_nsprotocol<FlutterBasicMessageChannel*> accessibility_channel_; fml::WeakPtrFactory<AccessibilityBridge> weak_factory_; int32_t previous_route_id_; std::unordered_map<int32_t, flutter::CustomAccessibilityAction> actions_; std::vector<int32_t> previous_routes_; std::unique_ptr<IosDelegate> ios_delegate_; FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge); }; } // namespace flutter #endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_
42.392523
89
0.768739
[ "object", "vector" ]
3d0ff16742751911a8b6c8a10dcd9c4dbc6b22f2
7,504
h
C
aws-cpp-sdk-kinesis-video-media/include/aws/kinesis-video-media/model/GetMediaResult.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-kinesis-video-media/include/aws/kinesis-video-media/model/GetMediaResult.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-kinesis-video-media/include/aws/kinesis-video-media/model/GetMediaResult.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/kinesis-video-media/KinesisVideoMedia_EXPORTS.h> #include <aws/core/utils/stream/ResponseStream.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/Array.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace KinesisVideoMedia { namespace Model { class AWS_KINESISVIDEOMEDIA_API GetMediaResult { public: GetMediaResult(); //We have to define these because Microsoft doesn't auto generate them GetMediaResult(GetMediaResult&&); GetMediaResult& operator=(GetMediaResult&&); //we delete these because Microsoft doesn't handle move generation correctly //and we therefore don't trust them to get it right here either. GetMediaResult(const GetMediaResult&) = delete; GetMediaResult& operator=(const GetMediaResult&) = delete; GetMediaResult(Aws::AmazonWebServiceResult<Aws::Utils::Stream::ResponseStream>&& result); GetMediaResult& operator=(Aws::AmazonWebServiceResult<Aws::Utils::Stream::ResponseStream>&& result); /** * <p>The content type of the requested media.</p> */ inline const Aws::String& GetContentType() const{ return m_contentType; } /** * <p>The content type of the requested media.</p> */ inline void SetContentType(const Aws::String& value) { m_contentType = value; } /** * <p>The content type of the requested media.</p> */ inline void SetContentType(Aws::String&& value) { m_contentType = std::move(value); } /** * <p>The content type of the requested media.</p> */ inline void SetContentType(const char* value) { m_contentType.assign(value); } /** * <p>The content type of the requested media.</p> */ inline GetMediaResult& WithContentType(const Aws::String& value) { SetContentType(value); return *this;} /** * <p>The content type of the requested media.</p> */ inline GetMediaResult& WithContentType(Aws::String&& value) { SetContentType(std::move(value)); return *this;} /** * <p>The content type of the requested media.</p> */ inline GetMediaResult& WithContentType(const char* value) { SetContentType(value); return *this;} /** * <p> The payload Kinesis Video Streams returns is a sequence of chunks from the * specified stream. For information about the chunks, see . The chunks that * Kinesis Video Streams returns in the <code>GetMedia</code> call also include the * following additional Matroska (MKV) tags: </p> <ul> <li> * <p>AWS_KINESISVIDEO_CONTINUATION_TOKEN (UTF-8 string) - In the event your * <code>GetMedia</code> call terminates, you can use this continuation token in * your next request to get the next chunk where the last request terminated.</p> * </li> <li> <p>AWS_KINESISVIDEO_MILLIS_BEHIND_NOW (UTF-8 string) - Client * applications can use this tag value to determine how far behind the chunk * returned in the response is from the latest chunk on the stream. </p> </li> <li> * <p>AWS_KINESISVIDEO_FRAGMENT_NUMBER - Fragment number returned in the chunk.</p> * </li> <li> <p>AWS_KINESISVIDEO_SERVER_TIMESTAMP - Server timestamp of the * fragment.</p> </li> <li> <p>AWS_KINESISVIDEO_PRODUCER_TIMESTAMP - Producer * timestamp of the fragment.</p> </li> </ul> <p>The following tags will be present * if an error occurs:</p> <ul> <li> <p>AWS_KINESISVIDEO_ERROR_CODE - String * description of an error that caused GetMedia to stop.</p> </li> <li> * <p>AWS_KINESISVIDEO_ERROR_ID: Integer code of the error.</p> </li> </ul> <p>The * error codes are as follows:</p> <ul> <li> <p>3002 - Error writing to the * stream</p> </li> <li> <p>4000 - Requested fragment is not found</p> </li> <li> * <p>4500 - Access denied for the stream's KMS key</p> </li> <li> <p>4501 - * Stream's KMS key is disabled</p> </li> <li> <p>4502 - Validation error on the * stream's KMS key</p> </li> <li> <p>4503 - KMS key specified in the stream is * unavailable</p> </li> <li> <p>4504 - Invalid usage of the KMS key specified in * the stream</p> </li> <li> <p>4505 - Invalid state of the KMS key specified in * the stream</p> </li> <li> <p>4506 - Unable to find the KMS key specified in the * stream</p> </li> <li> <p>5000 - Internal error</p> </li> </ul> */ inline Aws::IOStream& GetPayload() { return m_payload.GetUnderlyingStream(); } /** * <p> The payload Kinesis Video Streams returns is a sequence of chunks from the * specified stream. For information about the chunks, see . The chunks that * Kinesis Video Streams returns in the <code>GetMedia</code> call also include the * following additional Matroska (MKV) tags: </p> <ul> <li> * <p>AWS_KINESISVIDEO_CONTINUATION_TOKEN (UTF-8 string) - In the event your * <code>GetMedia</code> call terminates, you can use this continuation token in * your next request to get the next chunk where the last request terminated.</p> * </li> <li> <p>AWS_KINESISVIDEO_MILLIS_BEHIND_NOW (UTF-8 string) - Client * applications can use this tag value to determine how far behind the chunk * returned in the response is from the latest chunk on the stream. </p> </li> <li> * <p>AWS_KINESISVIDEO_FRAGMENT_NUMBER - Fragment number returned in the chunk.</p> * </li> <li> <p>AWS_KINESISVIDEO_SERVER_TIMESTAMP - Server timestamp of the * fragment.</p> </li> <li> <p>AWS_KINESISVIDEO_PRODUCER_TIMESTAMP - Producer * timestamp of the fragment.</p> </li> </ul> <p>The following tags will be present * if an error occurs:</p> <ul> <li> <p>AWS_KINESISVIDEO_ERROR_CODE - String * description of an error that caused GetMedia to stop.</p> </li> <li> * <p>AWS_KINESISVIDEO_ERROR_ID: Integer code of the error.</p> </li> </ul> <p>The * error codes are as follows:</p> <ul> <li> <p>3002 - Error writing to the * stream</p> </li> <li> <p>4000 - Requested fragment is not found</p> </li> <li> * <p>4500 - Access denied for the stream's KMS key</p> </li> <li> <p>4501 - * Stream's KMS key is disabled</p> </li> <li> <p>4502 - Validation error on the * stream's KMS key</p> </li> <li> <p>4503 - KMS key specified in the stream is * unavailable</p> </li> <li> <p>4504 - Invalid usage of the KMS key specified in * the stream</p> </li> <li> <p>4505 - Invalid state of the KMS key specified in * the stream</p> </li> <li> <p>4506 - Unable to find the KMS key specified in the * stream</p> </li> <li> <p>5000 - Internal error</p> </li> </ul> */ inline void ReplaceBody(Aws::IOStream* body) { m_payload = Aws::Utils::Stream::ResponseStream(body); } private: Aws::String m_contentType; Aws::Utils::Stream::ResponseStream m_payload; }; } // namespace Model } // namespace KinesisVideoMedia } // namespace Aws
48.102564
114
0.678305
[ "model" ]
3d129a2e04e0a22dab02091b6194ed7456f7f507
7,631
h
C
src/dale/llvmUtils/llvmUtils.h
tomhrr/dale
67841a7bb7bb20209697f99d1472028eefb1f342
[ "BSD-3-Clause" ]
1,083
2015-03-18T09:42:49.000Z
2022-03-29T03:17:47.000Z
src/dale/llvmUtils/llvmUtils.h
tomhrr/dale
67841a7bb7bb20209697f99d1472028eefb1f342
[ "BSD-3-Clause" ]
195
2015-01-04T03:06:41.000Z
2022-03-18T18:16:27.000Z
src/dale/llvmUtils/llvmUtils.h
tomhrr/dale
67841a7bb7bb20209697f99d1472028eefb1f342
[ "BSD-3-Clause" ]
56
2015-03-18T20:02:13.000Z
2022-01-22T19:35:27.000Z
#ifndef DALE_LLVMUTILS #define DALE_LLVMUTILS #include <sys/stat.h> #include <cerrno> #include <climits> #include <memory> #include <string> #include <utility> #include <vector> #include "../Type/Type.h" #include "../Unit/Unit.h" #include "../Variable/Variable.h" #include "../llvm_Linker.h" #include "../llvm_Module.h" #if D_LLVM_VERSION_ORD >= 33 #include "llvm/IRReader/IRReader.h" #include "llvm/Support/SourceMgr.h" #endif #if D_LLVM_VERSION_ORD <= 33 #include "llvm/PassManager.h" #else #include "llvm/IR/LegacyPassManager.h" #endif #if D_LLVM_VERSION_ORD >= 36 #include "llvm/Transforms/Utils/Cloning.h" #endif #if D_LLVM_VERSION_ORD <= 39 #include "llvm/Bitcode/ReaderWriter.h" #else #include "llvm/Bitcode/BitcodeReader.h" #include "llvm/Bitcode/BitcodeWriter.h" #endif #include "llvm/Support/FormattedStream.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #define _unused(x) ((void)x) #define STRTOUL_FAILED(ret, str, end) \ (((((ret) == ULONG_MAX || ((ret) == 0)) && (errno == ERANGE)) || \ (((ret) == 0) && ((str) == (end))))) #define DECIMAL_RADIX 10 #if D_LLVM_VERSION_ORD <= 35 #define DECLARE_ENGINE_BUILDER(mod, name) \ llvm::EngineBuilder name = llvm::EngineBuilder(mod); #elif D_LLVM_VERSION_ORD <= 60 #define DECLARE_ENGINE_BUILDER(mod, name) \ std::unique_ptr<llvm::Module> module_ptr(llvm::CloneModule(mod)); \ llvm::EngineBuilder name(move(module_ptr)); #else #define DECLARE_ENGINE_BUILDER(mod, name) \ std::unique_ptr<llvm::Module> module_ptr(llvm::CloneModule(*mod)); \ llvm::EngineBuilder name(move(module_ptr)); #endif /* Utility functions that depend on LLVM classes. Most of the ifdefs * required for backwards compatibility with older versions of LLVM * should be contained within the corresponding implementation file. */ namespace dale { /*! The PassManager type. */ #if D_LLVM_VERSION_ORD <= 33 typedef llvm::PassManager PassManager; #else typedef llvm::legacy::PassManager PassManager; #endif /*! The formatted output stream type. */ #if D_LLVM_VERSION_ORD <= 36 typedef llvm::formatted_raw_ostream llvm_formatted_ostream; #else typedef llvm::raw_fd_ostream llvm_formatted_ostream; #endif /*! Get the current target triple. */ std::string getTriple(); /*! Link the given module using the linker. * @param linker The linker. * @param mod The module. */ void linkModule(llvm::Linker *linker, llvm::Module *mod); /*! Add a data layout pass to the pass manager, based on the module's * data layout, if required. * @param pass_manager The pass manager. * @param mod The module. */ void addDataLayout(PassManager *pass_manager, llvm::Module *mod); /*! Add a print module pass to the pass manager. * @param pass_manager The pass manager. * @param ostream The output stream for the pass. */ void addPrintModulePass(PassManager *pass_manager, llvm::raw_fd_ostream *ostream); /*! Construct and return a new target machine. * @param mod The module (for its reference to the triple). */ llvm::TargetMachine *getTargetMachine(llvm::Module *mod); /*! Set the data layout for the module. * @param mod The module. * @param arch The current architecture. */ void setDataLayout(llvm::Module *mod, int arch); /*! Add the LTO passes to the pass manager. * @param pass_manager_builder The pass manager builder. * @param pass_manager The pass manager. */ void populateLTOPassManager( llvm::PassManagerBuilder *pass_manager_builder, PassManager *pass_manager); /*! Get a formatted output stream from a raw output stream. * @param ostream The raw output stream. */ llvm_formatted_ostream *getFormattedOstream( llvm::raw_fd_ostream *ostream); /*! Print the module to stderr, verify it if possible, and abort if * verification fails. * @param mod The module. */ void moduleDebugPass(llvm::Module *mod); /*! Print the function to stderr, verify it if possible, and abort if * verification fails. * @param fn The function. */ void functionDebugPass(llvm::Function *fn); /*! Add the 'always inline' attribute to the function. * @param fn The function. */ void addInlineAttribute(llvm::Function *fn); /*! Convert an instruction into an instruction iterator. * @param inst The instruction. */ llvm::BasicBlock::iterator instructionToIterator( llvm::Instruction *inst); /*! Set the insertion point of the builder to be before the specified * instruction. * @param builder The builder. * @param iter The instruction iterator. */ void setInsertPoint(llvm::IRBuilder<> *builder, llvm::BasicBlock::iterator iter); /*! Get the current EE address for the given variable. * @param ee The execution engine. * @param var The variable. */ uint64_t variableToAddress(llvm::ExecutionEngine *ee, Variable *var); /*! Get the current EE address for the given function. * @param ee The execution engine. * @param fn The function. */ uint64_t functionToAddress(Unit *unit, Function *fn); /*! Clone the current module and add it to the EE, if required. This * should only be used before executing a function via the JIT. * Cloning is only required in LLVM versions 3.6 and following, because * of how the EE takes ownership of the module in those versions. * @param unit The current unit. */ void cloneModuleIfRequired(Unit *unit); /*! Set the standard attributes for the 'basic' functions (i.e. the * core arithmetical and relational functions). * @param fn The function. */ void setStandardAttributes(llvm::Function *fn); /*! Load the module. * @param path The path to the module. */ llvm::Module *loadModule(std::string *path); /*! Construct a new linker. * @param path The path to the current executable ('.../dalec[i]'). * @param mod The initial module for linking. */ llvm::Linker *newLinker(const char *path, llvm::Module *mod); /*! Get an LLVM function type. * @param t The return type. * @param v The parameter types. * @param b Whether the function is a varargs function. */ llvm::FunctionType *getFunctionType(llvm::Type *t, std::vector<llvm::Type *> const &v, bool b); /*! Construct an LLVM string constant data array. * @param data The data for the array. */ llvm::Constant *getStringConstantArray(const char *data); /*! Construct an LLVM null pointer for the type. * @param type The type. */ llvm::ConstantPointerNull *getNullPointer(llvm::Type *type); /*! Link a file into the given linker. * @param linker The linker. * @param path The path to the file to be linked. */ void linkFile(llvm::Linker *linker, const char *path); /*! Get a new context. */ llvm::LLVMContext *getContext(); /*! Create a new empty function returning the specified type. * @param units The units context. * @param type The return type. * @param top A reference node for errors. */ Function *createFunction(Units *units, Type *type, Node *top); /*! Link the specified functions/variables into the current module, * inlining anything not already available. * @param mod The top-level module. * @param top A reference node for errors. * @param functions The functions to link into the module. * @param variables The variables to link into the module. */ void linkRetrievedObjects(llvm::Module *mod, Node *top, std::vector<Function *> *functions, std::vector<Variable *> *variables); } #endif
33.61674
72
0.701874
[ "vector" ]
3d13cffcb717d2e1c2c01bd5c1528639ddeec5e7
233,914
c
C
core/pubnub_core_unit_test.c
sghiocel/pubnub-c
149e536e4e1e973a717b324034aa08df9b1bc3a8
[ "MIT" ]
47
2015-07-09T14:14:32.000Z
2022-03-03T21:47:16.000Z
core/pubnub_core_unit_test.c
sghiocel/pubnub-c
149e536e4e1e973a717b324034aa08df9b1bc3a8
[ "MIT" ]
52
2015-11-03T16:59:24.000Z
2022-03-09T15:52:37.000Z
core/pubnub_core_unit_test.c
sghiocel/pubnub-c
149e536e4e1e973a717b324034aa08df9b1bc3a8
[ "MIT" ]
69
2015-08-19T11:32:27.000Z
2022-03-31T16:20:13.000Z
/* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */ #include "cgreen/cgreen.h" #include "cgreen/mocks.h" #include "pubnub_internal.h" #include "pubnub_server_limits.h" #include "pubnub_pubsubapi.h" #include "pubnub_coreapi.h" #if PUBNUB_USE_ADVANCED_HISTORY #include "pubnub_memory_block.h" #include "pubnub_advanced_history.h" #endif #include "pubnub_assert.h" #include "pubnub_alloc.h" #include "pubnub_log.h" #include "pbpal.h" #include "pubnub_version_internal.h" #include "pubnub_keep_alive.h" #include "test/pubnub_test_helper.h" #include "pubnub_json_parse.h" #include <stdlib.h> #include <string.h> #include <setjmp.h> #include <time.h> #include <assert.h> /* A less chatty cgreen :) */ #define attest assert_that #define equals is_equal_to #define streqs is_equal_to_string #define differs is_not_equal_to #define strdifs is_not_equal_to_string #define ptreqs(val) is_equal_to_contents_of(&(val), sizeof(val)) #define ptrdifs(val) is_not_equal_to_contents_of(&(val), sizeof(val)) #define sets(par, val) will_set_contents_of_parameter(par, &(val), sizeof(val)) #define sets_ex will_set_contents_of_parameter #define returns will_return struct uint8_block { size_t size; uint8_t* block; }; /* Current (simulated) string message received */ static const char* m_read; /* Number of simulated string messages received */ static int m_num_string_msgs_rcvd; /* Number of 'uint8_t' data blocks received*/ static int m_num_uint8_data_blocks; /* Array of simulated 'receive' messages */ static char* m_string_msg_array[20]; /* Array of simulated 'receive' messages */ static struct uint8_block* m_uint8_data_block_array[20]; /* Index(in the array) of the current string message used while receiving*/ static int m_i; /* Index(in the array) of the current 'uint8_t' data block used while * receiving*/ static int m_j; /* bit masks array for advancing through string or uint8blocks arrays while * receiving */ uint8_t string_or_uint8block_mask[10]; /* Awaits given amount of time in seconds */ static void wait_time_in_seconds(time_t time_in_seconds) { time_t time_start = time(NULL); do { } while ((time(NULL) - time_start) < time_in_seconds); return; } /* The Pubnub NTF mocks and stubs */ void pbntf_trans_outcome(pubnub_t* pb, enum pubnub_state state) { pb->state = state; mock(pb); } int pbntf_got_socket(pubnub_t* pb) { return (int)mock(pb); } void pbntf_lost_socket(pubnub_t* pb) { mock(pb); } void pbntf_update_socket(pubnub_t* pb) { mock(pb); } void pbntf_start_wait_connect_timer(pubnub_t* pb) { /* This might be mocked at some point */ } void pbntf_start_transaction_timer(pubnub_t* pb) { /* This might be mocked at some point */ } int pbntf_requeue_for_processing(pubnub_t* pb) { return (int)mock(pb); } int pbntf_enqueue_for_processing(pubnub_t* pb) { return (int)mock(pb); } int pbntf_watch_out_events(pubnub_t* pb) { return (int)mock(pb); } int pbntf_watch_in_events(pubnub_t* pb) { return (int)mock(pb); } /* The Pubnub PAL mocks and stubs */ static void buf_setup(pubnub_t* pb) { pb->ptr = (uint8_t*)pb->core.http_buf; pb->left = sizeof pb->core.http_buf / sizeof pb->core.http_buf[0]; } void pbpal_init(pubnub_t* pb) { buf_setup(pb); } enum pbpal_resolv_n_connect_result pbpal_resolv_and_connect(pubnub_t* pb) { return (int)mock(pb); } enum pbpal_resolv_n_connect_result pbpal_check_resolv_and_connect(pubnub_t* pb) { return (int)mock(pb); } #if defined(PUBNUB_CALLBACK_API) #if PUBNUB_CHANGE_DNS_SERVERS int pbpal_dns_rotate_server(pubnub_t *pb) { return (int)mock(pb); } #endif /* PUBNUB_CHANGE_DNS_SERVERS */ #endif /* defined(PUBNUB_CALLBACK_API) */ bool pbpal_connected(pubnub_t* pb) { return (bool)mock(pb); } void pbpal_free(pubnub_t* pb) { mock(pb); } enum pbpal_resolv_n_connect_result pbpal_check_connect(pubnub_t* pb) { return (int)mock(pb); } void pbpal_report_error_from_environment(pubnub_t* pb, char const* file, int line) { mock(pb); } #if 0 #include <execinfo.h> static void my_stack_trace(void) { void *trace[16]; char **messages = NULL; int i, trace_size = 0; trace_size = backtrace(trace, sizeof trace / sizeof trace[0]); messages = backtrace_symbols(trace, trace_size); for (i = 1; i < trace_size; ++i) { printf("[bt] #%d %s \n", i, messages[i]); /* find first occurence of '(' or ' ' in message[i] and assume * everything before that is the file name. (Don't go beyond 0 though * (string terminator)*/ size_t p = 0; while(messages[i][p] != '(' && messages[i][p] != ' ' && messages[i][p] != 0) ++p; char syscom[256]; snprintf(syscom, sizeof syscom, "addr2line %p -e %.*s", trace[i], p, messages[i]); //last parameter is the file name of the symbol system(syscom); } } #endif int pbpal_send(pubnub_t* pb, void const* data, size_t n) { return (int)mock(pb, data, n); } int pbpal_send_str(pubnub_t* pb, char const* s) { return (int)mock(pb, s); } int pbpal_send_status(pubnub_t* pb) { return (bool)mock(pb); } int pbpal_start_read_line(pubnub_t* pb) { unsigned distance; PUBNUB_ASSERT_INT_OPT(pb->sock_state, ==, STATE_NONE); if (pb->unreadlen > 0) { PUBNUB_ASSERT_OPT((char*)(pb->ptr + pb->unreadlen) <= (char*)(pb->core.http_buf + PUBNUB_BUF_MAXLEN)); memmove(pb->core.http_buf, pb->ptr, pb->unreadlen); } distance = pb->ptr - (uint8_t*)pb->core.http_buf; PUBNUB_ASSERT_UINT((distance + pb->left + pb->unreadlen), ==, (sizeof pb->core.http_buf / sizeof pb->core.http_buf[0])); pb->ptr -= distance; pb->left += distance; pb->sock_state = STATE_READ_LINE; return +1; } int pbpal_read_len(pubnub_t* pb) { return (char*)pb->ptr - pb->core.http_buf; } static int my_recv(void* p, size_t n) { static short m_new = 1; int to_read; if (string_or_uint8block_mask[(m_i + m_j) / 8] & (1 << (m_i + m_j) % 8)) { if (m_new) { assert(m_num_string_msgs_rcvd <= sizeof m_string_msg_array); if (m_i < m_num_string_msgs_rcvd) { m_read = m_string_msg_array[m_i]; m_new = 0; assert(m_read != NULL); if (strlen(m_read) == 0) { /* an empty string sent(server response simulation), * through function 'incoming', * 'APIs' should interpret as: * ('recv_from_platform_result' < 0) which gives * the oportunity to simulate and test * 'callback' environment in some degree. */ ++m_i; m_new = 1; return -1; } } else { /* If there is no more 'incoming' string msgs when expected * virtual platform simulates 'connection closed - server * side'(0 bytes received) */ m_new = 1; return 0; } } assert(m_read != NULL); to_read = strlen(m_read); if (to_read > n) { to_read = n; } if (strlen(m_read) == to_read) { ++m_i; m_new = 1; } } else { if (m_new) { assert(m_num_uint8_data_blocks <= sizeof m_uint8_data_block_array); if (m_j < m_num_uint8_data_blocks) { m_read = (const char*)m_uint8_data_block_array[m_j]->block; m_new = 0; } else { /* If there is no more 'incoming' 'uint8_t' data blocks when * expected virtual platform simulates 'connection closed - * server side'(0 bytes received) */ m_new = 1; return 0; } } assert(m_read != NULL); to_read = m_uint8_data_block_array[m_j]->size; if (to_read > n) { to_read = n; } if (!(m_uint8_data_block_array[m_j]->size -= to_read)) { ++m_j; m_new = 1; } } memcpy(p, m_read, to_read); m_read += to_read; return to_read; } enum pubnub_res pbpal_line_read_status(pubnub_t* pb) { uint8_t c; PUBNUB_ASSERT_OPT(STATE_READ_LINE == pb->sock_state); if (pb->unreadlen == 0) { int recvres; PUBNUB_ASSERT_OPT((char*)(pb->ptr + pb->left) == (char*)(pb->core.http_buf + PUBNUB_BUF_MAXLEN)); recvres = my_recv((char*)pb->ptr, pb->left); if (recvres < 0) { return PNR_IN_PROGRESS; } else if (0 == recvres) { pb->sock_state = STATE_NONE; return PNR_TIMEOUT; } PUBNUB_ASSERT_OPT(recvres <= pb->left); PUBNUB_LOG_TRACE( "pb=%p have new data of length=%d: %.*s\n", pb, recvres, recvres, pb->ptr); pb->unreadlen = recvres; pb->left -= recvres; } while (pb->unreadlen > 0) { --pb->unreadlen; c = *pb->ptr++; if (c == '\n') { PUBNUB_LOG_TRACE("pb=%p, newline found, line length: %d, ", pb, pbpal_read_len(pb)); WATCH_USHORT(pb->unreadlen); pb->sock_state = STATE_NONE; return PNR_OK; } } if (pb->left == 0) { PUBNUB_LOG_ERROR( "pbpal_line_read_status(pb=%p): buffer full but newline not found", pb); pb->sock_state = STATE_NONE; return PNR_TX_BUFF_TOO_SMALL; } return PNR_IN_PROGRESS; } int pbpal_start_read(pubnub_t* pb, size_t n) { unsigned distance; PUBNUB_ASSERT_UINT_OPT(n, >, 0); PUBNUB_ASSERT_INT_OPT(pb->sock_state, ==, STATE_NONE); WATCH_USHORT(pb->unreadlen); WATCH_USHORT(pb->left); if (pb->unreadlen > 0) { PUBNUB_ASSERT_OPT((char*)(pb->ptr + pb->unreadlen) <= (char*)(pb->core.http_buf + PUBNUB_BUF_MAXLEN)); memmove(pb->core.http_buf, pb->ptr, pb->unreadlen); } distance = pb->ptr - (uint8_t*)pb->core.http_buf; WATCH_UINT(distance); PUBNUB_ASSERT_UINT(distance + pb->unreadlen + pb->left, ==, sizeof pb->core.http_buf / sizeof pb->core.http_buf[0]); pb->ptr -= distance; pb->left += distance; pb->sock_state = STATE_READ; pb->len = n; return +1; } enum pubnub_res pbpal_read_status(pubnub_t* pb) { int have_read; PUBNUB_ASSERT_OPT(STATE_READ == pb->sock_state); if (0 == pb->unreadlen) { unsigned to_recv = pb->len; if (to_recv > pb->left) { to_recv = pb->left; } PUBNUB_ASSERT_OPT(to_recv > 0); have_read = my_recv((char*)pb->ptr, to_recv); if (have_read < 0) { return PNR_IN_PROGRESS; } else if (0 == have_read) { pb->sock_state = STATE_NONE; return PNR_TIMEOUT; } PUBNUB_ASSERT_OPT(pb->left >= have_read); pb->left -= have_read; } else { have_read = (pb->unreadlen >= pb->len) ? pb->len : pb->unreadlen; pb->unreadlen -= have_read; } pb->len -= have_read; pb->ptr += have_read; if ((0 == pb->len) || (0 == pb->left)) { pb->sock_state = STATE_NONE; return PNR_OK; } return PNR_IN_PROGRESS; } bool pbpal_closed(pubnub_t* pb) { return (bool)mock(pb); } void pbpal_forget(pubnub_t* pb) { mock(pb); } int pbpal_close(pubnub_t* pb) { pb->sock_state = STATE_NONE; return mock(pb); } /* The Pubnub version stubs */ char const* pubnub_sdk_name(void) { return "unit-test"; } char const* pubnub_version(void) { return "0.1"; } char const* pubnub_uname(void) { return "unit-test-0.1"; } char const* pubnub_uagent(void) { return "POSIX-PubNub-C-core/" PUBNUB_SDK_VERSION; } /* Assert "catching" */ static bool m_expect_assert; static jmp_buf m_assert_exp_jmpbuf; static char const* m_expect_assert_file; void assert_handler(char const* s, const char* file, long i) { printf("%s:%ld: Pubnub assert failed '%s'\n", file, i, s); } void test_assert_handler(char const* s, const char* file, long i) { // mock(s, i); printf("%s:%ld: Pubnub assert failed '%s'\n", file, i, s); attest(m_expect_assert); attest(m_expect_assert_file, streqs(file)); if (m_expect_assert) { m_expect_assert = false; longjmp(m_assert_exp_jmpbuf, 1); } } #define expect_assert_in(expr, file) \ { \ m_expect_assert = true; \ m_expect_assert_file = file; \ int val = setjmp(m_assert_exp_jmpbuf); \ if (0 == val) \ expr; \ attest(!m_expect_assert); \ } /* The tests themselves */ Ensure(/*pbjson_parse, */ get_object_value_valid) { char const* json = "{\"some\\key\\\"\": \"some\\value\",\"service\": " "\"xxx\", \"error\": true, " "\"payload\":{\"group\":\"gr\", \"some\\\"\\key\": " "value,\"chan\":[1,2,3]}, \"message\":0}"; struct pbjson_elem elem = { json, json + strlen(json) }; struct pbjson_elem parsed; attest(pbjson_get_object_value(&elem, "some\\key\\\"", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string(&parsed, "some\\value"), is_false); attest(pbjson_elem_equals_string(&parsed, "\"some\\value\""), is_true); attest(pbjson_get_object_value(&elem, "error", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string(&parsed, "true"), is_true); attest(pbjson_get_object_value(&elem, "service", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string(&parsed, "\"xxx\""), is_true); attest(pbjson_get_object_value(&elem, "message", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string(&parsed, "0"), is_true); attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string( &parsed, "{\"group\":\"gr\", \"some\\\"\\key\": value,\"chan\":[1,2,3]}"), is_true); attest(pbjson_object_name_parse_result_2_string(jonmpOK), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpOK)), is_greater_than(1)); } Ensure(/*pbjson_parse, */ get_object_value_invalid) { char const* json = "{\"service\": \"xxx\", \"error\": true, " "\"payload\":{\"group\":\"gr\",\"chan\":[1,2,3]}, " "\"message\":0}"; struct pbjson_elem elem = { json, json + strlen(json) }; struct pbjson_elem parsed; attest(pbjson_get_object_value(&elem, "", &parsed), equals(jonmpInvalidKeyName)); attest(pbjson_object_name_parse_result_2_string(jonmpInvalidKeyName), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpInvalidKeyName)), is_greater_than(1)); elem.end = elem.start; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpObjectIncomplete)); attest(pbjson_object_name_parse_result_2_string(jonmpObjectIncomplete), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpObjectIncomplete)), is_greater_than(1)); elem.end = elem.start + 1; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpKeyMissing)); attest(pbjson_object_name_parse_result_2_string(jonmpKeyMissing), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpKeyMissing)), is_greater_than(1)); elem.end = elem.start + 2; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpStringNotTerminated)); attest(pbjson_object_name_parse_result_2_string(jonmpStringNotTerminated), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpStringNotTerminated)), is_greater_than(1)); elem.end = elem.start + 10; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpMissingColon)); attest(pbjson_object_name_parse_result_2_string(jonmpMissingColon), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpMissingColon)), is_greater_than(1)); elem.end = elem.start + 11; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpMissingValueSeparator)); attest(pbjson_object_name_parse_result_2_string(jonmpMissingValueSeparator), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpMissingValueSeparator)), is_greater_than(1)); elem.end = elem.start + 12; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpMissingValueSeparator)); elem.end = elem.start + 13; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpValueIncomplete)); elem.end = elem.start + 17; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpObjectIncomplete)); elem.end = elem.start + 18; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpKeyMissing)); elem.end = elem.start + 19; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpKeyMissing)); elem.end = elem.start + 20; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpStringNotTerminated)); elem.end = elem.start + 26; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpMissingColon)); elem.end = elem.start + 27; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpMissingValueSeparator)); elem.start = json + 1; attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpNoStartCurly)); attest(pbjson_object_name_parse_result_2_string(jonmpNoStartCurly), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpNoStartCurly)), is_greater_than(1)); char const* json_2 = "{x:2}"; elem.start = json_2; elem.end = json_2 + strlen(json_2); attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpKeyNotString)); attest(pbjson_object_name_parse_result_2_string(jonmpKeyNotString), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpKeyNotString)), is_greater_than(1)); char const* json_no_colon = "{\"x\" 2}"; elem.start = json_no_colon; elem.end = json_no_colon + strlen(json_no_colon); attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpMissingColon)); } Ensure(/*pbjson_parse, */ get_object_value_key_doesnt_exist) { char const* json = "{\"service\": \"xxx\", \"error\": true, " "\"payload\":{\"group\":\"gr\",\"chan\":[1,2,3]}, " "\"message\":0}"; struct pbjson_elem elem = { json, json + strlen(json) }; struct pbjson_elem parsed; attest(pbjson_get_object_value(&elem, "zec", &parsed), equals(jonmpKeyNotFound)); attest(pbjson_get_object_value(&elem, "xxx", &parsed), equals(jonmpKeyNotFound)); attest(pbjson_get_object_value(&elem, "\"service\"", &parsed), equals(jonmpKeyNotFound)); attest(pbjson_get_object_value(&elem, "servic", &parsed), equals(jonmpKeyNotFound)); attest(pbjson_get_object_value(&elem, "ervice", &parsed), equals(jonmpKeyNotFound)); attest(pbjson_get_object_value(&elem, "essage", &parsed), equals(jonmpKeyNotFound)); attest(pbjson_get_object_value(&elem, "messag", &parsed), equals(jonmpKeyNotFound)); attest(pbjson_get_object_value(&elem, "messagg", &parsed), equals(jonmpKeyNotFound)); attest(pbjson_get_object_value(&elem, "mmessag", &parsed), equals(jonmpKeyNotFound)); attest(pbjson_object_name_parse_result_2_string(jonmpKeyNotFound), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(jonmpKeyNotFound)), is_greater_than(1)); attest(pbjson_object_name_parse_result_2_string(10), differs(NULL)); attest(strlen(pbjson_object_name_parse_result_2_string(10)), is_greater_than(1)); } Ensure(/*pbjson_parse, */ incomplete_json) { char const* json = "{\"some\\key\": \"some\\value\",\"service\": \"xxx\", " "\"error\": true, \"payload\":{\"group\":\"gr\", " "\"some\\\\key\": value,\"chan\":[1," /*2,3]}, \"message\":0}"*/; struct pbjson_elem elem = { json, json + strlen(json) }; struct pbjson_elem parsed; attest(pbjson_get_object_value(&elem, "some\\key", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string(&parsed, "some\\value"), is_false); attest(pbjson_elem_equals_string(&parsed, "\"some\\value\""), is_true); attest(pbjson_get_object_value(&elem, "error", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string(&parsed, "true"), is_true); attest(pbjson_get_object_value(&elem, "service", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string(&parsed, "\"xxx\""), is_true); attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpValueIncomplete)); char const* json_2 = "{\"some\\key\": \"some\\value\",\"service\": \"xxx\", \"erro"; elem.start = json_2; elem.end = json_2 + strlen(json_2); attest(pbjson_get_object_value(&elem, "error", &parsed), equals(jonmpStringNotTerminated)); attest(pbjson_get_object_value(&elem, "service", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string(&parsed, "\"xxx\""), is_true); attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpStringNotTerminated)); char const* json_3 = "{\"some\\key\": \"some\\value\",\"service\": " "\"xxx\", \"error\":tru\0 }"; elem.start = json_3; elem.end = json_3 + strlen(json_3) + 3; attest(pbjson_get_object_value(&elem, "error", &parsed), equals(jonmpValueIncomplete)); char const* json_4 = "{\"some\\key\": \"some\\value\",\"ser\0ice\": \"xxx\""; elem.start = json_4; elem.end = json_4 + strlen(json_4) + 11; attest(pbjson_get_object_value(&elem, "service", &parsed), equals(jonmpStringNotTerminated)); } Ensure(/*pbjson_parse, */ gibberish_json) { char const* json = "{\"some\\key\": \"some\\value\",\"service\": \"xxx\", " "\"error\": true, \"payload\":{\"group\":\"gr\", " "\"some\\key\": [{\"chan\":[1,2]}}]"; struct pbjson_elem elem = { json, json + strlen(json) }; struct pbjson_elem parsed; attest(pbjson_get_object_value(&elem, "some\\key", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string(&parsed, "some\\value"), is_false); attest(pbjson_elem_equals_string(&parsed, "\"some\\value\""), is_true); attest(pbjson_get_object_value(&elem, "payload", &parsed), equals(jonmpOK)); attest(pbjson_elem_equals_string( &parsed, "{\"group\":\"gr\", \"some\\key\": [{\"chan\":[1,2]}}]"), is_true); } Describe(single_context_pubnub); static pubnub_t* pbp; BeforeEach(single_context_pubnub) { pubnub_assert_set_handler((pubnub_assert_handler_t)assert_handler); m_read = NULL; m_num_string_msgs_rcvd = 0; m_num_uint8_data_blocks = 0; m_i = 0; m_j = 0; pbp = pubnub_alloc(); assert(pbp != NULL); pubnub_origin_set(pbp, NULL); } void free_m_msgs(char** msg_array) { int i; assert(m_num_string_msgs_rcvd < sizeof m_string_msg_array + 1); for (i = 0; i < m_num_string_msgs_rcvd; i++) { assert(m_string_msg_array[i] != NULL); free(m_string_msg_array[i]); m_string_msg_array[i] = NULL; } } AfterEach(single_context_pubnub) { if (pbp->state != PBS_IDLE) { expect(pbpal_close, when(pb, equals(pbp)), returns(0)); expect(pbpal_closed, when(pb, equals(pbp)), returns(true)); expect(pbpal_forget, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); } expect(pbpal_free, when(pb, equals(pbp))); attest(pubnub_free(pbp), equals(0)); free_m_msgs(m_string_msg_array); } void expect_have_dns_for_pubnub_origin() { expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbpal_resolv_and_connect, when(pb, equals(pbp)), returns(pbpal_connect_success)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); } static inline void expect_outgoing_with_url(char const* url) { expect(pbpal_send_str, when(s, streqs("GET ")), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbpal_send_str, when(s, streqs(url)), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbpal_send, when(data, streqs(" HTTP/1.1\r\nHost: ")), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbpal_send_str, when(s, streqs(PUBNUB_ORIGIN)), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbpal_send_str, when(s, streqs("\r\nUser-Agent: POSIX-PubNub-C-core/" PUBNUB_SDK_VERSION "\r\n" ACCEPT_ENCODING "\r\n")), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbntf_watch_in_events, when(pb, equals(pbp)), returns(0)); } static inline void incoming(char const* str, struct uint8_block* p_data) { if (str != NULL) { char* pmsg = malloc(sizeof(char) * (strlen(str) + 1)); assert(pmsg != NULL); assert(m_num_string_msgs_rcvd < sizeof m_string_msg_array); /** Marks the bit for string to be read(received) in due time. If the bit is 0 uint8_data_block is expected. */ string_or_uint8block_mask[(m_num_string_msgs_rcvd + m_num_uint8_data_blocks) / 8] |= 1 << (m_num_string_msgs_rcvd + m_num_uint8_data_blocks) % 8; strcpy(pmsg, str); m_string_msg_array[m_num_string_msgs_rcvd++] = pmsg; } if (p_data != NULL) { assert(m_num_uint8_data_blocks < sizeof m_uint8_data_block_array); m_uint8_data_block_array[m_num_uint8_data_blocks++] = p_data; } } static inline void incoming_and_close(char const* str, struct uint8_block* p_data) { incoming(str, p_data); expect(pbpal_close, when(pb, equals(pbp)), returns(0)); // expect(pbpal_closed, when(pb, equals(pbp)), returns(true)); expect(pbpal_forget, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); } static void cancel_and_cleanup(pubnub_t* pbp) { expect(pbpal_close, when(pb, equals(pbp)), returns(0)); expect(pbpal_closed, when(pb, equals(pbp)), returns(true)); expect(pbpal_forget, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); pubnub_cancel(pbp); attest(pbp->core.last_result, equals(PNR_CANCELLED)); } /* -- LEAVE operation -- */ Ensure(single_context_pubnub, leave_have_dns) { pubnub_init(pbp, "pubkey", "subkey"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/subkey/channel/lamanche/" "leave?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_leave(pbp, "lamanche", NULL), equals(PNR_OK)); attest(pubnub_last_publish_result(pbp), streqs("")); attest(pubnub_last_http_code(pbp), equals(200)); } /* This tests the DNS resolution code. Since we know for sure it is the same for all Pubnub operations/transactions, we shall test it only for "leave". */ Ensure(single_context_pubnub, leave_wait_dns) { pubnub_init(pbp, "pubkey", "subkey"); /* DNS resolution not yet available... */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(+1)); expect(pbpal_resolv_and_connect, when(pb, equals(pbp)), returns(pbpal_resolv_sent)); expect(pbntf_watch_in_events, when(pb, equals(pbp)), returns(0)); attest(pubnub_leave(pbp, "lamanche", NULL), equals(PNR_STARTED)); /* ... still not available... */ expect(pbpal_check_resolv_and_connect, when(pb, equals(pbp)), returns(pbpal_resolv_rcv_wouldblock)); attest(pbnc_fsm(pbp), equals(0)); /* ... and here it is: */ expect(pbntf_update_socket, when(pb, equals(pbp)), returns(+1)); expect(pbntf_watch_out_events, when(pb, equals(pbp))); expect(pbpal_check_resolv_and_connect, when(pb, equals(pbp)), returns(pbpal_connect_success)); expect_outgoing_with_url("/v2/presence/sub-key/subkey/channel/lamanche/" "leave?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, leave_wait_dns_cancel) { pubnub_init(pbp, "pubkey", "subkey"); /* DNS resolution not yet available... */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(+1)); expect(pbpal_resolv_and_connect, when(pb, equals(pbp)), returns(pbpal_resolv_sent)); expect(pbntf_watch_in_events, when(pb, equals(pbp)), returns(0)); attest(pubnub_leave(pbp, "lamanche", NULL), equals(PNR_STARTED)); /* ... user is impatient... */ cancel_and_cleanup(pbp); } /* This tests the TCP establishment code. Since we know for sure it is the same for all Pubnub operations/transactions, we shall test it only for "leave". */ Ensure(single_context_pubnub, leave_wait_tcp) { pubnub_init(pbp, "pubkey", "subkey"); /* DNS resolved but TCP connection not yet established... */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(+1)); expect(pbpal_resolv_and_connect, when(pb, equals(pbp)), returns(pbpal_connect_wouldblock)); attest(pubnub_leave(pbp, "lamanche", NULL), equals(PNR_STARTED)); /* ... and here it is: */ expect(pbpal_check_connect, when(pb, equals(pbp)), returns(pbpal_connect_success)); expect_outgoing_with_url("/v2/presence/sub-key/subkey/channel/lamanche/" "leave?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, leave_wait_tcp_cancel) { pubnub_init(pbp, "pubkey", "subkey"); /* DNS resolved but TCP connection not yet established... */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbpal_resolv_and_connect, when(pb, equals(pbp)), returns(pbpal_connect_wouldblock)); expect(pbpal_check_connect, when(pb, equals(pbp)), returns(pbpal_connect_wouldblock)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); attest(pubnub_leave(pbp, "lamanche", NULL), equals(PNR_STARTED)); /* ... user is impatient... */ cancel_and_cleanup(pbp); } Ensure(single_context_pubnub, leave_changroup) { pubnub_init(pbp, "kpub", "ssub"); /* Both channel and channel group set */ expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/ssub/channel/k1/" "leave?pnsdk=unit-test-0.1&channel-group=tnt"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_leave(pbp, "k1", "tnt"), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); /* Only channel group set */ /* We dont have to do DNS resolution again on the same context already in use. The connection keeps beeing established by default. */ // expect_have_dns_for_pubnub_origin(); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/ssub/channel/,/" "leave?pnsdk=unit-test-0.1&channel-group=mala"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_leave(pbp, NULL, "mala"), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); /* Neither channel nor channel group set */ attest(pubnub_leave(pbp, NULL, NULL), equals(PNR_INVALID_CHANNEL)); } Ensure(single_context_pubnub, leave_uuid_auth) { pubnub_init(pbp, "pubX", "Xsub"); attest(pbp->core.uuid_len, equals(0)); /* Set UUID */ pubnub_set_uuid(pbp, "DEDA-BABACECA-DECA"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/Xsub/channel/k/" "leave?pnsdk=unit-test-0.1&uuid=DEDA-BABACECA-" "DECA"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_leave(pbp, "k", NULL), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pbp->core.uuid_len, equals(18)); /* Set auth, too */ pubnub_set_auth(pbp, "super-secret-key"); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/Xsub/channel/k2/" "leave?pnsdk=unit-test-0.1&uuid=DEDA-BABACECA-" "DECA&auth=super-secret-key"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_leave(pbp, "k2", NULL), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); /* Reset UUID */ pubnub_set_uuid(pbp, NULL); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/Xsub/channel/k3/" "leave?pnsdk=unit-test-0.1&auth=super-secret-key"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_leave(pbp, "k3", NULL), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pbp->core.uuid_len, equals(0)); /* Reset auth, too */ pubnub_set_auth(pbp, NULL); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url( "/v2/presence/sub-key/Xsub/channel/k4/leave?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_leave(pbp, "k4", NULL), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, leave_bad_response) { pubnub_init(pbp, "pubkey", "subkey"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/subkey/channel/lamanche/" "leave?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n[]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_leave(pbp, "lamanche", NULL), equals(PNR_FORMAT_ERROR)); } Ensure(single_context_pubnub, leave_in_progress) { pubnub_init(pbp, "pubkey", "subkey"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/subkey/channel/lamanche/" "leave?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\n", NULL); /* simulates 'callback' condition of PNR_IN_PROGRESS. * expl: recv_msg would return 0 otherwise as if the connection * closes from servers side. */ incoming("", NULL); attest(pubnub_leave(pbp, "lamanche", NULL), equals(PNR_STARTED)); attest(pubnub_leave(pbp, "lamanche", NULL), equals(PNR_IN_PROGRESS)); cancel_and_cleanup(pbp); } /* -- TIME operation -- */ Ensure(single_context_pubnub, time) { pubnub_init(pbp, "tkey", "subt"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/time/0?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 9\r\n\r\n[1643092]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_time(pbp), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_get(pbp), streqs("1643092")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), equals(NULL)); } Ensure(single_context_pubnub, time_bad_response) { pubnub_init(pbp, "tkey", "subt"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/time/0?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 9\r\n\r\n{1643092}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_time(pbp), equals(PNR_FORMAT_ERROR)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), equals(NULL)); } Ensure(single_context_pubnub, time_in_progress) { pubnub_init(pbp, "pubkey", "subkey"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/time/0?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\n", NULL); /* incoming empty string simulates conditions for PNR_IN_PROGRESS */ incoming("", NULL); // expect(pbpal_close, when(pb, equals(pbp)), returns(0)); attest(pubnub_time(pbp), equals(PNR_STARTED)); attest(pubnub_time(pbp), equals(PNR_IN_PROGRESS)); cancel_and_cleanup(pbp); } /* -- PUBLISH operation -- */ Ensure(single_context_pubnub, publish) { pubnub_init(pbp, "publkey", "subkey"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/publish/publkey/subkey/0/jarak/0/%22zec%22?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "30\r\n\r\n[1,\"Sent\",\"14178940800777403\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_last_publish_result(pbp), streqs("")); attest(pubnub_publish(pbp, "jarak", "\"zec\""), equals(PNR_OK)); attest(pubnub_last_publish_result(pbp), streqs("\"Sent\"")); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, publish_change_origin) { pubnub_init(pbp, "publkey", "subkey"); attest(pubnub_get_origin(pbp), streqs(PUBNUB_ORIGIN)); attest(pubnub_origin_set(pbp, "new_origin_server"), equals(0)); expect_have_dns_for_pubnub_origin(); expect(pbpal_send_str, when(s, streqs("GET ")), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbpal_send_str, when(s, streqs("/publish/publkey/subkey/0/jarak/0/%22zec%22?pnsdk=unit-test-0.1")), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbpal_send, when(data, streqs(" HTTP/1.1\r\nHost: ")), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbpal_send_str, when(s, streqs("new_origin_server")), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbpal_send_str, when(s, streqs("\r\nUser-Agent: POSIX-PubNub-C-core/" PUBNUB_SDK_VERSION "\r\n" ACCEPT_ENCODING "\r\n")), returns(0)); expect(pbpal_send_status, returns(0)); expect(pbntf_watch_in_events, when(pb, equals(pbp)), returns(0)); incoming("HTTP/1.1 200\r\nContent-Length: " "30\r\n\r\n[1,\"Sent\",\"14178940800777403\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_last_publish_result(pbp), streqs("")); attest(pubnub_publish(pbp, "jarak", "\"zec\""), equals(PNR_OK)); attest(pubnub_last_publish_result(pbp), streqs("\"Sent\"")); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_get_origin(pbp), streqs("new_origin_server")); } Ensure(single_context_pubnub, publish_http_chunked) { pubnub_init(pbp, "publkey", "subkey"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/publish/publkey/subkey/0/jarak/0/%22zec%22?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nTransfer-Encoding: " "chunked\r\n\r\n12\r\n[1,\"Sent\",\"1417894\r\n0C\r\n0800777403\"]" "\r\n0\r\n", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_last_publish_result(pbp), streqs("")); attest(pubnub_publish(pbp, "jarak", "\"zec\""), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_last_publish_result(pbp), streqs("\"Sent\"")); } Ensure(single_context_pubnub, http_headers_no_content_length_or_chunked) { pubnub_init(pbp, "publkey", "subkey"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/publish/publkey/subkey/0/,/0/%22zec%22?pnsdk=unit-test-0.1"); /* No 'content-length' nor 'chunked' header field */ incoming("HTTP/1.1 400\r\n\r\n[0,\"Invalid\",\"14178940800999505\"]", NULL); expect(pbpal_close, when(pb, equals(pbp)), returns(0)); expect(pbpal_forget, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_last_publish_result(pbp), streqs("")); attest(pubnub_publish(pbp, ",", "\"zec\""), equals(PNR_IO_ERROR)); attest(pubnub_last_publish_result(pbp), streqs("")); } Ensure(single_context_pubnub, publish_failed_invalid_channel) { pubnub_init(pbp, "publkey", "subkey"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/publish/publkey/subkey/0/,/0/%22zec%22?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 400\r\nContent-Length: " "33\r\n\r\n[0,\"Invalid\",\"14178940800999505\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_last_publish_result(pbp), streqs("")); attest(pubnub_publish(pbp, ",", "\"zec\""), equals(PNR_PUBLISH_FAILED)); attest(pubnub_last_publish_result(pbp), streqs("\"Invalid\"")); } Ensure(single_context_pubnub, publish_msg_too_long) { pubnub_init(pbp, "publkey", "subkey"); char msg[PUBNUB_BUF_MAXLEN + 1]; memset(msg, 'A', sizeof msg); msg[sizeof msg - 1] = '\0'; attest(pubnub_publish(pbp, "w", msg), equals(PNR_TX_BUFF_TOO_SMALL)); /* URL encoded char */ memset(msg, '"', sizeof msg); msg[sizeof msg - 1] = '\0'; attest(pubnub_publish(pbp, "w", msg), equals(PNR_TX_BUFF_TOO_SMALL)); attest(pubnub_last_publish_result(pbp), streqs("")); } Ensure(single_context_pubnub, publish_in_progress) { pubnub_init(pbp, "pubkey", "subkey"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/publish/pubkey/subkey/0/jarak/0/4443?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\n", NULL); /* simulates recv_msg() < 0 which saves from closed connection */ incoming("", NULL); attest(pubnub_publish(pbp, "jarak", "4443"), equals(PNR_STARTED)); attest(pubnub_publish(pbp, "x", "0"), equals(PNR_IN_PROGRESS)); cancel_and_cleanup(pbp); } Ensure(single_context_pubnub, publish_uuid_auth) { pubnub_init(pbp, "pubX", "Xsub"); /* Set UUID */ pubnub_set_uuid(pbp, "0ADA-BEDA-0000"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/publish/pubX/Xsub/0/k/0/" "4443?pnsdk=unit-test-0.1&uuid=0ADA-BEDA-0000"); incoming("HTTP/1.1 200\r\nContent-Length: 3\r\n\r\n[1]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_publish(pbp, "k", "4443"), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pbp->core.uuid_len, equals(14)); /* Set auth, too */ pubnub_set_auth(pbp, "bad-secret-key"); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/publish/pubX/Xsub/0/k2/0/" "443?pnsdk=unit-test-0.1&uuid=0ADA-BEDA-0000&auth=" "bad-secret-key"); incoming("HTTP/1.1 200\r\nContent-Length: 3\r\n\r\n[1]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_publish(pbp, "k2", "443"), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); /* Reset UUID */ pubnub_set_uuid(pbp, NULL); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/publish/pubX/Xsub/0/k3/0/" "4443?pnsdk=unit-test-0.1&auth=bad-secret-key"); incoming("HTTP/1.1 200\r\nContent-Length: 3\r\n\r\n[1]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_publish(pbp, "k3", "4443"), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pbp->core.uuid_len, equals(0)); /* Reset auth, too */ pubnub_set_auth(pbp, NULL); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url( "/publish/pubX/Xsub/0/k4/0/443?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 3\r\n\r\n[1]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_publish(pbp, "k4", "443"), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, publish_bad_response) { pubnub_init(pbp, "tkey", "subt"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/publish/tkey/subt/0/k6/0/443?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 9\r\n\r\n<\"1\":\"X\">", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_publish(pbp, "k6", "443"), equals(PNR_FORMAT_ERROR)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_last_publish_result(pbp), streqs("")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), equals(NULL)); } Ensure(single_context_pubnub, publish_failed_server_side) { pubnub_init(pbp, "tkey", "subt"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/publish/tkey/subt/0/k6/0/443?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 9\r\n\r\n{\"1\":\"X\"}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_publish(pbp, "k6", "443"), equals(PNR_PUBLISH_FAILED)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_last_publish_result(pbp), streqs("\"1\":\"X\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), equals(NULL)); } /* -- HISTORY operation -- */ Ensure(single_context_pubnub, history_without_timetoken) { pubnub_init(pbp, "publhis", "subhis"); /* Without time-token */ expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/history/sub-key/subhis/channel/" "ch?pnsdk=unit-test-0.1&count=22&include_token=" "false"); incoming("HTTP/1.1 200\r\nContent-Length: " "45\r\n\r\n[[1,2,3],14370854953886727,14370864554607266]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_history(pbp, "ch", 22, false), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("[1,2,3]")); attest(pubnub_get(pbp), streqs("14370854953886727")); attest(pubnub_get(pbp), streqs("14370864554607266")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, history_with_timetoken) { pubnub_init(pbp, "publhis", "subhis"); /* With time-token */ expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/history/sub-key/subhis/channel/" "ch?pnsdk=unit-test-0.1&count=22&include_token=" "true"); incoming("HTTP/1.1 200\r\nContent-Length: " "171\r\n\r\n[[{\"message\":1,\"timetoken\":14370863460777883},{" "\"message\":2,\"timetoken\":14370863461279046},{\"message\":3," "\"timetoken\":14370863958459501}],14370863460777883," "14370863958459501]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_history(pbp, "ch", 22, true), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("[{\"message\":1,\"timetoken\":14370863460777883},{" "\"message\":2,\"timetoken\":14370863461279046},{\"message\":" "3,\"timetoken\":14370863958459501}]")); attest(pubnub_get(pbp), streqs("14370863460777883")); attest(pubnub_get(pbp), streqs("14370863958459501")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, history_in_progress) { pubnub_init(pbp, "publhis", "subhis"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/history/sub-key/subhis/channel/" "ch?pnsdk=unit-test-0.1&count=22&include_token=" "false"); incoming("HTTP/1.1 200\r\n", NULL); incoming("", NULL); attest(pubnub_history(pbp, "ch", 22, false), equals(PNR_STARTED)); attest(pubnub_history(pbp, "x", 55, false), equals(PNR_IN_PROGRESS)); cancel_and_cleanup(pbp); } Ensure(single_context_pubnub, history_auth) { pubnub_init(pbp, "pubX", "Xsub"); pubnub_set_auth(pbp, "go-secret-key"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/history/sub-key/Xsub/channel/" "hhh?pnsdk=unit-test-0.1&count=" "40&include_token=false&auth=go-secret-key"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n[]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_history(pbp, "hhh", 40, false), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, history_bad_response) { pubnub_init(pbp, "pubkey", "Xsub"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/history/sub-key/Xsub/channel/" "ttt?pnsdk=unit-test-0.1&count=10&include_token=" "false"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n{}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_history(pbp, "ttt", 10, false), equals(PNR_FORMAT_ERROR)); } /* -- ADVANCED HISTORY message_counts -- */ #if PUBNUB_USE_ADVANCED_HISTORY Ensure(single_context_pubnub, gets_advanced_history_message_counts_for_two_channels_since_timetoken) { size_t io_count = 2; struct pubnub_chan_msg_count chan_msg_counters[2]; pubnub_chamebl_t channel_1 = {"some", sizeof "some" - 1}; pubnub_chamebl_t channel_2 = {"other", sizeof "other" - 1}; pubnub_init(pbp, "pub-nina", "sub-pinta"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v3/history/sub-key/sub-pinta/message-counts/" "some,other?pnsdk=unit-test-0.1&timetoken=14378854953886727"); incoming("HTTP/1.1 200\r\nContent-Length: 85\r\n\r\n" "{\"status\":200, \"error\": false, \"error_message\": \"\", \"channels\": {\"some\":1,\"other\":5}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_message_counts(pbp, "some,other", "14378854953886727"), equals(PNR_OK)); attest(pubnub_get_chan_msg_counts_size(pbp), equals(2)); attest(pubnub_get_chan_msg_counts(pbp, &io_count, chan_msg_counters), equals(0)); attest(io_count, equals(2)); attest(strncmp(chan_msg_counters[0].channel.ptr, channel_1.ptr, channel_1.size), equals(0)); attest(chan_msg_counters[0].channel.size, equals(channel_1.size)); attest(chan_msg_counters[0].message_count, equals(1)); attest(strncmp(chan_msg_counters[1].channel.ptr, channel_2.ptr, channel_2.size), equals(0)); attest(chan_msg_counters[1].channel.size, equals(channel_2.size)); attest(chan_msg_counters[1].message_count, equals(5)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, gets_message_counts_for_two_channels_since_channel_timetokens) { size_t io_count = 2; struct pubnub_chan_msg_count chan_msg_counters[2]; pubnub_chamebl_t channel_1 = {"ocean", sizeof "ocean" - 1}; pubnub_chamebl_t channel_2 = {"wind", sizeof "wind" - 1}; pubnub_init(pbp, "pub-mission", "sub-santa-maria"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v3/history/sub-key/sub-santa-maria/message-counts/" "ocean,wind?pnsdk=unit-test-0.1&channelsTimetoken=" "14378854953886727,14378856783886727"); incoming("HTTP/1.1 200\r\nContent-Length: 87\r\n\r\n" "{\"status\":200, \"error\": false, \"error_message\": \"\", \"channels\": {\"wind\":18,\"ocean\":76}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_message_counts(pbp, "ocean,wind", "14378854953886727,14378856783886727"), equals(PNR_OK)); attest(pubnub_get_chan_msg_counts_size(pbp), equals(2)); attest(pubnub_get_chan_msg_counts(pbp, &io_count, chan_msg_counters), equals(0)); attest(io_count, equals(2)); attest(strncmp(chan_msg_counters[0].channel.ptr, channel_2.ptr, channel_2.size), equals(0)); attest(chan_msg_counters[0].channel.size, equals(channel_2.size)); attest(chan_msg_counters[0].message_count, equals(18)); attest(strncmp(chan_msg_counters[1].channel.ptr, channel_1.ptr, channel_1.size), equals(0)); attest(chan_msg_counters[1].channel.size, equals(channel_1.size)); attest(chan_msg_counters[1].message_count, equals(76)); /* Message is read */ attest(pubnub_get_chan_msg_counts(pbp, &io_count, chan_msg_counters), equals(0)); attest(io_count, equals(0)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, get_message_counts_gets_message_counts_for_three_channels_since_channel_timetokens) { int o_count[3]; pubnub_init(pbp, "pub-delta", "sub-echo"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v3/history/sub-key/sub-echo/message-counts/" "bravo,alfa,charlie?pnsdk=unit-test-0.1&channelsTimetoken=" "15378854953886727,15378856783886727,15378856783886727"); incoming("HTTP/1.1 200\r\nContent-Length: 106\r\n\r\n" "{\"status\":200, \"error\": false, \"error_message\": \"\", \"channels\": {\"charlie\":25,\"alfa\":196 , \"bravo\":3 } }", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_message_counts(pbp, "bravo,alfa,charlie", "15378854953886727,15378856783886727,15378856783886727"), equals(PNR_OK)); attest(pubnub_get_chan_msg_counts_size(pbp), equals(sizeof o_count/sizeof o_count[0])); attest(pubnub_get_message_counts(pbp, "alfa,charlie,bravo", o_count), equals(0)); attest(o_count[0], equals(196)); attest(o_count[1], equals(25)); attest(o_count[2], equals(3)); /* Message is already read in full */ attest(pubnub_get_chan_msg_counts_size(pbp), equals(0)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, handles_an_error_reported_from_server_on_message_counts_request) { int o_count[3]; char msg[sizeof "there must be some kind of mistake"]; pubnub_chamebl_t o_msg = {msg,}; pubnub_init(pbp, "pub-foxtrot", "sub-golf"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v3/history/sub-key/sub-golf/message-counts/" "hotel?pnsdk=unit-test-0.1&timetoken=" "15578854953886727"); incoming("HTTP/1.1 404\r\nContent-Length: 105\r\n\r\n" "{\"status\":404 , \"error\": true, \"error_message\" : \"there must be some kind of mistake\", \"channels\": {} }", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_message_counts(pbp, "hotel", "15578854953886727"), equals(PNR_ERROR_ON_SERVER)); attest(pubnub_get_error_message(pbp, &o_msg), equals(0)); attest(o_msg.size, equals(sizeof "there must be some kind of mistake" - 1)); attest(strncmp(o_msg.ptr, "there must be some kind of mistake", o_msg.size), equals(0)); /* Using the same test, but assuming that it was successful response on corresponding pubnub_message_counts() request that got object 'channels', but without any values in it. pubnub_get_message_counts() will set corresponding array members(message counters) to negative values. */ attest(pubnub_get_message_counts(pbp, "kilo,lima,mike", o_count), equals(0)); attest(o_count[0], is_less_than(0)); attest(o_count[1], is_less_than(0)); attest(o_count[2], is_less_than(0)); attest(pubnub_last_http_code(pbp), equals(404)); } Ensure(single_context_pubnub, handles_wrong_format_in_the_response_on_message_counts_request) { char msg[sizeof "some kind of mistake"]; pubnub_chamebl_t o_msg = {msg,}; pubnub_init(pbp, "pub-november", "sub-oscar"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v3/history/sub-key/sub-oscar/message-counts/" "papa,quebec?pnsdk=unit-test-0.1&channelsTimetoken=" "15578854953886727,15516381360410684"); /* Starting 'curly' is missing */ incoming("HTTP/1.1 404\r\nContent-Length: 104\r\n\r\n" "\"status\":404 , \"error\": true, \"error_message\" : \"there must be some kind of mistake\", \"channels\": {} }", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_message_counts(pbp, "papa,quebec", "15578854953886727,15516381360410684"), equals(PNR_FORMAT_ERROR)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v3/history/sub-key/sub-oscar/message-counts/" "papa?pnsdk=unit-test-0.1&timetoken=" "15578854953886727"); /* 'error_message' is missing */ incoming("HTTP/1.1 404\r\nContent-Length: 47\r\n\r\n" "{\"status\":404 , \"error\": true, \"channels\": {} }", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_message_counts(pbp, "papa", "15578854953886727"), equals(PNR_ERROR_ON_SERVER)); attest(pubnub_get_error_message(pbp, &o_msg), equals(-1)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v3/history/sub-key/sub-oscar/message-counts/" "papa?pnsdk=unit-test-0.1&timetoken=" "15378854953886727"); /* 'error' is missing */ incoming("HTTP/1.1 404\r\nContent-Length: 90\r\n\r\n" "{\"status\":404 , \"error_message\" : \"there must be some kind of mistake\", \"channels\": {} }", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_message_counts(pbp, "papa", "15378854953886727"), equals(PNR_FORMAT_ERROR)); attest(pubnub_last_http_code(pbp), equals(404)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v3/history/sub-key/sub-oscar/message-counts/" "papa?pnsdk=unit-test-0.1&timetoken=" "15378854953886727"); /* 'channels' are missing */ incoming("HTTP/1.1 200\r\nContent-Length: 76\r\n\r\n" "{\"status\":200 , \"error\": false, \"error_message\" : \"some kind of mistake\" }", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_message_counts(pbp, "papa", "15378854953886727"), equals(PNR_FORMAT_ERROR)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, handles_irregular_use_of_advanced_history_message_counts_functions) { size_t io_count; struct pubnub_chan_msg_count chan_msg_counters[1]; int o_count[3]; char msg[10]; pubnub_chamebl_t o_msg = {msg,}; pubnub_init(pbp, "pub-india", "sub-juliett"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v3/history/sub-key/sub-juliett/message-counts/" "kilo,lima,mike?pnsdk=unit-test-0.1&channelsTimetoken=" "15378856783886727,15378856783886727,15378854953886727"); incoming("HTTP/1.1 200\r\nContent-Length: 130\r\n\r\n" "{\"status\":200, \"error\": false, \"error_message\"", NULL); /* incoming empty string simulates conditions for PNR_IN_PROGRESS */ incoming("", NULL); attest(pubnub_message_counts(pbp, "kilo,lima,mike", "15378856783886727,15378856783886727,15378854953886727"), equals(PNR_STARTED)); /* None of these functions should do anything since transaction is in progress */ attest(pubnub_get_error_message(pbp, &o_msg), equals(-1)); attest(pubnub_get_chan_msg_counts_size(pbp), equals(-1)); attest(pubnub_get_chan_msg_counts(pbp, &io_count, chan_msg_counters), equals(-1)); attest(pubnub_get_message_counts(pbp, "kilo,lima,mike", o_count), equals(-1)); attest(pubnub_message_counts(pbp, "bravo,alfa,charlie", "15378856783886727,15378856783886727,15378854953886727"), equals(PNR_IN_PROGRESS)); incoming(" : \"there is no mistake\", \"channels\": { \"mike\" : 52 , \"kilo\":75 , \"lima\" : 0 } }", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); /* Transaction just finished. Have to read the response first before we start a new one */ attest(pubnub_message_counts(pbp, "bravo,alfa,charlie", "15578856783886727,15578856783886727,15578854953886727"), equals(PNR_RX_BUFF_NOT_EMPTY)); attest(pubnub_get_chan_msg_counts_size(pbp), equals(sizeof o_count/sizeof o_count[0])); attest(pubnub_get_message_counts(pbp, "kilo,lima,mike ", o_count), equals(0)); attest(o_count[0], equals(75)); attest(o_count[1], equals(0)); attest(o_count[2], equals(52)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, get_chan_msg_counts_gets_message_counts_for_two_channels_but_the_answer_has_three) { struct pubnub_chan_msg_count chan_msg_counters[2]; size_t io_count = sizeof chan_msg_counters/sizeof chan_msg_counters[0]; pubnub_chamebl_t channel_1 = {"tango", sizeof "tango" - 1}; pubnub_chamebl_t channel_2 = {"sierra", sizeof "sierra" - 1}; pubnub_init(pbp, "pub-quebeq", "sub-romeo"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v3/history/sub-key/sub-romeo/message-counts/" "sierra,tango?pnsdk=unit-test-0.1&channelsTimetoken=" "15378854953886727,15378856783886727"); incoming("HTTP/1.1 200\r\nContent-Length: 112\r\n\r\n" "{\"status\":200, \"error\": false, \"error_message\": \"\", \"channels\": { \"tango\":38 , \"sierra\":17 , \"uniform\": 51 } }", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_message_counts(pbp, "sierra,tango", "15378854953886727,15378856783886727"), equals(PNR_OK)); attest(pubnub_get_chan_msg_counts_size(pbp), equals(3)); attest(pubnub_get_chan_msg_counts(pbp, &io_count, chan_msg_counters), equals(0)); attest(io_count, equals(sizeof chan_msg_counters/sizeof chan_msg_counters[0])); attest(strncmp(chan_msg_counters[0].channel.ptr, channel_1.ptr, channel_1.size), equals(0)); attest(chan_msg_counters[0].channel.size, equals(channel_1.size)); attest(chan_msg_counters[0].message_count, equals(38)); attest(strncmp(chan_msg_counters[1].channel.ptr, channel_2.ptr, channel_2.size), equals(0)); attest(chan_msg_counters[1].channel.size, equals(channel_2.size)); attest(chan_msg_counters[1].message_count, equals(17)); /* Message is read */ attest(pubnub_get_chan_msg_counts_size(pbp), equals(0)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, advanced_history_message_counts_handles_invalid_timetokens) { pubnub_init(pbp, "pub-delta", "sub-echo"); attest(pubnub_message_counts(pbp, "victor", "153"), equals(PNR_INVALID_PARAMETERS)); attest(pubnub_message_counts(pbp, "victor", " 15378854953886727"), equals(PNR_INVALID_PARAMETERS)); attest(pubnub_message_counts(pbp, "victor,whiskey", "15378854953886727 ,15378856783886727"), equals(PNR_INVALID_PARAMETERS)); attest(pubnub_message_counts(pbp, "victor,whiskey", "15378854953886727,727"), equals(PNR_INVALID_PARAMETERS)); attest(pubnub_message_counts(pbp, "victor,whiskey", "727,15378854953886727"), equals(PNR_INVALID_PARAMETERS)); attest(pubnub_message_counts(pbp, "victor", "15378854953886727,15378856783886727"), equals(PNR_INVALID_PARAMETERS)); attest(pubnub_message_counts(pbp, "x-ray, yankee, zulu", "15378854953886727,15378856783886727"), equals(PNR_INVALID_PARAMETERS)); } Ensure(single_context_pubnub, advanced_history_message_counts_handles_invalid_channels) { char channel_name_too_long[PUBNUB_MAX_CHANNEL_NAME_LENGTH + 4]; pubnub_init(pbp, "pub-delta", "sub-echo"); memset(channel_name_too_long, 'a', sizeof channel_name_too_long - 1); channel_name_too_long[sizeof channel_name_too_long - 1] = '\0'; attest(pubnub_message_counts(pbp, channel_name_too_long, "15378854953886727"), equals(PNR_INVALID_PARAMETERS)); /* comma just after the beginning of the channel list(one character in between) */ channel_name_too_long[1] = ','; attest(pubnub_message_counts(pbp, channel_name_too_long, "15378854953886727"), equals(PNR_INVALID_PARAMETERS)); attest(pubnub_message_counts(pbp, channel_name_too_long, "15378854953886727,15378856783886727"), equals(PNR_INVALID_PARAMETERS)); /* comma just before the end of channel list string(one character in between) */ channel_name_too_long[1] = 'b'; channel_name_too_long[sizeof channel_name_too_long - 3] = ','; attest(pubnub_message_counts(pbp, channel_name_too_long, "15378854953886727"), equals(PNR_INVALID_PARAMETERS)); attest(pubnub_message_counts(pbp, channel_name_too_long, "15378854953886727,15378856783886727"), equals(PNR_INVALID_PARAMETERS)); } #endif /* -- ADVANCED HISTORY message_counts -- */ /* -- SET_STATE operation -- */ Ensure(single_context_pubnub, set_state) { pubnub_init(pbp, "publhis", "subhis"); /* with uuid from context */ pubnub_set_uuid(pbp, "universal"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/subhis/channel/ch/uuid/" "universal/data?pnsdk=unit-test-0.1&state=%7B%7D"); incoming("HTTP/1.1 200\r\nContent-Length: 67\r\n\r\n{\"status\": " "200,\"message\":\"OK\", \"service\": \"Presence\", " "\"payload\":{}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_set_state(pbp, "ch", NULL, NULL, "{}"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(9)); attest(pubnub_get(pbp), streqs("{\"status\": 200,\"message\":\"OK\", \"service\": \"Presence\", \"payload\":{}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* with 'auth' set in context and 'uuid' from parameter to the function */ pubnub_set_auth(pbp, "auth-key"); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/subhis/channel/ch/uuid/" "shazalakazoo/" "data?pnsdk=unit-test-0.1&auth=auth-key&state=%7B%7D"); incoming("HTTP/1.1 200\r\nContent-Length: " "63\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_set_state(pbp, "ch", NULL, "shazalakazoo", "{}"), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\",\"payload\":{}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* set state to 'channel group(s)' with 'auth' set in context and 'uuid' * from parameter to the function */ pubnub_set_auth(pbp, "authentic"); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/subhis/channel/,/uuid/" "melwokee/" "data?pnsdk=unit-test-0.1&channel-" "group=[gr1,gr2]&auth=authentic&state=%7BIOW%7D"); incoming("HTTP/1.1 200\r\nContent-Length: " "66\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{IOW}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_set_state(pbp, NULL, "[gr1,gr2]", "melwokee", "{IOW}"), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\",\"payload\":{IOW}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* set state to 'channel(s)' and 'channel group(s)' with 'auth' set in * context and 'uuid' from parameter to the function */ pubnub_set_auth(pbp, "three"); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/subhis/channel/[ch1,ch2]/" "uuid/linda-darnell/" "data?pnsdk=unit-test-0.1&channel-group=" "[gr3,gr4]&auth=three&state=%7BI%7D"); incoming("HTTP/1.1 200\r\nContent-Length: " "64\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{I}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_set_state(pbp, "[ch1,ch2]", "[gr3,gr4]", "linda-darnell", "{I}"), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\",\"payload\":{I}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* set state for no 'channel' and no 'channel group'. */ pubnub_set_auth(pbp, NULL); // with or without this line attest(pubnub_set_state(pbp, NULL, NULL, "linda-darnell", "{I}"), equals(PNR_INVALID_CHANNEL)); } Ensure(single_context_pubnub, set_state_in_progress) { pubnub_init(pbp, "publ-one", "sub-one"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/sub-one/channel/ch/uuid/blackbeard/" "data?pnsdk=unit-test-0.1&state=%7B%22the_pirate%22%3A%22true%22%7D"); incoming("HTTP/1.1 200\r\n", NULL); incoming("", NULL); attest(pubnub_set_state(pbp, "ch", NULL, "blackbeard", "{\"the_pirate\":\"true\"}"), equals(PNR_STARTED)); attest(pubnub_set_state( pbp, "ch", NULL, "blackbeard", "{\"the_pirate\":\"arrrrrrr_arrrrr\"}"), equals(PNR_IN_PROGRESS)); cancel_and_cleanup(pbp); } Ensure(single_context_pubnub, set_state_in_progress_interrupted_and_accomplished) { pubnub_init(pbp, "publ-one", "sub-one"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/sub-one/channel/ch/uuid/blackbeard/" "data?pnsdk=unit-test-0.1&state=%7B%22the_pirate%22%3A%22true%22%7D"); /* incoming first message */ incoming("HTTP/1.1 200\r\n", NULL); incoming("", NULL); attest(pubnub_set_state(pbp, "ch", NULL, "blackbeard", "{\"the_pirate\":\"true\"}"), equals(PNR_STARTED)); attest(pubnub_set_state( pbp, "ch", NULL, "blackbeard", "{\"the_pirate\":\"arrrrrrr_arrrrr\"}"), equals(PNR_IN_PROGRESS)); /* incoming second and last message */ incoming("Content-Length: " "82\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{\"the_pirate\":\"true\"}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\",\"payload\":{\"the_pirate\":\"true\"}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, set_state_set_auth_and_uuid) { pubnub_init(pbp, "pubX", "Xsub"); pubnub_set_auth(pbp, "portobello"); pubnub_set_uuid(pbp, "morgan"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/Xsub/channel/ch/uuid/morgan/" "data?pnsdk=unit-test-0.1&auth=portobello&state=%7B%22the_privateer%22%3A%22letter_of_marque%22%7D"); incoming("HTTP/1.1 200\r\nContent-Length: " "96\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{\"the_privateer\":\"letter_of_" "marque\"}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_set_state( pbp, "ch", NULL, NULL, "{\"the_privateer\":\"letter_of_marque\"}"), equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pbp->core.uuid_len, equals(6)); } Ensure(single_context_pubnub, set_state_bad_response) { pubnub_init(pbp, "pubkey", "Xsub"); pubnub_set_uuid(pbp, "chili_peppers"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/Xsub/channel/ch/uuid/chili_peppers/" "data?pnsdk=unit-test-0.1&state=%7B%22chili%22%3A%22red%22%7D"); incoming("HTTP/1.1 200\r\nContent-Length: 2\r\n\r\n<chiki, chiki bum, " "chiki bum]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_set_state(pbp, "ch", NULL, NULL, "{\"chili\":\"red\"}"), equals(PNR_FORMAT_ERROR)); attest(pbp->core.uuid_len, equals(13)); } /* STATE_GET operation */ Ensure(single_context_pubnub, state_get_1channel) { pubnub_init(pbp, "key", "subY"); /* with uuid from context */ pubnub_set_uuid(pbp, "speedy"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/subY/channel/ch/uuid/speedy?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 76\r\n\r\n{\"status\": " "200,\"message\":\"OK\", \"service\": \"Presence\", " "\"payload\":{\"running\"}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_state_get(pbp, "ch", NULL, NULL), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(6)); attest(pubnub_get(pbp), streqs("{\"status\": 200,\"message\":\"OK\", \"service\": \"Presence\", \"payload\":{\"running\"}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* with 'auth' set in context and 'uuid' from parameter to the function */ pubnub_set_auth(pbp, "auth-key"); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/subY/channel/ch/uuid/" "brza_fotografija?pnsdk=unit-test-0.1&auth=auth-" "key"); incoming("HTTP/1.1 200\r\nContent-Length: " "72\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{key:value}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_state_get(pbp, "ch", NULL, "brza_fotografija"), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\",\"payload\":{key:value}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, state_get_channelgroup) { pubnub_init(pbp, "key", "subY"); /* state_get to 'channel group(s)' with 'auth' set in context and 'uuid' * from parameter to the function */ pubnub_set_auth(pbp, "mouth"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/subY/channel/,/uuid/" "fireworks?pnsdk=unit-test-0.1&channel-group=[gr1," "gr2]&auth=mouth"); incoming("HTTP/1.1 200\r\nContent-Length: " "141\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{\"channels\":{\"alfa\":{key:value}," "\"bravo\":{},\"mike\":{},\"charlie\":{},\"foxtrot\":{}}}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_state_get(pbp, NULL, "[gr1,gr2]", "fireworks"), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{\"channels\":{\"alfa\":{key:value},\"bravo\":{}" ",\"mike\":{},\"charlie\":{},\"foxtrot\":{}}}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* set state to 'channel(s)' and 'channel group(s)' with 'auth' set in * context and 'uuid' from parameter to the function */ pubnub_set_auth(pbp, "cat"); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/subY/channel/[ch1,ch2]/uuid/" "leslie-mann?pnsdk=unit-test-0.1&channel-group=[" "gr3,gr4]&auth=cat"); incoming("HTTP/1.1 200\r\nContent-Length: " "153\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{\"channels\":{\"ch1\":{jason_state}," "\"ch2\":{},\"this_one\":{},\"that_one\":{},\"and_another_one\":{}" "}}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_state_get(pbp, "[ch1,ch2]", "[gr3,gr4]", "leslie-mann"), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{\"channels\":{\"ch1\":{jason_state},\"ch2\":{}," "\"this_one\":{},\"that_one\":{},\"and_another_one\":{}}}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* state_get for no 'channel' and no 'channel group'. */ pubnub_set_auth(pbp, NULL); // with or without this line attest(pubnub_state_get(pbp, NULL, NULL, "leslie"), equals(PNR_INVALID_CHANNEL)); } Ensure(single_context_pubnub, state_get_in_progress_interrupted_and_accomplished) { pubnub_init(pbp, "publ-key", "sub-key"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/sub-key/channel/ch/uuid/" "dragon?pnsdk=unit-test-0.1"); /* incoming first message */ incoming("HTTP/1.1 200\r\n", NULL); /* incoming empty string simulates conditions for PNR_IN_PROGRESS */ incoming("", NULL); attest(pubnub_state_get(pbp, "ch", NULL, "dragon"), equals(PNR_STARTED)); attest(pubnub_state_get(pbp, "night_channel", NULL, "knight"), equals(PNR_IN_PROGRESS)); /* incoming next message */ incoming("Content-Length: 82\r\n\r\n{", NULL); /* incoming the last message */ incoming("\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{free_state_of_jones}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); /* rolling rock */ attest(pbnc_fsm(pbp), equals(0)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\",\"payload\":{free_state_of_jones}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, state_get_bad_response) { pubnub_init(pbp, "publkey", "Xsub"); pubnub_set_uuid(pbp, "annoying"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/Xsub/channel/ch/uuid/" "annoying?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 18\r\n\r\n[incorrect answer]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_state_get(pbp, "ch", NULL, NULL), equals(PNR_FORMAT_ERROR)); attest(pbp->core.uuid_len, equals(8)); } /* HERE_NOW operation */ Ensure(single_context_pubnub, here_now_channel) { pubnub_init(pbp, "publZ", "subZ"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/subZ/channel/shade?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 98\r\n\r\n{\"status\": " "200,\"message\":\"OK\", \"service\": \"Presence\", " "\"uuids\":[jack,johnnie,chivas],\"occupancy\":3}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_here_now(pbp, "shade", NULL), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\": 200,\"message\":\"OK\", \"service\": \"Presence\", \"uuids\":[jack,johnnie,chivas],\"occupancy\":3}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, here_now_channel_with_auth) { pubnub_init(pbp, "publZ", "subZ"); pubnub_set_auth(pbp, "auth-key"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/subZ/channel/" "channel?pnsdk=unit-test-0.1&auth=auth-key"); incoming("HTTP/1.1 200\r\nContent-Length: " "102\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"uuids\":[daniel's,walker,regal,beam]," "\"occupancy\":4}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_here_now(pbp, "channel", NULL), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"uuids\":[daniel's,walker,regal,beam],\"occupancy\":4}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, here_now_channelgroups) { pubnub_init(pbp, "publZ", "subZ"); /* set_auth */ pubnub_set_auth(pbp, "mouse"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/subZ/channel/" ",?pnsdk=unit-test-0.1&channel-group=[gr2,gr1]&" "auth=mouse"); incoming("HTTP/1.1 200\r\nContent-Length: " "233\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1," "uuid2],\"occupancy\":2},\"ch2\":{\"uuids\":[uuid3],\"occupancy\":" "1},\"ch3\":{etc.},\"ch4\":{},\"ch5\":{}},\"total_channels\":5," "\"total_occupancy\":something}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_here_now(pbp, NULL, "[gr2,gr1]"), equals(PNR_STARTED)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1,uuid2]," "\"occupancy\":2},\"ch2\":{\"uuids\":[uuid3],\"occupancy\":1}" ",\"ch3\":{etc.},\"ch4\":{},\"ch5\":{}},\"total_channels\":5," "\"total_occupancy\":something}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, here_now_channel_and_channelgroups) { pubnub_init(pbp, "publZ", "subZ"); /* here_now on 'channel(s)' and 'channel group(s)' with 'auth' and 'uuid' */ pubnub_set_auth(pbp, "globe"); pubnub_set_uuid(pbp, "12345"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/subZ/channel/" "[ch1,ch2]?pnsdk=unit-test-0.1&channel-group=[gr3," "gr4]&uuid=12345&auth=globe"); incoming("HTTP/1.1 200\r\nContent-Length: " "290\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1," "uuid2,uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}," "\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{etc.}},\"total_" "channels\":5,\"total_occupancy\":8}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_here_now(pbp, "[ch1,ch2]", "[gr3,gr4]"), equals(PNR_STARTED)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pbp->core.uuid_len, equals(5)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1,uuid2," "uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}" ",\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{etc.}}," "\"total_channels\":5,\"total_occupancy\":8}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* Ensure(single_context_pubnub, here_now_no_channel_and_no_channelgroups) { pubnub_init(pbp, "publZ", "subZ"); attest(pubnub_here_now(pbp, NULL, NULL), equals(PNR_INVALID_CHANNEL)); } */ /* processing of chunked response is common for all operations */ Ensure(single_context_pubnub, here_now_channel_and_channelgroups_chunked) { pubnub_init(pbp, "publZ", "subZ"); /* here_now on 'channel(s)' and 'channel group(s)' with 'auth' and 'uuid' */ pubnub_set_auth(pbp, "globe"); pubnub_set_uuid(pbp, "12345"); expect_have_dns_for_pubnub_origin(); /* Don't forget that chunk lengths should be in hexadecimal representation */ expect_outgoing_with_url("/v2/presence/sub-key/subZ/channel/" "[ch1,ch2]?pnsdk=unit-test-0.1&channel-group=[gr3," "gr4]&uuid=12345&auth=globe"); incoming("HTTP/1.1 200\r\nTransfer-Encoding: chunked\r\n\r\n " "118\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1," "uuid2,uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}," "\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{etc.}},\"total_" "channels\":5,\"total_occu\r\na\r\npancy\":8}}\r\n0\r\n", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_here_now(pbp, "[ch1,ch2]", "[gr3,gr4]"), equals(PNR_STARTED)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pbp->core.uuid_len, equals(5)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1,uuid2," "uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}" ",\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{etc.}}," "\"total_channels\":5,\"total_occupancy\":8}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, here_now_in_progress_interrupted_and_accomplished) { pubnub_init(pbp, "publ-one", "sub-one"); /* here_now on 'channel(s)' and 'channel group(s)' with 'auth' and 'uuid' */ pubnub_set_auth(pbp, "lion"); pubnub_set_uuid(pbp, "cub"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/sub-one/channel/" "[ch5,ch7]?pnsdk=unit-test-0.1&channel-group=[gr1," "gr2]&uuid=cub&auth=lion"); incoming("HTTP/1.1 200\r\nTransfer-Encoding: " "chunked\r\n\r\n122\r\n{\"status\":200,\"mes", NULL); attest(pubnub_here_now(pbp, "[ch5,ch7]", "[gr1,gr2]"), equals(PNR_STARTED)); attest(pubnub_here_now(pbp, "ch", NULL), equals(PNR_IN_PROGRESS)); attest(pbp->core.uuid_len, equals(3)); /* finish chunked */ incoming("sage\":\"OK\",\"service\":\"Presence\",\"payload\":{channels:{" "\"ch1\":{\"uuids\":[uuid1,uuid2,uuid3],\"occupancy\":3},\"ch2\":{" "\"uuids\":[uuid3,uuid4],\"occupancy\":2},\"ch3\":{\"uuids\":[" "uuid7],\"occupancy\":1},\"ch4\":{\"uuids\":[],\"occupancy\":0}," "\"ch5\":{etc.}},\"total_channels\":5,\"total_occupancy\":8}}" "\r\n0\r\n", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1,uuid2," "uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}" ",\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{etc.}}," "\"total_channels\":5,\"total_occupancy\":8}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* GLOBAL_HERE_NOW operation */ Ensure(single_context_pubnub, global_here_now) { pubnub_init(pbp, "publ-white", "sub-white"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/sub-white?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "334\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1," "uuid2,uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}," "\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{\"uuids\":[prle, " "tihi, mrki, paja], " "\"occupancy\":4}},\"total_channels\":5,\"total_occupancy\":12}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_global_here_now(pbp), equals(PNR_STARTED)); attest(pubnub_global_here_now(pbp), equals(PNR_IN_PROGRESS)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1,uuid2," "uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}" ",\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{\"uuids\":[" "prle, tihi, mrki, paja], " "\"occupancy\":4}},\"total_channels\":5,\"total_occupancy\":" "12}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, global_here_now_chunked) { pubnub_init(pbp, "publ-beo", "sub-beo"); /* With uuid & auth */ pubnub_set_auth(pbp, "beograd"); pubnub_set_uuid(pbp, "pobednik"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/" "sub-beo?pnsdk=unit-test-0.1&uuid=pobednik&auth=beograd"); /* Chunk lengths are in hexadecimal representation */ incoming("HTTP/1.1 200\r\nTransfer-Encoding: " "chunked\r\n\r\n1\r\n{\r\n12c\r\n\"status\":200,\"message\":" "\"OK\",\"service\":\"Presence\",\"payload\":{channels:{\"ch1\":{" "\"uuids\":[uuid1,uuid2,uuid3],\"occupancy\":3},\"ch2\":{" "\"uuids\":[uuid3,uuid4],\"occupancy\":2},\"ch3\":{\"uuids\":[" "uuid7],\"occupancy\":1},\"ch4\":{\"uuids\":[],\"occupancy\":0}," "\"ch5\":{\"uuids\":[prle, tihi, mrki, paja], " "\"occupancy\":4}},\"total_c\r\n21\r\nhannels\":5,\"total_" "occupancy\":12}}\r\n0\r\n", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_global_here_now(pbp), equals(PNR_STARTED)); attest(pbp->core.uuid_len, equals(8)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1,uuid2," "uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}" ",\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{\"uuids\":[" "prle, tihi, mrki, paja], " "\"occupancy\":4}},\"total_channels\":5,\"total_occupancy\":" "12}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, global_here_now_in_progress_interrupted_and_acomplished) { pubnub_init(pbp, "publ-my", "sub-my"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/sub-my?pnsdk=unit-test-0.1"); incoming( "HTTP/1.1 200\r\nContent-Length: 334\r\n\r\n{\"status\":200,\"mess", NULL); /* Keeps fsm in progress */ incoming("", NULL); attest(pubnub_global_here_now(pbp), equals(PNR_STARTED)); attest(pubnub_global_here_now(pbp), equals(PNR_IN_PROGRESS)); incoming("age\":\"OK\",\"service\":\"Presence\",\"payload\":{channels:{" "\"ch1\":{\"uuids\":[uuid1,uuid2,uuid3],\"occupancy\":3},\"ch2\":{" "\"uuids\":[uuid3,uuid4],\"occupancy\":2},\"ch3\":{\"uuids\":[" "uuid7],\"occupancy\":1},\"ch4\":{\"uuids\":[],\"occupancy\":0}," "\"ch5\":{\"uuids\":[prle, tihi, mrki, paja], " "\"occupancy\":4}},\"total_channels\":5,\"total_occupancy\":12}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); /* roll the rock */ attest(pbnc_fsm(pbp), equals(0)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1,uuid2," "uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}" ",\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{\"uuids\":[" "prle, tihi, mrki, paja], " "\"occupancy\":4}},\"total_channels\":5,\"total_occupancy\":" "12}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* WHERE_NOW operation */ Ensure(single_context_pubnub, where_now) { pubnub_init(pbp, "publ-where", "sub-where"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/sub-where/uuid/shane(1953)?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "89\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"Payload\":{\"channels\":[tcm,retro,mgm]}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_where_now(pbp, "shane(1953)"), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\",\"Payload\":{\"channels\":[tcm,retro,mgm]}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, where_now_set_uuid) { pubnub_init(pbp, "publ-her", "sub-her"); pubnub_set_uuid(pbp, "50fb7a0b-1688-45b9-9f27-ea83308464d8-ab3817df"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/sub-her/uuid/50fb7a0b-1688-45b9-9f27-ea83308464d8" "-ab3817df?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "100\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"Payload\":{\"channels\":[discovery,nat_geo,nature]" "}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); /* Recognizes the uuid set from the context */ attest(pubnub_where_now(pbp, NULL), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(45)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"Payload\":{\"channels\":[discovery,nat_geo,nature]}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, where_now_set_auth) { pubnub_init(pbp, "publ-sea", "sub-sea"); pubnub_set_uuid(pbp, "fish"); pubnub_set_auth(pbp, "big"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/sub-sea/uuid/whale?pnsdk=unit-test-0.1&auth=big"); incoming("HTTP/1.1 200\r\nContent-Length: " "107\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"Payload\":{\"channels\":[first,second,third," "fourth,fifth]}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); /* Chooses the uuid from the call not the one set in context */ attest(pubnub_where_now(pbp, "whale"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(4)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"Payload\":{\"channels\":[first,second,third,fourth,fifth]}" "}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, where_now_in_progress_interrupted_and_accomplished) { pubnub_init(pbp, "publ-good", "sub-good"); pubnub_set_uuid(pbp, "man_with_no_name"); pubnub_set_auth(pbp, "west"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v2/presence/sub-key/sub-good/uuid/bad?pnsdk=unit-test-0.1&auth=west"); incoming("HTTP/1.1 200\r\nContent-Length: " "140\r\n\r\n{\"status\":200,\"message\":\"OK\",\"ser", NULL); /* server won't close connection after sending this much */ incoming("", NULL); attest(pubnub_where_now(pbp, "bad"), equals(PNR_STARTED)); attest(pubnub_where_now(pbp, "ugly"), equals(PNR_IN_PROGRESS)); attest(pbp->core.uuid_len, equals(16)); /* client reciving rest of the message */ incoming("vice\":\"Presence\",\"Payload\":{\"channels\":[western,here," "there,everywhere,fifth_channel,small_town,boot_hill]}}", NULL); /* Push until finished */ attest(pbnc_fsm(pbp), equals(0)); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"Payload\":{\"channels\":[western,here,there,everywhere," "fifth_channel,small_town,boot_hill]}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* HEARTBEAT operation */ Ensure(single_context_pubnub, heartbeat_channel) { pubnub_init(pbp, "publ-beat", "sub-beat"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/sub-beat/channel/panama/" "heartbeat?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "50\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\"}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_heartbeat(pbp, "panama", NULL), equals(PNR_OK)); attest( pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, heartbeat_channelgroups) { pubnub_init(pbp, "publ-beat", "sub-beat"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/sub-beat/channel/,/" "heartbeat?pnsdk=unit-test-0.1&channel-group=[" "deep,shallow]"); incoming("HTTP/1.1 200\r\nContent-Length: " "50\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\"}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_heartbeat(pbp, NULL, "[deep,shallow]"), equals(PNR_OK)); attest( pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, heartbeat_channel_and_channelgroups) { pubnub_init(pbp, "publ-ocean", "sub-ocean"); pubnub_set_auth(pbp, "sailing"); pubnub_set_uuid(pbp, "capetan"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/sub-ocean/channel/" "young_and_salty/" "heartbeat?pnsdk=unit-test-0.1&channel-group=[" "deep,shallow]&uuid=capetan&auth=sailing"); incoming("HTTP/1.1 200\r\nContent-Length: " "50\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\"}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_heartbeat(pbp, "young_and_salty", "[deep,shallow]"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(7)); attest( pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, heartbeat_no_channel_and_no_channelgroups) { pubnub_init(pbp, "publ-", "sub-"); attest(pubnub_heartbeat(pbp, NULL, NULL), equals(PNR_INVALID_CHANNEL)); } Ensure(single_context_pubnub, heartbeat_channel_and_channelgroups_interrupted_and_accomplished) { pubnub_init(pbp, "publ-game", "sub-game"); pubnub_set_auth(pbp, "white"); pubnub_set_uuid(pbp, "player"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/sub-game/channel/moves/" "heartbeat?pnsdk=unit-test-0.1&channel-group=[" "fast,slow]&uuid=player&auth=white"); incoming("HTTP/1.1 200\r\nContent-Length:", NULL); incoming("", NULL); attest(pubnub_heartbeat(pbp, "moves", "[fast,slow]"), equals(PNR_STARTED)); attest(pubnub_heartbeat(pbp, "punches", "[fast,slow]"), equals(PNR_IN_PROGRESS)); attest(pbp->core.uuid_len, equals(6)); incoming(" 50\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\"}", NULL); /* Push until finished */ attest(pbnc_fsm(pbp), equals(0)); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest( pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* ADD_CHANNEL_TO_GROUP operation */ Ensure(single_context_pubnub, add_channel_to_group) { pubnub_init(pbp, "publ-kc", "sub-kc"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v1/channel-registration/sub-key/sub-kc/" "channel-group/" "ch_group?pnsdk=unit-test-0.1&add=ch_one"); incoming("HTTP/1.1 200\r\nContent-Length: " "72\r\n\r\n{\"service\":\"channel-registry\",\"status\":200," "\"error\":false,\"message\":\"OK\"}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_add_channel_to_group(pbp, "ch_one", "ch_group"), equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("{\"service\":\"channel-registry\",\"status\":200,\"error\":false,\"message\":\"OK\"}")); attest(pubnub_get_channel(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, add_channel_to_group_interrupted_and_accomplished) { pubnub_init(pbp, "publ-kc", "sub-kc"); /* With auth */ pubnub_set_auth(pbp, "rice_chocolate"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v1/channel-registration/sub-key/sub-kc/channel-group/" "ch_group?pnsdk=unit-test-0.1&add=ch_one&auth=rice_chocolate"); incoming("HTTP/1.1 200\r\nContent-Length: 72\r\n\r\n{\"service\"", NULL); /* won't close connection */ incoming("", NULL); attest(pubnub_add_channel_to_group(pbp, "ch_one", "ch_group"), equals(PNR_STARTED)); attest(pubnub_add_channel_to_group(pbp, "ch", "ch_group"), equals(PNR_IN_PROGRESS)); incoming(":\"channel-registry\",\"status\":200,\"error\":false,\"message\":" "\"OK\"}", NULL); /* keep 'turning' it until finished */ attest(pbnc_fsm(pbp), equals(0)); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("{\"service\":\"channel-registry\",\"status\":200,\"error\":false,\"message\":\"OK\"}")); attest(pubnub_get_channel(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* REMOVE_CHANNEL_FROM_GROUP operation */ Ensure(single_context_pubnub, remove_channel_from_group) { pubnub_init(pbp, "publ-kum_Ruzvelt", "sub-kum_Ruzvelt"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v1/channel-registration/sub-key/sub-kum_Ruzvelt/" "channel-group/" "ch_group?pnsdk=unit-test-0.1&remove=ch_one"); incoming("HTTP/1.1 200\r\nContent-Length: " "72\r\n\r\n{\"service\":\"channel-registry\",\"status\":200," "\"error\":false,\"message\":\"OK\"}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_remove_channel_from_group(pbp, "ch_one", "ch_group"), equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("{\"service\":\"channel-registry\",\"status\":200,\"error\":false,\"message\":\"OK\"}")); attest(pubnub_get_channel(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, remove_channel_from_group_interrupted_and_accomplished) { pubnub_init(pbp, "publ-Teheran", "sub-Teheran"); /* With auth */ pubnub_set_auth(pbp, "dates"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/v1/channel-registration/sub-key/sub-Teheran/channel-group/" "ch_group?pnsdk=unit-test-0.1&remove=ch_one&auth=dates"); incoming("HTTP/1.1 200\r\nContent-", NULL); /* won't close connection */ incoming("", NULL); attest(pubnub_remove_channel_from_group(pbp, "ch_one", "ch_group"), equals(PNR_STARTED)); attest(pubnub_remove_channel_from_group(pbp, "ch", "ch_group"), equals(PNR_IN_PROGRESS)); incoming("Length: " "72\r\n\r\n{\"service\":\"channel-registry\",\"status\":200," "\"error\":false,\"message\":\"OK\"}", NULL); /* keep 'turning' it until finished */ attest(pbnc_fsm(pbp), equals(0)); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("{\"service\":\"channel-registry\",\"status\":200,\"error\":false,\"message\":\"OK\"}")); attest(pubnub_get_channel(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* REMOVE_CHANNEL_GROUP operation */ Ensure(single_context_pubnub, remove_channel_group) { pubnub_init(pbp, "publ-bell", "sub-bell"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v1/channel-registration/sub-key/sub-bell/" "channel-group/group_name/" "remove?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 82\r\n\r\n{\"service\": " "\"channel-registry\" , \"status\" : 200 ,\"error\" " ":false,\"message\": \"OK\"}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_remove_channel_group(pbp, "group_name"), equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("{\"service\": \"channel-registry\" , \"status\" : 200 ,\"error\" :false,\"message\": \"OK\"}")); attest(pubnub_get_channel(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, remove_channel_group_interrupted_and_accomplished) { pubnub_init(pbp, "publ-blue", "sub-blue"); /* With auth */ pubnub_set_auth(pbp, "sky"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v1/channel-registration/sub-key/sub-blue/" "channel-group/group/" "remove?pnsdk=unit-test-0.1&auth=sky"); incoming("HTTP/1.1 200\r\nContent-Len", NULL); /* won't close connection */ incoming("", NULL); attest(pubnub_remove_channel_group(pbp, "group"), equals(PNR_STARTED)); attest(pubnub_remove_channel_group(pbp, "another_group"), equals(PNR_IN_PROGRESS)); incoming("gth: 79\r\n\r\n{ \"service\":\"channel-registry\" ,\"status\" : " "200,\"error\" : false ,\"message\":\"OK\"}", NULL); /* keep 'turning' it until finished */ attest(pbnc_fsm(pbp), equals(0)); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("{ \"service\":\"channel-registry\" ,\"status\" : 200,\"error\" : false ,\"message\":\"OK\"}")); attest(pubnub_get_channel(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* LIST_CHANNEL_GROUP operation */ Ensure(single_context_pubnub, list_channel_group) { pubnub_init(pbp, "publ-science", "sub-science"); /* With auth */ pubnub_set_auth(pbp, "research"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v1/channel-registration/sub-key/sub-science/" "channel-group/" "info?pnsdk=unit-test-0.1&auth=research"); incoming("HTTP/1.1 200\r\nContent-Length: 154\r\n\r\n{\"service\": " "\"channel-registry\" , \"status\": 200 ,\"error\" " ":false,\"payload\":{\"group\":\"info\",\"channels\":{\"weather\"," " \"polution\",\"resources\",\"consumtion\",...}}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_list_channel_group(pbp, "info"), equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("{\"service\": \"channel-registry\" , \"status\": 200 " ",\"error\" " ":false,\"payload\":{\"group\":\"info\",\"channels\":{" "\"weather\", " "\"polution\",\"resources\",\"consumtion\",...}}}")); attest(pubnub_get_channel(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, list_channel_group_interrupted_and_accomplished) { pubnub_init(pbp, "publ-air-traffic", "sub-air-traffic"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v1/channel-registration/sub-key/sub-air-traffic/" "channel-group/airborne?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Len", NULL); /* won't close connection */ incoming("", NULL); attest(pubnub_list_channel_group(pbp, "airborne"), equals(PNR_STARTED)); attest(pubnub_list_channel_group(pbp, "landed"), equals(PNR_IN_PROGRESS)); incoming("gth: 128\r\n\r\n{ \"service\":\"channel-registry\" ,\"status\" : " "200,\"error\" : false , " "\"payload\":{\"group\":\"airborne\",\"channels\":{\"pw45\", " "\"xg37\",...}}}", NULL); /* keep 'turning' it until finished */ attest(pbnc_fsm(pbp), equals(0)); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("{ \"service\":\"channel-registry\" ,\"status\" : " "200,\"error\" : false , " "\"payload\":{\"group\":\"airborne\",\"channels\":{\"pw45\", " "\"xg37\",...}}}")); attest(pubnub_get_channel(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* SUBSCRIBE operation */ Ensure(single_context_pubnub, subscribe) { pubnub_init(pbp, "publ-magazin", "sub-magazin"); attest(pubnub_uuid_get(pbp), streqs(NULL)); attest(pubnub_auth_get(pbp), streqs(NULL)); attest(pubnub_last_time_token(pbp), streqs("0")); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/subscribe/sub-magazin/health/0/0?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"1516014978925123457\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "health", NULL), equals(PNR_OK)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_last_time_token(pbp), streqs("1516014978925123457")); /* Not publish operation */ attest(pubnub_last_publish_result(pbp), streqs("")); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-magazin/health/0/" "1516014978925123457?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "56\r\n\r\n[[pomegranate_juice,papaya,mango]," "\"1516714978925123457\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "health", NULL), equals(PNR_OK)); attest(pubnub_last_time_token(pbp), streqs("1516714978925123457")); attest(pubnub_get(pbp), streqs("pomegranate_juice")); attest(pubnub_get(pbp), streqs("papaya")); attest(pubnub_get(pbp), streqs("mango")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, subscribe_channel_groups) { pubnub_init(pbp, "publ-bulletin", "sub-bulletin"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-bulletin/,/0/" "0?pnsdk=unit-test-0.1&channel-group=updates"); incoming( "HTTP/1.1 200\r\nContent-Length: 25\r\n\r\n[[],\"251614978925123457\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, NULL, "updates"), equals(PNR_OK)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_last_time_token(pbp), streqs("251614978925123457")); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-bulletin/,/0/" "251614978925123457?pnsdk=unit-test-0.1&channel-" "group=updates"); incoming("HTTP/1.1 200\r\nContent-Length: " "110\r\n\r\n[[skype,web_brouser,text_editor]," "\"251624978925123457\",\"updates,updates,updates\",\"messengers," "brousers,editors\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, NULL, "updates"), equals(PNR_OK)); attest(pubnub_last_time_token(pbp), streqs("251624978925123457")); attest(pubnub_get(pbp), streqs("skype")); attest(pubnub_get_channel(pbp), streqs("messengers")); attest(pubnub_get(pbp), streqs("web_brouser")); attest(pubnub_get_channel(pbp), streqs("brousers")); attest(pubnub_get(pbp), streqs("text_editor")); attest(pubnub_get_channel(pbp), streqs("editors")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-bulletin/,/0/" "251624978925123457?pnsdk=unit-test-0.1&channel-" "group=updates"); incoming("HTTP/1.1 200\r\nContent-Length: " "51\r\n\r\n[[virtualbox],\"251624978925123457\",\"updates\"," "\"VMs\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, NULL, "updates"), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("virtualbox")); attest(pubnub_get_channel(pbp), streqs("VMs")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, subscribe_channels_and_channel_groups) { pubnub_init(pbp, "publ-key", "sub-Key"); pubnub_set_uuid(pbp, "admin"); pubnub_set_auth(pbp, "msgs"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-Key/[ch1,ch2]/0/" "0?pnsdk=unit-test-0.1&channel-group=[chgr2,chgr3," "chgr4]&uuid=admin&auth=msgs"); incoming("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"3516149789251234578\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "[ch1,ch2]", "[chgr2,chgr3,chgr4]"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(5)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-Key/[ch1,ch2]/0/" "3516149789251234578?pnsdk=unit-test-0.1&channel-" "group=[chgr2,chgr3,chgr4]&uuid=admin&auth=msgs"); incoming("HTTP/1.1 200\r\nContent-Length: " "150\r\n\r\n[[msg1,msg2,{\"text\":\"Hello " "World!\"},msg4,msg5,{\"key\":\"val\\ue\"}]," "\"352624978925123458\",\"chgr4,chgr2,chgr3,chgr4,chgr7,chgr4\"," "\"ch5,ch8,ch6,ch17,ch1,ch2\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "[ch1,ch2]", "[chgr2,chgr3,chgr4]"), equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("ch5")); attest(pubnub_get_channel(pbp), streqs("ch8")); attest(pubnub_get_channel(pbp), streqs("ch6")); attest(pubnub_get_channel(pbp), streqs("ch17")); attest(pubnub_get_channel(pbp), streqs("ch1")); attest(pubnub_get_channel(pbp), streqs("ch2")); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), streqs("msg1")); attest(pubnub_get(pbp), streqs("msg2")); attest(pubnub_get(pbp), streqs("{\"text\":\"Hello World!\"}")); attest(pubnub_get(pbp), streqs("msg4")); attest(pubnub_get(pbp), streqs("msg5")); attest(pubnub_get(pbp), streqs("{\"key\":\"val\\ue\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-Key/ch17/0/" "352624978925123458?pnsdk=unit-test-0.1&uuid=" "admin&auth=msgs"); incoming("HTTP/1.1 200\r\nContent-Length: " "47\r\n\r\n[[message],\"352624979925123457\",\"chgr4\",\"ch17\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "ch17", NULL), equals(PNR_OK)); attest(pubnub_subscribe(pbp, NULL, "chgr2"), equals(PNR_RX_BUFF_NOT_EMPTY)); attest(pubnub_get(pbp), streqs("message")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs("ch17")); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_uuid_get(pbp), streqs("admin")); attest(pubnub_auth_get(pbp), streqs("msgs")); } Ensure(single_context_pubnub, subscribe_channel_groups_interrupted_and_accomplished_chunked) { pubnub_init(pbp, "publ-measurements", "sub-measurements"); pubnub_set_uuid(pbp, "technician"); pubnub_set_auth(pbp, "weather-conditions"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-measurements/,/0/" "0?pnsdk=unit-test-0.1&channel-group=[air-" "temperature,humidity,wind-speed-and-direction," "pressure]&uuid=technician&auth=weather-" "conditions"); incoming("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"1516149789251234578\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe( pbp, NULL, "[air-temperature,humidity,wind-speed-and-direction,pressure]"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(10)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-measurements/,/0/" "1516149789251234578?pnsdk=unit-test-0.1&channel-" "group=[air-temperature,humidity,wind-speed-and-" "direction,pressure]&uuid=technician&auth=weather-" "conditions"); incoming("HTTP/1.1 200\r\nTransfer-Encoding: " "chunked\r\n\r\n9d\r\n[[{\"uuid1\":\"-2\"},{\"uuid2\":\"-5\"},{" "\"Kingston\":\"+22\"},{\"Manila\":\"+38\"},{\"bouy76\":\"+5\"},{" "\"Pr. Astrid " "Coast\":\"Unable_to_fetch_temperature\"}]," "\"1516149789251234583\"\r\n97\r\n,\"air-temperature,air-" "temperature,air-temperature,air-temperature,air-temperature,air-" "temperature\",\"ch-atmp,ch-atmp,ch-atmp,ch-atmp,ch-atmp,ch-" "atmp\"]\r\n0\r\n", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe( pbp, NULL, "[air-temperature,humidity,wind-speed-and-direction,pressure]"), equals(PNR_STARTED)); attest(pubnub_subscribe(pbp, "some_channels", "some_channel_goups"), equals(PNR_IN_PROGRESS)); /* 'push' until finished */ attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_subscribe(pbp, NULL, "some_channel_goups"), equals(PNR_RX_BUFF_NOT_EMPTY)); attest(pubnub_get(pbp), streqs("{\"uuid1\":\"-2\"}")); attest(pubnub_get_channel(pbp), streqs("ch-atmp")); attest(pubnub_get(pbp), streqs("{\"uuid2\":\"-5\"}")); attest(pubnub_get(pbp), streqs("{\"Kingston\":\"+22\"}")); attest(pubnub_get(pbp), streqs("{\"Manila\":\"+38\"}")); attest(pubnub_get(pbp), streqs("{\"bouy76\":\"+5\"}")); attest(pubnub_subscribe(pbp, NULL, "wind-speed-and-direction"), equals(PNR_RX_BUFF_NOT_EMPTY)); attest(pubnub_get(pbp), streqs("{\"Pr. Astrid Coast\":\"Unable_to_fetch_temperature\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-measurements/,/0/" "1516149789251234583?pnsdk=unit-test-0.1&channel-" "group=[air-temperature,humidity,wind-speed-and-" "direction,pressure]&uuid=technician&auth=weather-" "conditions"); incoming("HTTP/1.1 200\r\nTransfer-Encoding: " "chunked\r\n\r\n101\r\n[[{\"uuid1\":{\"dir\":w,\"speed\":\"2mph\"," "\"blows\":\"3mph\"}},{\"uuid2\":{\"dir\":nw,\"speed\":\"5mph\"," "\"blows\":\"7mph\"}},{\"Sebu, " "Philippines\":{\"dir\":nne,\"speed\":\"4mph\",\"blows\":\"4mph\"}" "},{\"Sri Jayawardenepura Kotte, Sri " "Lanka\":{\"dir\":ne,\"speed\":\"7mph\",\"blows\":\"7mph\"}}]," "\"151614\r\n93\r\n9789251234597\",\"wind-speed-and-direction," "wind-speed-and-direction,wind-speed-and-direction,wind-speed-and-" "direction\",\"ch-ws1,ch-ws2,ch-ws3,ch-ws1\"]\r\n0\r\n", NULL); attest(pubnub_subscribe( pbp, NULL, "[air-temperature,humidity,wind-speed-and-direction,pressure]"), equals(PNR_STARTED)); attest(pubnub_subscribe(pbp, NULL, "humidity"), equals(PNR_IN_PROGRESS)); /* 'push' until finished */ expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("ch-ws1")); attest( pubnub_get(pbp), streqs( "{\"uuid1\":{\"dir\":w,\"speed\":\"2mph\",\"blows\":\"3mph\"}}")); attest( pubnub_get(pbp), streqs( "{\"uuid2\":{\"dir\":nw,\"speed\":\"5mph\",\"blows\":\"7mph\"}}")); attest(pubnub_get(pbp), streqs("{\"Sebu, Philippines\":{\"dir\":nne,\"speed\":\"4mph\",\"blows\":\"4mph\"}}")); attest(pubnub_get(pbp), streqs("{\"Sri Jayawardenepura Kotte, Sri Lanka\":{\"dir\":ne,\"speed\":\"7mph\",\"blows\":\"7mph\"}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, subscribe_no_channel_and_no_channelgroups) { pubnub_init(pbp, "publ-something", "sub-something"); attest(pubnub_subscribe(pbp, NULL, NULL), equals(PNR_INVALID_CHANNEL)); } Ensure(single_context_pubnub, subscribe_parse_response_format_error) { pubnub_init(pbp, "publ-fe", "sub-fe"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-fe/[ch2]/0/" "0?pnsdk=unit-test-0.1&channel-group=[chgr2," "chgr4]"); incoming("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n{[],\"3516149789251234578\"}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "[ch2]", "[chgr2,chgr4]"), equals(PNR_FORMAT_ERROR)); } Ensure(single_context_pubnub, subscribe_reestablishing_broken_keep_alive_conection) { pubnub_init(pbp, "publ-key", "sub-Key"); pubnub_set_uuid(pbp, "admin"); pubnub_set_auth(pbp, "msgs"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-Key/[ch1,ch2]/0/" "0?pnsdk=unit-test-0.1&channel-group=[chgr2,chgr3," "chgr4]&uuid=admin&auth=msgs"); incoming("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"3516149789251234578\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "[ch1,ch2]", "[chgr2,chgr3,chgr4]"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(5)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* Sending GET request returns failure which means broken connection */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect(pbpal_send_str, when(s, streqs("GET ")), returns(-1)); /* Connection is not closed instantaneously */ expect(pbpal_close, when(pb, equals(pbp)), returns(+1)); expect(pbpal_closed, when(pb, equals(pbp)), returns(true)); expect(pbpal_forget, when(pb, equals(pbp))); /* Renewing DNS resolution and reestablishing connection */ expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-Key/[ch1,ch2]/0/" "3516149789251234578?pnsdk=unit-test-0.1&channel-" "group=[chgr2,chgr3,chgr4]&uuid=admin&auth=msgs"); incoming("HTTP/1.1 200\r\nContent-Length: " "150\r\n\r\n[[msg1,msg2,{\"text\":\"Hello " "World!\"},msg4,msg5,{\"key\":\"val\\ue\"}]," "\"352624978925123458\",\"chgr4,chgr2,chgr3,chgr4,chgr7,chgr4\"," "\"ch5,ch8,ch6,ch17,ch1,ch2\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "[ch1,ch2]", "[chgr2,chgr3,chgr4]"), equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("ch5")); attest(pubnub_get_channel(pbp), streqs("ch8")); attest(pubnub_get_channel(pbp), streqs("ch6")); attest(pubnub_get_channel(pbp), streqs("ch17")); attest(pubnub_get_channel(pbp), streqs("ch1")); attest(pubnub_get_channel(pbp), streqs("ch2")); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), streqs("msg1")); attest(pubnub_get(pbp), streqs("msg2")); attest(pubnub_get(pbp), streqs("{\"text\":\"Hello World!\"}")); attest(pubnub_get(pbp), streqs("msg4")); attest(pubnub_get(pbp), streqs("msg5")); attest(pubnub_get(pbp), streqs("{\"key\":\"val\\ue\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* connection keeps alive this time */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-Key/ch17/0/" "352624978925123458?pnsdk=unit-test-0.1&uuid=" "admin&auth=msgs"); incoming("HTTP/1.1 200\r\nContent-Length: " "47\r\n\r\n[[message],\"352624979925123457\",\"chgr4\",\"ch17\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "ch17", NULL), equals(PNR_OK)); attest(pubnub_subscribe(pbp, NULL, "chgr2"), equals(PNR_RX_BUFF_NOT_EMPTY)); attest(pubnub_get(pbp), streqs("message")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs("ch17")); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, subscribe_not_using_keep_alive_connection) { pubnub_init(pbp, "publ-key", "sub-Key"); /* Won't be using default 'keep-alive' connection */ pubnub_dont_use_http_keep_alive(pbp); /* Shouldn't make any difference having set these parameters */ pubnub_set_keep_alive_param(pbp, 49, 50); pubnub_set_uuid(pbp, "admin"); pubnub_set_auth(pbp, "msgs"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-Key/[ch1,ch2]/0/" "0?pnsdk=unit-test-0.1&channel-group=[chgr2,chgr3," "chgr4]&uuid=admin&auth=msgs"); incoming_and_close("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"3516149789251234578\"]", NULL); attest(pubnub_subscribe(pbp, "[ch1,ch2]", "[chgr2,chgr3,chgr4]"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(5)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, subscribe_not_using_and_than_using_keep_alive_connection) { pubnub_init(pbp, "publ-key", "sub-Key"); /* Won't be using default 'keep-alive' connection */ pubnub_dont_use_http_keep_alive(pbp); pubnub_set_uuid(pbp, "admin"); pubnub_set_auth(pbp, "msgs"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-Key/[ch1,ch2]/0/" "0?pnsdk=unit-test-0.1&channel-group=[chgr2,chgr3," "chgr4]&uuid=admin&auth=msgs"); incoming_and_close("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"3516149789251234578\"]", NULL); attest(pubnub_subscribe(pbp, "[ch1,ch2]", "[chgr2,chgr3,chgr4]"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(5)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* After finishing following transaction switches connection to 'keep_alive' */ pubnub_use_http_keep_alive(pbp); /* Renewing DNS resolution with new request */ expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-Key/[ch1,ch2]/0/" "3516149789251234578?pnsdk=unit-test-0.1&channel-" "group=[chgr2,chgr3,chgr4]&uuid=admin&auth=msgs"); incoming("HTTP/1.1 200\r\nContent-Length: " "150\r\n\r\n[[msg1,msg2,{\"text\":\"Hello " "World!\"},msg4,msg5,{\"key\":\"val\\ue\"}]," "\"352624978925123458\",\"chgr4,chgr2,chgr3,chgr4,chgr7,chgr4\"," "\"ch5,ch8,ch6,ch17,ch1,ch2\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "[ch1,ch2]", "[chgr2,chgr3,chgr4]"), equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("ch5")); attest(pubnub_get_channel(pbp), streqs("ch8")); attest(pubnub_get_channel(pbp), streqs("ch6")); attest(pubnub_get_channel(pbp), streqs("ch17")); attest(pubnub_get_channel(pbp), streqs("ch1")); attest(pubnub_get_channel(pbp), streqs("ch2")); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), streqs("msg1")); attest(pubnub_get(pbp), streqs("msg2")); attest(pubnub_get(pbp), streqs("{\"text\":\"Hello World!\"}")); attest(pubnub_get(pbp), streqs("msg4")); attest(pubnub_get(pbp), streqs("msg5")); attest(pubnub_get(pbp), streqs("{\"key\":\"val\\ue\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* connection keeps alive */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-Key/ch17/0/" "352624978925123458?pnsdk=unit-test-0.1&uuid=" "admin&auth=msgs"); /* simulates 'callback' condition of PNR_IN_PROGRESS. * (expl: recv_msg would return 0 otherwise as if the connection * closes from servers side.) */ incoming("", NULL); expect(pbpal_close, when(pb, equals(pbp)), returns(0)); expect(pbpal_forget, when(pb, equals(pbp))); expect(pbntf_requeue_for_processing, when(pb, equals(pbp)), returns(0)); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-Key/ch17/0/" "352624978925123458?pnsdk=unit-test-0.1&uuid=" "admin&auth=msgs"); incoming("HTTP/1.1 200\r\nContent-Length: " "47\r\n\r\n[[message],\"352624979925123457\",\"chgr4\",\"ch17\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); /* Transaction timer expires while expecting the answer because the connection was broken at some place, at some point, from some reason and, in meantime, reestablished again on that stretch, while our connection with origin server no longer exists... */ attest(pubnub_subscribe(pbp, "ch17", NULL), equals(PNR_STARTED)); pbnc_stop(pbp, PNR_TIMEOUT); pbnc_fsm(pbp); attest(pubnub_subscribe(pbp, NULL, "chgr2"), equals(PNR_RX_BUFF_NOT_EMPTY)); attest(pubnub_get(pbp), streqs("message")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs("ch17")); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* KEEP_ALIVE_ADVANCED */ Ensure(single_context_pubnub, keeps_connection_alive_for_certain_number_of_operations) { pubnub_init(pbp, "publ-persian", "sub-persian"); attest(pubnub_uuid_get(pbp), streqs(NULL)); attest(pubnub_auth_get(pbp), streqs(NULL)); attest(pubnub_last_time_token(pbp), streqs("0")); /* Keep connection alive for up to 1 second or up to 3 operations */ pubnub_set_keep_alive_param(pbp, 0, 3); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/subscribe/sub-persian/civilization/0/0?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"1516014978925123458\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "civilization", NULL), equals(PNR_OK)); /* Awaits given number of seconds. If changed to greater value test fails. */ wait_time_in_seconds(0); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_last_time_token(pbp), streqs("1516014978925123458")); /* Not publish operation */ attest(pubnub_last_publish_result(pbp), streqs("")); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-persian/civilization/0/" "1516014978925123458?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "46\r\n\r\n[[\"tigris\",\"euphrates\"],\"1516014978925123459\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "civilization", NULL), equals(PNR_OK)); /* Same outcome for any delay between last two operations, if one before the last was accomplished within given time interval */ wait_time_in_seconds(0); attest(pubnub_last_time_token(pbp), streqs("1516014978925123459")); attest(pubnub_get(pbp), streqs("\"tigris\"")); attest(pubnub_get(pbp), streqs("\"euphrates\"")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/publish/publ-persian/sub-persian/0/civilization/" "0/%22hanging_gardens%22?pnsdk=unit-test-0.1"); incoming_and_close("HTTP/1.1 200\r\nContent-Length: " "32\r\n\r\n[1,\"Sent\",\"1516014978925123459\"]", NULL); attest(pubnub_last_publish_result(pbp), streqs("")); attest(pubnub_publish(pbp, "civilization", "\"hanging_gardens\""), equals(PNR_OK)); attest(pubnub_last_publish_result(pbp), streqs("\"Sent\"")); attest(pubnub_last_http_code(pbp), equals(200)); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-persian/civilization/0/" "1516014978925123459?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: 61\r\n\r\n[[\"hanging_gardens\", " "\"arabian_nights\"],\"1516714978925123460\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "civilization", NULL), equals(PNR_OK)); attest(pubnub_last_time_token(pbp), streqs("1516714978925123460")); attest(pubnub_get(pbp), streqs("\"hanging_gardens\"")); attest(pubnub_get(pbp), streqs(" \"arabian_nights\"")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, doesnt_keep_connection_alive_confinement_number_of_operations) { pubnub_init(pbp, "publ-some", "sub-some"); attest(pubnub_uuid_get(pbp), streqs(NULL)); attest(pubnub_auth_get(pbp), streqs(NULL)); attest(pubnub_last_time_token(pbp), streqs("0")); /* Keep connection alive for up to 3 seconds or up to 0 operations */ pubnub_set_keep_alive_param(pbp, 2, 0); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/subscribe/sub-some/light/0/0?pnsdk=unit-test-0.1"); incoming_and_close("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"1516014978925123458\"]", NULL); attest(pubnub_subscribe(pbp, "light", NULL), equals(PNR_OK)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_last_time_token(pbp), streqs("1516014978925123458")); /* Not publish operation */ attest(pubnub_last_publish_result(pbp), streqs("")); /* Keep connection alive for up to 3 seconds or up to 1 operation */ pubnub_set_keep_alive_param(pbp, 2, 1); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/subscribe/sub-some/light/0/1516014978925123458?pnsdk=unit-test-0.1"); incoming_and_close("HTTP/1.1 200\r\nContent-Length: " "35\r\n\r\n[[warm,cold],\"1516014978925123459\"]", NULL); attest(pubnub_subscribe(pbp, "light", NULL), equals(PNR_OK)); attest(pubnub_last_time_token(pbp), streqs("1516014978925123459")); attest(pubnub_get(pbp), streqs("warm")); attest(pubnub_get(pbp), streqs("cold")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, keep_alive_connection_closes_time_runs_out) { pubnub_init(pbp, "publ-some", "sub-some"); attest(pubnub_uuid_get(pbp), streqs(NULL)); attest(pubnub_auth_get(pbp), streqs(NULL)); attest(pubnub_last_time_token(pbp), streqs("0")); /* Keep connection alive for up to 1 second or up to 3 operations */ pubnub_set_keep_alive_param(pbp, 0, 3); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/subscribe/sub-some/discharge/0/0?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"1516014978925123458\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "discharge", NULL), equals(PNR_OK)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); attest(pubnub_last_time_token(pbp), streqs("1516014978925123458")); /* Not publish operation */ attest(pubnub_last_publish_result(pbp), streqs("")); /* Time runs out. Connection closes after following operation */ wait_time_in_seconds(1); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-some/discharge/0/" "1516014978925123458?pnsdk=unit-test-0.1"); incoming_and_close("HTTP/1.1 200\r\nContent-Length: " "35\r\n\r\n[[lightning],\"1516014978925123459\"]", NULL); attest(pubnub_subscribe(pbp, "discharge", NULL), equals(PNR_OK)); attest(pubnub_last_time_token(pbp), streqs("1516014978925123459")); attest(pubnub_get(pbp), streqs("lightning")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, subscribe_not_using_keep_alive_and_than_using_it_again_with_parameters) { pubnub_init(pbp, "publ-key", "sub-Key"); /* Won't be using default 'keep-alive' connection */ pubnub_dont_use_http_keep_alive(pbp); /* Don't influence and shouldn't be influenced by operations while * 'keep_alive' is off */ pubnub_set_keep_alive_param(pbp, 5, 2); pubnub_set_uuid(pbp, "admin"); pubnub_set_auth(pbp, "msgs"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-Key/[ch1,ch2]/0/" "0?pnsdk=unit-test-0.1&channel-group=[chgr2,chgr3," "chgr4]&uuid=admin&auth=msgs"); incoming_and_close("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"3516149789251234578\"]", NULL); attest(pubnub_subscribe(pbp, "[ch1,ch2]", "[chgr2,chgr3,chgr4]"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(5)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* Turns back on 'keep-alive' */ pubnub_use_http_keep_alive(pbp); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-Key/ch1/0/" "3516149789251234578?pnsdk=unit-test-0.1&uuid=" "admin&auth=msgs"); incoming("HTTP/1.1 200\r\nContent-Length: " "30\r\n\r\n[[msg1],\"3516149789251234579\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "ch1", NULL), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("msg1")); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-Key/ch1/0/" "3516149789251234579?pnsdk=unit-test-0.1&uuid=" "admin&auth=msgs"); incoming_and_close("HTTP/1.1 200\r\nContent-Length: " "30\r\n\r\n[[msg2],\"3516149789251234580\"]", NULL); attest(pubnub_subscribe(pbp, "ch1", NULL), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("msg2")); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } /* DATA COMPRESSION */ Ensure(single_context_pubnub, subscribe_gzip_response) { uint8_t gzip_chunk0[] = { 0x1f, 0x8b, 0x08, 0x00, 0xae, 0x8b, 0xe3, 0x5a, 0x02, 0x03, 0xad, 0x8d, 0x3b, 0x0b, 0xc2, 0x30, 0x14, 0x85, 0xff, 0x8a, 0xdc, 0xd5, 0x54, 0x48, 0xda, 0xf4, 0xe1, 0x26, 0x8e, 0x22, 0xb8, 0x38, 0x95, 0x52, 0x6e, 0xdb, 0x68, 0x03, 0x6d, 0x52, 0xd2 }; struct uint8_block chunk_block0 = { 41, gzip_chunk0 }; uint8_t gzip_chunk1[] = { 0x9b, 0x41, 0xa4, 0xff, 0xdd, 0x3e, 0x16, 0x47, 0x07, 0xa7, 0xcb, 0xf7, 0x9d, 0x73, 0xb8, 0x79, 0xfe, 0x06, 0xef, 0x75, 0xc3, 0xe1, 0x08, 0x81, 0x80, 0x89, 0x6d, 0x28, 0x16, 0x94, 0x2b, 0x5e, 0xb4, 0x79, 0x8e, 0x64, 0xcd, 0x6c, 0xf6, 0x62, 0x6b, 0x5c, 0xd1, 0xe8, 0x0e, 0x17, 0x11, 0xa6, 0xab, 0xa8, 0xac, 0x7f, 0x25, 0xf1, 0x22, 0xb6, 0xcd, 0xcd, 0x1d, 0x76, 0xa7, 0x91, 0x9c, 0x6e, 0x76, 0x67, 0x8b, 0x23, 0xcd, 0xc9, 0xdd, 0x60, 0xd5, 0xa9, 0x92, 0x6c, 0xf9, 0x50, 0x54, 0xb7, 0x25, 0xa9, 0x7e, 0x50, 0x0e, 0xc9, 0x3b, 0x05, 0x53, 0xc1, 0x80, 0x4b, 0x1e, 0xf3, 0x28, 0x4b, 0xd2, 0x4c, 0x48, 0x2e, 0xc2, 0x48, 0xa6, 0x21, 0x30, 0x40, 0xed, 0x82, 0xaf, 0x26, 0xfb, 0x33, 0xcf, 0x1f, 0xea, 0x36, 0x40, 0xea, 0x07, 0xf6, 0xe3, 0x85, 0xe2, 0x03, 0x8a, 0x9f, 0x27, 0xee, 0x32, 0x01, 0x00, 0x00 }; struct uint8_block chunk_block1 = { 132, gzip_chunk1 }; uint8_t gzip_body2[] = { 0x1f, 0x8b, 0x08, 0x00, 0xa7, 0x37, 0xe3, 0x5a, 0x02, 0x03, 0xad, 0xce, 0xcb, 0x0a, 0x83, 0x30, 0x10, 0x05, 0xd0, 0x5f, 0x91, 0x59, 0xc7, 0x45, 0xa2, 0x69, 0xaa, 0x9f, 0xd0, 0x76, 0x51, 0xe8, 0x52, 0x5c, 0x44, 0x33, 0x60, 0x68, 0x1b, 0x83, 0x0f, 0x42, 0x11, 0xff, 0xbd, 0x51, 0xc1, 0x07, 0x74, 0xd9, 0xd5, 0xcd, 0x30, 0x39, 0x37, 0xc9, 0xb2, 0x01, 0xfa, 0x5e, 0x2b, 0x0a, 0xe9, 0x00, 0x4a, 0x37, 0x90, 0x3a, 0x02, 0xad, 0x45, 0x54, 0x90, 0x02, 0x7b, 0xdb, 0x0a, 0x08, 0x14, 0xaf, 0xda, 0xb5, 0x7e, 0x8c, 0xa6, 0x71, 0x1c, 0xc9, 0x22, 0xd8, 0x2a, 0xcc, 0x8e, 0xf0, 0x23, 0x11, 0x2b, 0x79, 0x60, 0xd1, 0x93, 0xe0, 0x5e, 0xe9, 0x97, 0xb6, 0x56, 0x1b, 0x6c, 0x37, 0x6e, 0x70, 0xf3, 0xf1, 0xd1, 0xc7, 0x9b, 0x6f, 0x74, 0x70, 0x91, 0x1f, 0xe9, 0x64, 0xa3, 0xd0, 0xa0, 0xed, 0x1b, 0x19, 0x5c, 0xeb, 0xae, 0x43, 0x12, 0x4c, 0xab, 0x9b, 0x34, 0x4f, 0xb9, 0x55, 0xee, 0x1a, 0xc5, 0xcf, 0x1f, 0xe5, 0x04, 0x28, 0xa7, 0x27, 0x1a, 0x27, 0xe2, 0x9c, 0x30, 0x4e, 0x59, 0x14, 0xf3, 0x44, 0xf8, 0x7b, 0x4e, 0x1b, 0x15, 0xce, 0x36, 0x94, 0xfe, 0xe4, 0xeb, 0xb0, 0xec, 0x74, 0x6d, 0xc8, 0xff, 0x16, 0xfe, 0x95, 0xb2, 0x0a, 0x5d, 0x4b, 0xc9, 0x1c, 0x6c, 0x89, 0x68, 0x09, 0x0a, 0xf9, 0x17, 0x1e, 0xf5, 0xc8, 0xfc, 0x94, 0x01, 0x00, 0x00 }; struct uint8_block body_block2 = { 203, gzip_body2 }; pubnub_init(pbp, "publ-measurements", "sub-measurements"); pubnub_set_uuid(pbp, "technician"); pubnub_set_auth(pbp, "weather-conditions"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/subscribe/sub-measurements/,/0/" "0?pnsdk=unit-test-0.1&channel-group=[air-" "temperature,humidity,wind-speed-and-direction," "pressure]&uuid=technician&auth=weather-" "conditions"); incoming("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"1516149789251234578\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe( pbp, NULL, "[air-temperature,humidity,wind-speed-and-direction,pressure]"), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(10)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-measurements/,/0/" "1516149789251234578?pnsdk=unit-test-0.1&channel-" "group=[air-temperature,humidity,wind-speed-and-" "direction,pressure]&uuid=technician&auth=weather-" "conditions"); incoming("HTTP/1.1 200\r\n" "Transfer-Encoding: chunked\r\n" "Content-Encoding: gzip\r\n" "\r\n" "29\r\n", &chunk_block0); incoming("\r\n84\r\n", &chunk_block1); incoming("\r\n0\r\n", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe( pbp, NULL, "[air-temperature,humidity,wind-speed-and-direction,pressure]"), equals(PNR_STARTED)); attest(pubnub_subscribe(pbp, "some_channels", "some_channel_goups"), equals(PNR_IN_PROGRESS)); /* 'push' until finished */ attest(pbnc_fsm(pbp), equals(0)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest(pubnub_subscribe(pbp, NULL, "some_channel_goups"), equals(PNR_RX_BUFF_NOT_EMPTY)); attest(pubnub_get(pbp), streqs("{\"uuid1\":\"-2\"}")); attest(pubnub_get_channel(pbp), streqs("ch-atmp")); attest(pubnub_get(pbp), streqs("{\"uuid2\":\"-5\"}")); attest(pubnub_get(pbp), streqs("{\"Kingston\":\"+22\"}")); attest(pubnub_get(pbp), streqs("{\"Manila\":\"+38\"}")); attest(pubnub_get(pbp), streqs("{\"bouy76\":\"+5\"}")); attest(pubnub_subscribe(pbp, NULL, "wind-speed-and-direction"), equals(PNR_RX_BUFF_NOT_EMPTY)); attest(pubnub_get(pbp), streqs("{\"Pr. Astrid Coast\":\"Unable_to_fetch_temperature\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); pubnub_set_uuid(pbp, "bird"); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/sub-measurements/uuid/" "bird?pnsdk=unit-test-0.1&auth=weather-" "conditions"); incoming("HTTP/1.1 200\r\nContent-Length: " "100\r\n\r\n{\"status\":200,\"message\":\"OK\",\"service\":" "\"Presence\",\"Payload\":{\"channels\":[discovery,nat_geo,nature]" "}}", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); /* Recognizes the uuid set from the context */ attest(pubnub_where_now(pbp, NULL), equals(PNR_OK)); attest(pbp->core.uuid_len, equals(4)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"Payload\":{\"channels\":[discovery,nat_geo,nature]}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/sub-measurements/,/0/" "1516149789251234583?pnsdk=unit-test-0.1&channel-" "group=[air-temperature,humidity,wind-speed-and-" "direction,pressure]&uuid=bird&auth=weather-" "conditions"); incoming("HTTP/1.1 200\r\n" "Content-Encoding: gzip\r\n" "Content-Length: 203\r\n" "\r\n", &body_block2); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe( pbp, NULL, "[air-temperature,humidity,wind-speed-and-direction,pressure]"), equals(PNR_OK)); attest(pubnub_get_channel(pbp), streqs("ch-ws1")); attest( pubnub_get(pbp), streqs( "{\"uuid1\":{\"dir\":w,\"speed\":\"2mph\",\"blows\":\"3mph\"}}")); attest( pubnub_get(pbp), streqs( "{\"uuid2\":{\"dir\":nw,\"speed\":\"5mph\",\"blows\":\"7mph\"}}")); attest(pubnub_get(pbp), streqs("{\"Sebu, Philippines\":{\"dir\":nne,\"speed\":\"4mph\",\"blows\":\"4mph\"}}")); attest(pubnub_get(pbp), streqs("{\"Sri Jayawardenepura Kotte, Sri Lanka\":{\"dir\":ne,\"speed\":\"7mph\",\"blows\":\"7mph\"}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, global_here_now_gzip_response) { uint8_t gzip_body[] = { 0x1f, 0x8b, 0x08, 0x00, 0x26, 0x60, 0xe4, 0x5a, 0x02, 0x03, 0x5d, 0xcf, 0x4b, 0x0a, 0x83, 0x30, 0x10, 0x06, 0xe0, 0xab, 0xc8, 0xac, 0x67, 0xa1, 0x89, 0x52, 0xc8, 0x15, 0xba, 0x68, 0xf7, 0x45, 0x4a, 0x88, 0xa1, 0x0a, 0x31, 0x91, 0x3c, 0x5a, 0x44, 0xbc, 0x5a, 0xcf, 0xd0, 0x23, 0x35, 0x06, 0x04, 0xe3, 0x66, 0x92, 0x0c, 0xdf, 0x3f, 0x4c, 0x16, 0x70, 0x9e, 0xfb, 0xe0, 0x80, 0x91, 0xb2, 0x44, 0x18, 0xa5, 0x73, 0xfc, 0x25, 0x81, 0xc1, 0xed, 0x0a, 0x08, 0x4e, 0xda, 0xf7, 0x20, 0xb6, 0xe7, 0xdd, 0x4a, 0x27, 0x75, 0xbc, 0x22, 0x4c, 0x7c, 0x56, 0x86, 0x77, 0xc0, 0x16, 0xd1, 0x73, 0xad, 0xa5, 0x72, 0x6c, 0x01, 0xd1, 0x57, 0xb1, 0x01, 0x21, 0x0c, 0x5d, 0x9c, 0xf5, 0xd8, 0xce, 0x0a, 0xb7, 0x4a, 0x52, 0xa5, 0x2d, 0x82, 0x11, 0x22, 0x4c, 0x5c, 0x8b, 0x19, 0x18, 0x5d, 0x31, 0x26, 0xc8, 0x39, 0x41, 0x93, 0xad, 0x73, 0x4b, 0x92, 0xa5, 0x67, 0x7b, 0xc9, 0x55, 0x95, 0x54, 0x7d, 0x54, 0x39, 0x28, 0x13, 0x68, 0x8e, 0xc0, 0xdb, 0x41, 0xcc, 0x42, 0x49, 0x2c, 0x46, 0xe3, 0x7b, 0x69, 0xb1, 0x70, 0x9f, 0xdf, 0xd7, 0x76, 0x2d, 0x16, 0xf9, 0xb2, 0x31, 0xea, 0x8d, 0xe7, 0xea, 0xb9, 0x7f, 0x18, 0x58, 0xb3, 0xb7, 0x8e, 0x3b, 0x90, 0x75, 0xfd, 0x03, 0x8d, 0x7b, 0x90, 0x91, 0x50, 0x01, 0x00, 0x00 }; struct uint8_block body_block = { 197, gzip_body }; uint8_t gzip_chunk1[] = { 0x1f, 0x8b, 0x08, 0x00, 0x67, 0x51, 0xe4, 0x5a, 0x02, 0x03, 0xb5, 0x5a, 0x69, 0x73, 0x1b, 0x47, 0x92, 0xfd, 0x2b, 0x13, 0xfa, 0xbc, 0x85, 0xa8, 0xfb, 0xd8, 0x6f, 0x38, 0x6d, 0x79, 0x64, 0x51, 0x23, 0x79, 0x67, 0x6c, 0x6f, 0x4c, 0x20, 0xea, 0x94, 0x20, 0x93, 0x00, 0x87, 0x00, 0xa5, 0xd1, 0x1c, 0xff, 0x7d, 0x5f, 0x56, 0x77, 0x43, 0xa4, 0x65, 0x07, 0x38, 0x1b, 0xb6, 0x29, 0xd2, 0xec, 0xee, 0xea, 0xaa, 0xac, 0xcc, 0x97, 0x2f, 0x5f, 0x16, 0xf8, 0xcf, 0x67, 0xc7, 0x53, 0x3c, 0xdd, 0x1f, 0x9f, 0xfd, 0xf7, 0x1f, 0x24, 0xe7, 0xff, 0xf5, 0x87, 0x67, 0x37, 0xf5, 0x78, 0x8c, 0x6f, 0x2b, 0xae, 0x9f, 0x5d, 0xfd, 0xf1, 0x19, 0x6e, 0xdc, 0xc6, 0x4f, 0xd7, 0x87, 0x58, 0x70, 0xe3, 0x9f, 0xcf, 0xf2, 0xbb, 0xb8, 0xdf, 0xd7, 0xeb, 0x63, 0xbf, 0xb8, 0xdb, 0xdd, 0xc6, 0x3d, 0x7b, 0x17, 0xaf, 0xaf, 0x0f, 0xfb, 0x7a, 0x62, 0xc7, 0xba, 0x3f, 0x1e, 0xee, 0x86, 0x47, 0x87, 0x9c, 0xef, 0xf1, 0x30, 0x7f, 0xc2, 0x95, 0xc0, 0x1c, 0xf7, 0xf7, 0xbb, 0x42, 0x4f, 0xfe, 0xf7, 0x99, 0x77, 0xb2, 0x96, 0x66, 0x38, 0x4b, 0x59, 0x56, 0xa6, 0x93, 0x8f, 0x2c, 0xb6, 0x28, 0x58, 0x48, 0x26, 0x28, 0xe5, 0x22, 0x7e, 0xfa, 0x67, 0x7f, 0xfd, 0x37, 0xde, 0x79, 0x75, 0x77, 0xf8, 0xfb, 0xa7, 0xed, 0xf2, 0x5d, 0xcd, 0x3f, 0x6d, 0xaf, 0xf6, 0xd7, 0xbb, 0x7d, 0xdd, 0xaa, 0x0b, 0x93, 0x4b, 0x37, 0x73, 0x7a, 0x26, 0x14, 0x9f, 0x09, 0xee, 0x86, 0x59, 0x62, 0xb9, 0xd9, 0xed, 0x6f, 0x0f, 0x77, 0xa7, 0x78, 0xfd, 0xc5, 0xcb, 0xf2, 0xd1, 0xcb, 0x45, 0xf2, 0x26, 0x5d, 0x12, 0xac, 0x5a, 0xdb, 0x98, 0x96, 0xda, 0xb1, 0x18, 0x92, 0x66, 0xd2, 0x6a, 0xad, 0x64, 0xf5, 0x36, 0xda, 0x44, 0xfe, 0x10, 0xbc, 0x5a, 0x5f, 0xa4, 0x66, 0x5c, 0x6a, 0xc5, 0xb4, 0xd7, 0x99, 0xf9, 0x60, 0x39, 0x93, 0x4e, 0x9b, 0x9c, 0xaa, 0xa8, 0x3a, 0xa7, 0x61, 0xed, 0x37, 0xef, 0x76, 0xf5, 0xba, 0x6c, 0xbf, 0xdc, 0x88, 0xfc, 0x72, 0x1f, 0x86, 0x3f, 0x32, 0x46, 0x48, 0xec, 0x83, 0x9b, 0x99, 0x90, 0x62, 0x26, 0xac, 0xef, 0xeb, 0x0a, 0x3e, 0x33, 0x7a, 0x26, 0x95, 0xc3, 0x1d, 0x4d, 0x77, 0x74, 0x98, 0x09, 0x8d, 0xab, 0xa0, 0x66, 0x41, 0x0d, 0x43, 0x14, 0x9e, 0x89, 0x99, 0xc1, 0x8b, 0x9c, 0xf7, 0x21, 0x76, 0xa6, 0xec, 0xcc, 0x9a, 0x99, 0x14, 0xfd, 0x1a, 0x0f, 0x25, 0xdc, 0xe3, 0xe1, 0x24, 0x3d, 0xbc, 0x21, 0x67, 0x92, 0xe3, 0x2d, 0xed, 0x67, 0xce, 0xf4, 0x3b, 0x92, 0xcf, 0x24, 0x26, 0xe6, 0xf8, 0x16, 0x81, 0xee, 0x60, 0x02, 0x49, 0xdf, 0xb0, 0x44, 0xda, 0x3e, 0x24, 0xc0, 0xc1, 0xd2, 0x93, 0x19, 0x33, 0xe1, 0x25, 0xdd, 0x82, 0xe7, 0x25, 0x99, 0x42, 0xae, 0x0f, 0x83, 0xb9, 0x9e, 0x7e, 0x15, 0x33, 0x8f, 0xbb, 0xa2, 0xaf, 0x45, 0x86, 0x7b, 0x3b, 0xd3, 0x72, 0x66, 0xc7, 0xb5, 0x03, 0xec, 0x9e, 0xd1, 0xe2, 0xe3, 0xb5, 0x9d, 0x05, 0x9a, 0x15, 0xff, 0xb3, 0xe7, 0x85, 0xf1, 0x98, 0x0b, 0x9a, 0xa9, 0x2f, 0x03, 0x53, 0xa5, 0xc4, 0xad, 0x6e, 0x41, 0xdf, 0x51, 0xd0, 0x33, 0x13, 0x06, 0x5f, 0x75, 0x6b, 0x8d, 0xef, 0xab, 0x88, 0xe0, 0x3e, 0xef, 0x11, 0x97, 0xb4, 0x47, 0x4e, 0x8f, 0xfa, 0x4b, 0xc2, 0x38, 0xb2, 0x43, 0xd0, 0xb7, 0x17, 0xc3, 0xb6, 0x25, 0x2c, 0x51, 0x01, 0xdb, 0x14, 0x67, 0xdf, 0xfa, 0x99, 0x87, 0xb1, 0xc3, 0x73, 0x47, 0x3e, 0x94, 0x33, 0x47, 0x6b, 0x0d, 0x77, 0x38, 0xa6, 0x1d, 0xde, 0xd0, 0xd3, 0x0c, 0xb4, 0x94, 0x94, 0x66, 0xe6, 0xec, 0x67, 0xe7, 0xc2, 0x9d, 0x34, 0xd2, 0x8c, 0xae, 0x33, 0x04, 0x51, 0x49, 0xe1, 0x55, 0x72, 0xb8, 0x83, 0x41, 0xe4, 0x4c, 0x2c, 0x20, 0xd4, 0xf4, 0x9a, 0x20, 0x47, 0x90, 0xcd, 0x63, 0x50, 0x06, 0x57, 0x49, 0x03, 0x4f, 0xb8, 0xbe, 0xba, 0xd7, 0x33, 0x4c, 0x25, 0x95, 0x9c, 0x6e, 0xd0, 0x68, 0xcc, 0x40, 0x21, 0x38, 0xdb, 0x8f, 0x6b, 0x41, 0x51, 0xeb, 0x01, 0xf1, 0x98, 0xd1, 0x90, 0x89, 0xe4, 0x88, 0xcf, 0x06, 0xe3, 0x2e, 0xa1, 0x66, 0x9c, 0x44, 0xc0, 0x3c, 0xbc, 0xe5, 0x60, 0xb0, 0x0e, 0x23, 0x60, 0xba, 0x47, 0x71, 0xd3, 0xfb, 0x73, 0x50, 0xf8, 0x4c, 0xe1, 0x86, 0x71, 0x93, 0x7b, 0x1d, 0x85, 0xc4, 0x4e, 0x2b, 0x75, 0xc8, 0x62, 0x94, 0x99, 0x69, 0xf5, 0xd9, 0x0f, 0xd8, 0x31, 0xb6, 0x2a, 0x2c, 0x9f, 0xd6, 0xa6, 0xaf, 0x01, 0x3d, 0x67, 0x68, 0x13, 0xca, 0xba, 0xad, 0x61, 0xa6, 0x71, 0x8d, 0x5d, 0x4b, 0x1e, 0x86, 0xf1, 0x74, 0xe9, 0x09, 0x2c, 0x2a, 0x4c, 0xf1, 0x10, 0xb0, 0x4c, 0x62, 0x75, 0x3f, 0x6d, 0xd8, 0x70, 0xc2, 0xd2, 0xac, 0x87, 0x03, 0x2f, 0x20, 0x0d, 0x80, 0xe4, 0x60, 0xce, 0xe3, 0x95, 0x9f, 0xc1, 0x83, 0x23, 0x3e, 0x75, 0x87, 0x27, 0x6e, 0x49, 0x39, 0xec, 0x43, 0x8b, 0x9e, 0x5c, 0x14, 0x2d, 0x39, 0x80, 0x5a, 0xd0, 0x7c, 0xb8, 0x81, 0x9f, 0x83, 0x59, 0x04, 0x69, 0xd3, 0x51, 0x2e, 0x85, 0x99, 0xec, 0x22, 0xec, 0x01, 0x82, 0x26, 0x9c, 0xf7, 0x4a, 0xef, 0x39, 0x6c, 0x69, 0x88, 0x84, 0x1c, 0x3c, 0x0c, 0xd7, 0x7a, 0x73, 0xb6, 0x34, 0xcc, 0xec, 0x34, 0x40, 0x08, 0x47, 0x91, 0xd3, 0xb4, 0xb7, 0x0e, 0x12, 0x00, 0xa4, 0x3b, 0x93, 0x82, 0x2d, 0x1f, 0x22, 0x02, 0x61, 0xd1, 0x63, 0x72, 0xa9, 0x19, 0xe2, 0x89, 0xbb, 0x72, 0xf0, 0xb0, 0xef, 0x3b, 0x03, 0x1a, 0xa4, 0x1a, 0xe7, 0xc4, 0x66, 0xb4, 0xed, 0x11, 0x1f, 0x6c, 0xef, 0x71, 0x83, 0x95, 0x14, 0x97, 0x1e, 0x58, 0x5a, 0x9e, 0x36, 0x46, 0xa6, 0x8e, 0xe9, 0x49, 0x86, 0x4b, 0x5a, 0x36, 0xc8, 0x09, 0x52, 0x20, 0x52, 0xc0, 0x4e, 0x8d, 0x71, 0xb1, 0x3d, 0x4e, 0x82, 0xcb, 0x59, 0xe0, 0xe3, 0xa4, 0x0e, 0x79, 0x66, 0xd4, 0x04, 0x3b, 0xd1, 0x93, 0x93, 0xb0, 0x8d, 0x6f, 0x33, 0x86, 0x92, 0xa6, 0xa5, 0x74, 0xb4, 0xf6, 0xf3, 0xac, 0x58, 0x9a, 0xf8, 0x60, 0x08, 0x55, 0xb7, 0x44, 0xc1, 0xd3, 0x83, 0x43, 0x88, 0x81, 0xfa, 0x3f, 0x21, 0x27, 0xff, 0x00, 0x29, 0x66, 0xf2, 0xf9, 0xe4, 0xd0, 0x10, 0xa6, 0xe4, 0x95, 0xb4, 0xf9, 0x4e, 0x5c, 0x6a, 0x8c, 0x8a, 0xe9, 0x20, 0xed, 0x3e, 0x1d, 0xe3, 0xdf, 0x1d, 0x12, 0x7a, 0xca, 0x4b, 0xdd, 0x6f, 0x21, 0xfa, 0x82, 0x76, 0x03, 0xde, 0x72, 0xe1, 0x9c, 0x33, 0x81, 0x52, 0xdc, 0x8e, 0x6c, 0xa3, 0x87, 0x58, 0xc2, 0xfd, 0x21, 0x9c, 0xf3, 0x43, 0x75, 0x30, 0x8f, 0xa8, 0x21, 0x36, 0x13, 0x03, 0xf7, 0x99, 0x11, 0x34, 0x7e, 0xc8, 0x3a, 0x37, 0xa1, 0xa6, 0x43, 0x4f, 0xf3, 0x8e, 0xdf, 0xf1, 0x56, 0x5f, 0x49, 0x0f, 0xf3, 0x70, 0xfb, 0x90, 0x76, 0xb1, 0x94, 0x19, 0xe8, 0xc4, 0x89, 0xce, 0x86, 0x0f, 0xb2, 0x88, 0xc8, 0x9d, 0x77, 0x5a, 0x1a, 0x81, 0x42, 0x18, 0xb6, 0x8e, 0x40, 0x30, 0xbe, 0x24, 0xc9, 0x69, 0x08, 0x0a, 0x71, 0xa8, 0x18, 0xa1, 0x42, 0x26, 0xfb, 0x19, 0x68, 0x72, 0xf0, 0x26, 0x30, 0x6c, 0x01, 0x03, 0x39, 0xf3, 0xe7, 0x49, 0x81, 0x37, 0xa2, 0xb5, 0x91, 0xa5, 0x45, 0x9f, 0x13, 0x8c, 0x64, 0x27, 0xd2, 0xa6, 0xd4, 0x75, 0x7c, 0x0c, 0xd6, 0xe0, 0x7a, 0x4e, 0xac, 0x60, 0xd4, 0x79, 0x7b, 0x94, 0x19, 0x44, 0xaf, 0x6e, 0xb8, 0x45, 0xf3, 0x83, 0xb9, 0x1f, 0x56, 0x02, 0x7c, 0x03, 0xb4, 0xd6, 0x4c, 0x34, 0x2e, 0x00, 0x1c, 0x5a, 0x67, 0x48, 0x35, 0x4a, 0x33, 0xac, 0xac, 0xcf, 0x66, 0xe3, 0x29, 0xae, 0x25, 0xcd, 0x39, 0xbc, 0xd3, 0x59, 0x88, 0x6a, 0x89, 0x7b, 0x8c, 0x60, 0xaa, 0x41, 0x66, 0x4c, 0x71, 0x4f, 0x79, 0x68, 0x27, 0xb0, 0x76, 0xd2, 0xd4, 0x53, 0x1a, 0x9c, 0x6d, 0xa7, 0xbc, 0x81, 0xef, 0x07, 0x8a, 0x26, 0x23, 0x42, 0x0f, 0x9f, 0x94, 0x61, 0x08, 0x5f, 0x20, 0x82, 0xf6, 0xe4, 0x85, 0x91, 0x35, 0x2d, 0xe1, 0x8c, 0x5c, 0xe0, 0x1f, 0x30, 0x97, 0x26, 0x97, 0xf6, 0x01, 0x94, 0xda, 0x94, 0x36, 0xee, 0x8c, 0x91, 0x21, 0x59, 0x25, 0x81, 0x8f, 0x8f, 0x78, 0x14, 0x94, 0x37, 0xf8, 0xa7, 0x27, 0xff, 0x28, 0xf2, 0x0f, 0xd8, 0xe3, 0x61, 0xa9, 0xec, 0xd5, 0x53, 0x3d, 0x74, 0x19, 0x76, 0x34, 0x62, 0xa8, 0xf3, 0x0c, 0x85, 0xda, 0x4e, 0xf5, 0xa7, 0xa7, 0x41, 0xe8, 0x5e, 0x9d, 0x32, 0x0b, 0x38, 0xc0, 0x73, 0x0b, 0xdf, 0x9f, 0xe1, 0x01, 0xca, 0x90, 0x9c, 0x68, 0x21, 0x9c, 0xa3, 0x69, 0x7b, 0x4d, 0x1e, 0xeb, 0xd1, 0xb4, 0x34, 0x6d, 0xbb, 0x4f, 0xdb, 0xab, 0x8a, 0xe9, 0x69, 0xcd, 0xd5, 0x04, 0x08, 0x6d, 0x87, 0xe2, 0x77, 0x66, 0x4e, 0x92, 0x59, 0xa4, 0x10, 0x86, 0x72, 0x8a, 0xec, 0xeb, 0xe0, 0x46, 0xdd, 0xf5, 0x7d, 0x5a, 0x54, 0x1e, 0xbc, 0x82, 0x1f, 0xe1, 0x73, 0xa0, 0x68, 0x73, 0x63, 0x5d, 0x24, 0xb6, 0xe2, 0x9d, 0xee, 0xc5, 0x90, 0xd2, 0x24, 0xdc, 0xec, 0x90, 0xd1, 0x23, 0x90, 0xf1, 0xea, 0xac, 0x13, 0xf2, 0x23, 0xed, 0x43, 0x7b, 0x1e, 0x00, 0x33, 0xd5, 0x37, 0x42, 0x92, 0x0f, 0x67, 0xb3, 0x46, 0xb5, 0xa0, 0xc6, 0x92, 0x28, 0x3a, 0x31, 0x60, 0x3b, 0x43, 0x9d, 0x71, 0x7e, 0x60, 0x1e, 0x2f, 0xa6, 0x32, 0x4f, 0x4c, 0x41, 0x8a, 0x89, 0x5c, 0x3f, 0xc2, 0x79, 0x48, 0x44, 0x47, 0x15, 0xe8, 0xcc, 0x9b, 0xc4, 0x03, 0xb4, 0x98, 0x1d, 0x15, 0x07, 0x55, 0x75, 0xc4, 0x6f, 0xd4, 0x17, 0x44, 0x06, 0x30, 0x07, 0xaf, 0xc8, 0x70, 0xe6, 0x1a, 0x44, 0xb8, 0xfb, 0xf5, 0x0c, 0x3c, 0x69, 0x86, 0x0a, 0x28, 0x07, 0xe3, 0x28, 0x27, 0x55, 0x07, 0xa7, 0x35, 0x9f, 0x8b, 0x24, 0xae, 0xfc, 0xa4, 0xa0, 0xb0, 0x8e, 0x73, 0x5d, 0x1b, 0x60, 0x9d, 0x2e, 0x28, 0x95, 0x36, 0xda, 0xd5, 0x58, 0x18, 0xd7, 0x12, 0xd2, 0x33, 0x78, 0xc5, 0xa2, 0x2b, 0x82, 0x09, 0x91, 0x53, 0x36, 0x46, 0xb7, 0x16, 0xf5, 0x05, 0x89, 0xfc, 0xa4, 0x29, 0xfa, 0x62, 0x5f, 0xbf, 0xfc, 0xea, 0xc2, 0x5c, 0x99, 0x37, 0x57, 0x45, 0x4a, 0x4c, 0x56, 0xd2, 0xf2, 0x00, 0x3b, 0x4b, 0x3c, 0x7a, 0x96, 0x5b, 0xf4, 0xd2, 0x27, 0x95, 0x78, 0x1d, 0x95, 0xf0, 0xea, 0xc5, 0xa5, 0xb9, 0x62, 0x4c, 0x21, 0x25, 0x58, 0xa3, 0x65, 0x0c, 0x4c, 0x2b, 0x65, 0x59, 0x34, 0x3a, 0xb0, 0x8c, 0x84, 0x2c, 0xd6, 0x1a, 0x6f, 0xe4, 0x38, 0x57, 0x8b, 0xc7, 0xbc, 0xdb, 0xbe, 0x85, 0x9a, 0x3e, 0x94, 0xfa, 0xe6, 0xfe, 0x98, 0xef, 0x76, 0xa9, 0xde, 0x5d, 0x98, 0xfe, 0x76, 0xcf, 0x9a, 0xcf, 0x41, 0xeb, 0x16, 0x58, 0xc9, 0xb6, 0x30, 0x9d, 0x6b, 0x63, 0xde, 0x99, 0xc2, 0x8c, 0xf7, 0x4a, 0x4a, 0xeb, 0x5a, 0xcc, 0x6d, 0x58, 0xa1, 0x5a, 0xde, 0x8a, 0x48, 0xa2, 0x05, 0xed, 0x83, 0x11, 0x2a, 0x72, 0xbc, 0x27, 0xf1, 0x6a, 0xf5, 0x11, 0xa9, 0xe6, 0x25, 0xf6, 0x15, 0x31, 0xdd, 0xbf, 0x86, 0x96, 0x67, 0x7b, 0x7b, 0xc0, 0x7c, 0x30, 0x56, 0xd8, 0x7f, 0xdd, 0x1f, 0xeb, 0x1d, 0x73, 0xc6, 0x60, 0xd4, 0x17, 0x16, 0xd9, 0x9f, 0x5b, 0x14, 0x35, 0x1c, 0xd8, 0x64, 0x60, 0xc9, 0xa1, 0x89, 0xd0, 0x09, 0xbf, 0x05, 0x9d, 0x2c, 0xb3, 0xc9, 0x62, 0xcf, 0xa6, 0x88, 0x52, 0x3b, 0x9e, 0x30, 0xd4, 0xdb, 0xd2, 0x44, 0xd2, 0x91, 0x29, 0x25, 0x39, 0x5c, 0x6d, 0x3c, 0x0b, 0x42, 0x57, 0xa6, 0x62, 0x88, 0xdc, 0x48, 0xa7, 0xda, 0x80, 0x70, 0x0c, 0xad, 0xd1, 0x21, 0xab, 0x6a, 0x61, 0xc5, 0x47, 0xf4, 0x31, 0x3a, 0x44, 0xe6, 0xab, 0x10, 0xcc, 0x97, 0x62, 0x3d, 0x8f, 0x22, 0xf1, 0xc2, 0xc7, 0xa1, 0x29, 0xe6, 0xd0, 0x5a, 0x56, 0x88, 0x98, 0xb0, 0x4c, 0x63, 0xdb, 0x2c, 0x5a, 0x1e, 0x59, 0xad, 0x2a, 0xb6, 0x66, 0x9a, 0x44, 0x50, 0xc6, 0xa1, 0x4e, 0x68, 0xe0, 0xa4, 0x2a, 0xa6, 0x0a, 0xa2, 0xa2, 0x45, 0xf1, 0xcc, 0x27, 0x9e, 0x99, 0x95, 0x46, 0x36, 0x53, 0x43, 0x6c, 0xf9, 0x3c, 0x14, 0xa6, 0x9a, 0xe8, 0x35, 0x2b, 0x25, 0xc0, 0x31, 0x0e, 0x2f, 0x79, 0xd5, 0x04, 0x83, 0x53, 0x95, 0xd3, 0x3c, 0x97, 0x68, 0xc4, 0xe0, 0xe8, 0xed, 0x76, 0x7f, 0x38, 0xed, 0xda, 0x2e, 0xc7, 0xd3, 0xee, 0xb0, 0x3f, 0x6e, 0xb7, 0xda, 0x39, 0xe5, 0x2f, 0x84, 0x32, 0xf0, 0xda, 0x4a, 0x2c, 0x95, 0x05, 0xa0, 0x15, 0xd3, 0x07, 0x20, 0xc5, 0x37, 0xcd, 0xaa, 0x93, 0x5e, 0xcb, 0x56, 0x45, 0x8e, 0x23, 0x52, 0x6e, 0x3e, 0xdd, 0xc4, 0xdb, 0x4b, 0x0d, 0xa9, 0x6e, 0x48, 0x84, 0xdc, 0x32, 0x93, 0xde, 0x22, 0x08, 0x19, 0x33, 0xf9, 0x2c, 0x13, 0xcb, 0xd9, 0x66, 0xe8, 0x11, 0xa7, 0x93, 0x1a, 0xad, 0x5d, 0x1e, 0x76, 0xfb, 0x97, 0xb0, 0x77, 0xbb, 0xd8, 0xed, 0x31, 0x55, 0xbd, 0x0c, 0x39, 0xf4, 0xba, 0x50, 0xce, 0xc9, 0x31, 0x1b, 0x32, 0x12, 0xa4, 0x08, 0xc5, 0x92, 0x16, 0x95, 0xa1, 0xee, 0x73, 0xe0, 0x27, 0x3b, 0x20, 0x6a, 0x32, 0x75, 0x3b, 0xf6, 0xd6, 0x5f, 0xce, 0xaa, 0x7f, 0x3e, 0xed, 0xda, 0x1b, 0xbd, 0x5c, 0x71, 0xc1, 0xd4, 0x1c, 0x90, 0xd1, 0xcb, 0x45, 0x60, 0x7e, 0x8e, 0x86, 0x74, 0xb9, 0x59, 0x84, 0x8d, 0x32, 0xf3, 0xf5, 0x4a, 0x4e, 0x11, 0xf6, 0xdc, 0x29, 0xbb, 0x96, 0x92, 0x71, 0xb3, 0x42, 0x84, 0x37, 0x56, 0xb2, 0xb9, 0x9c, 0x6f, 0x98, 0xd9, 0xac, 0xe4, 0x4a, 0x73, 0xbf, 0x31, 0x76, 0x3e, 0x0e, 0x5d, 0xad, 0xdd, 0xc6, 0x8b, 0x4d, 0x60, 0xcb, 0x30, 0x37, 0xc0, 0xb3, 0x72, 0x2c, 0x58, 0xb9, 0x62, 0x6e, 0x35, 0x0f, 0xc1, 0x1a, 0x67, 0xbc, 0x73, 0xe3, 0xd0, 0xc0, 0x97, 0x81, 0xf3, 0xb9, 0xc2, 0x5c, 0x01, 0x68, 0xf4, 0x76, 0xc5, 0x30, 0x46, 0xb2, 0xc5, 0xca, 0xad, 0xf8, 0x5a, 0x71, 0x2c, 0xb9, 0x9e, 0x66, 0x05, 0xa1, 0x2b, 0xb5, 0x00, 0xa8, 0xcd, 0x82, 0x70, 0x83, 0xb5, 0x31, 0x74, 0xc5, 0xd6, 0x4a, 0xdb, 0xb9, 0x5d, 0xf9, 0xb5, 0x38, 0x03, 0x57, 0xaf, 0x97, 0x73, 0x13, 0xa4, 0x63, 0x6a, 0xed, 0x24, 0xb6, 0xa5, 0x11, 0x09, 0x32, 0xc5, 0xad, 0x0d, 0x37, 0x76, 0x09, 0xe3, 0x86, 0xe2, 0x88, 0xa1, 0x72, 0x1d, 0x8c, 0xd9, 0x2c, 0xe6, 0xb0, 0x64, 0x33, 0x07, 0x5b, 0x08, 0x47, 0xdb, 0x12, 0x4c, 0x06, 0x2f, 0xdd, 0x42, 0xc9, 0xe5, 0x62, 0x35, 0xcd, 0xaa, 0x82, 0x92, 0x26, 0x6c, 0x34, 0x13, 0xab, 0x95, 0x66, 0x7a, 0xa5, 0x97, 0x6c, 0x6e, 0xe7, 0x73, 0xe6, 0xf5, 0x12, 0xf3, 0xba, 0x95, 0x5c, 0xfb, 0xc9, 0xd6, 0xe2, 0x5d, 0xd1, 0x35, 0x15, 0x56, 0x83, 0xc3, 0x50, 0xe5, 0x04, 0x38, 0x48, 0x02, 0xc2, 0x3e, 0x39, 0x9f, 0x15, 0x32, 0xe0, 0x6c, 0x2b, 0xc4, 0x80, 0xb7, 0x1b, 0xb1, 0x60, 0x6a, 0xa9, 0xc0, 0x59, 0xdc, 0x1a, 0x16, 0x5c, 0x08, 0x6c, 0xae, 0x36, 0x1b, 0x29, 0x97, 0x6e, 0x81, 0x7d, 0x4d, 0x06, 0xd8, 0x35, 0xe8, 0x20, 0x2c, 0xd8, 0x6a, 0xb3, 0x59, 0x21, 0x04, 0x72, 0x0d, 0x5b, 0xfd, 0x92, 0xad, 0x37, 0x7e, 0xbd, 0x11, 0xcb, 0xb5, 0xd6, 0xcb, 0xe5, 0xe4, 0x57, 0xef, 0x34, 0x32, 0x59, 0x33, 0x5e, 0x1c, 0x9c, 0x05, 0xd2, 0x63, 0x31, 0x35, 0x04, 0x4f, 0x81, 0x84, 0x9c, 0x05, 0x62, 0xce, 0xf9, 0xb8, 0x94, 0xf0, 0x94, 0x5f, 0xc1, 0x03, 0x2b, 0x8a, 0x56, 0x90, 0x96, 0x2d, 0xc8, 0x77, 0xf3, 0xd5, 0x62, 0x81, 0x0e, 0x79, 0xb5, 0x90, 0x43, 0x0f, 0x8d, 0xa1, 0x73, 0x25, 0xe0, 0x12, 0x61, 0x80, 0x1b, 0xc4, 0x41, 0xf3, 0x05, 0x02, 0x85, 0x2a, 0xc7, 0xac, 0x58, 0x2c, 0xd7, 0x0b, 0x07, 0x8e, 0x83, 0xb3, 0x3a, 0x0a, 0xdf, 0xdf, 0x6c, 0x63, 0x35, 0x4e, 0x58, 0xc5, 0x41, 0x2f, 0x01, 0x3e, 0x30, 0xc9, 0xb3, 0x84, 0x6e, 0x85, 0x85, 0x64, 0x35, 0xe8, 0x28, 0xbb, 0xec, 0xe3, 0xf6, 0xfe, 0xf6, 0x7a, 0xb7, 0xff, 0xe9, 0x02, 0xfe, 0x6d, 0xf5, 0xda, 0x1b, 0x9f, 0x58, 0xe5, 0x2e, 0x32, 0x14, 0x96, 0x02, 0x17, 0x79, 0xc7, 0x8c, 0x05, 0xb1, 0xc3, 0xb7, 0xde, 0xb4, 0xf1, 0x8c, 0xe6, 0xf6, 0x6d, 0x89, 0x9f, 0x2e, 0xcc, 0xe6, 0x72, 0x53, 0x20, 0xa4, 0xcc, 0x62, 0x4b, 0x70, 0x78, 0x54, 0x92, 0x45, 0x09, 0x3e, 0x6c, 0xc6, 0xeb, 0x2c, 0x0a, 0x97, 0xb1, 0x85, 0x61, 0xb6, 0xe3, 0xee, 0xf8, 0xe1, 0xf7, 0xad, 0x0f, 0xd1, 0xa5, 0x92, 0x9c, 0x88, 0x17, 0x0e, 0x94, 0x9c, 0x8b, 0x32, 0x67, 0xd4, 0x56, 0xe7, 0x51, 0x6f, 0xb5, 0x08, 0x95, 0x25, 0x74, 0xf0, 0x8c, 0x53, 0x45, 0x4b, 0x21, 0x9a, 0xc8, 0xfb, 0x81, 0x92, 0xb5, 0x15, 0x24, 0x13, 0x2d, 0xcb, 0x56, 0x3b, 0x8c, 0xb3, 0x20, 0x34, 0x62, 0x79, 0x67, 0xa3, 0xe4, 0x8d, 0x62, 0x3f, 0x6d, 0xed, 0xf6, 0xfe, 0x2e, 0x7e, 0xd8, 0x95, 0x78, 0x61, 0x33, 0x60, 0x17, 0x9e, 0x6c, 0x8d, 0xac, 0x98, 0x82, 0x18, 0x4a, 0x30, 0x8e, 0x2f, 0xd2, 0x20, 0x10, 0x56, 0xe6, 0x5a, 0xc0, 0xee, 0xbc, 0x0e, 0x13, 0x2e, 0xe6, 0x3f, 0x5c, 0x3a, 0xaf, 0x43, 0x59, 0x42, 0x0a, 0x45, 0x86, 0x6f, 0x4f, 0x7e, 0x07, 0x99, 0xd7, 0x80, 0x6a, 0xe2, 0x92, 0xf6, 0x25, 0x29, 0x95, 0xca, 0xa8, 0x17, 0xde, 0xac, 0x5f, 0xbe, 0x59, 0x7f, 0x7b, 0xc5, 0xae, 0x9e, 0xf3, 0xcd, 0xf7, 0xe1, 0xa5, 0xba, 0xe0, 0x9d, 0x04, 0xc5, 0x0c, 0x1d, 0x12, 0x19, 0x3a, 0x78, 0xd0, 0x38, 0x97, 0x02, 0x65, 0xd0, 0x35, 0x86, 0x42, 0x67, 0x33, 0xd5, 0x3f, 0xf0, 0xef, 0x20, 0x73, 0x93, 0x51, 0xc5, 0x07, 0xc6, 0x33, 0xb0, 0xd4, 0x45, 0x46, 0xb0, 0xc5, 0x62, 0x6f, 0x1e, 0x3c, 0x2d, 0x6b, 0x46, 0x95, 0x1a, 0x03, 0x7f, 0xbd, 0xbb, 0xf9, 0x5d, 0xe3, 0x0e, 0x86, 0x3e, 0x5d, 0x98, 0x0f, 0x82, 0x88, 0x03, 0x1e, 0x8d, 0x39, 0x44, 0x9e, 0xe9, 0x8a, 0x3a, 0x1d, 0x85, 0x6f, 0x1d, 0xfe, 0x12, 0x06, 0x83, 0x25, 0xc7, 0xc9, 0x7e, 0x38, 0xdc, 0x9f, 0xee, 0x53, 0xdd, 0x2e, 0xbf, 0xdd, 0xfe, 0xf9, 0xcd, 0x2f, 0xa8, 0x36, 0xff, 0x58, 0xb6, 0xb9, 0xf1, 0x74, 0xc3, 0x92, 0x9c, 0x65, 0x3f, 0x7c, 0xb5, 0x7e, 0xbd, 0x5c, 0x5d, 0xaf, 0xee, 0xf8, 0xd4, 0xc8, 0x42, 0x58, 0xa2, 0xa9, 0x41, 0x74, 0xde, 0xb9, 0xdd, 0x7e, 0x51, 0xde, 0x3d, 0xbf, 0x1a, 0x84, 0x33, 0x89, 0x74, 0xa8, 0xe2, 0xae, 0x3b, 0x2d, 0xfb, 0xf4, 0x29, 0xee, 0x7f, 0x3c, 0x85, 0x6f, 0xde, 0x2f, 0xba, 0x6c, 0xef, 0x9a, 0x94, 0x0e, 0x07, 0x81, 0xb6, 0xef, 0xbf, 0xa9, 0xdf, 0x1d, 0x77, 0x6e, 0xf1, 0x4d, 0x19, 0xfb, 0xa2, 0xa1, 0x63, 0xc6, 0x73, 0xcf, 0x9e, 0xdf, 0xef, 0xc3, 0xa7, 0x8f, 0xf3, 0x20, 0xee, 0xfb, 0x72, 0x6a, 0x46, 0xed, 0x50, 0x57, 0xe7, 0x9c, 0x9d, 0x3e, 0xe4, 0xba, 0xdb, 0xbd, 0x7f, 0xff, 0x82, 0x8f, 0xdd, 0x43, 0xe8, 0x0d, 0x1a, 0x09, 0x66, 0xf6, 0xc7, 0xe5, 0x5b, 0xaa, 0xfc, 0xaf, 0xfd, 0xa0, 0xe9, 0x49, 0x04, 0xf7, 0xb3, 0x59, 0xea, 0x5c, 0x58, 0x90, 0xf3, 0xd5, 0xc7, 0xfc, 0xcd, 0x8b, 0xb0, 0x19, 0x7a, 0x82, 0xe1, 0x10, 0xc5, 0x43, 0xf3, 0x32, 0xf1, 0x36, 0xbd, 0xbc, 0x7a, 0x21, 0xfe, 0xfc, 0xea, 0xf6, 0x67, 0xb6, 0x18, 0xce, 0x6e, 0xd6, 0xf9, 0x90, 0x51, 0x44, 0x5f, 0xed, 0xa7, 0x56, 0xa2, 0x77, 0x75, 0x86, 0x3a, 0x47, 0xcb, 0xc2, 0x8f, 0xed, 0x5d, 0x7c, 0xbd, 0x7a, 0xf5, 0x95, 0x1e, 0x35, 0x36, 0xc9, 0x77, 0xf4, 0xaf, 0xc8, 0xa9, 0xc3, 0x9f, 0xec, 0xdf, 0xfe, 0x72, 0x2d, 0x9f, 0xeb, 0xbb, 0xb3, 0x63, 0xa8, 0xb3, 0xa3, 0xe6, 0x57, 0xb0, 0x97, 0x57, 0xee, 0xeb, 0x1f, 0x6f, 0xe2, 0xfd, 0xfb, 0xd3, 0xf4, 0x90, 0x24, 0x3e, 0x1d, 0xd3, 0x80, 0x58, 0xf9, 0x3f, 0xf4, 0x8b, 0xdb, 0x7f, 0xfc, 0x4f, 0x79, 0xf9, 0xfc, 0x97, 0x96, 0xfc, 0xf1, 0xe3, 0xed, 0xfc, 0xfd, 0xd5, 0xf3, 0xaf, 0x17, 0x7f, 0x1b, 0x1d, 0x40, 0xfd, 0x86, 0x34, 0xe8, 0x39, 0x14, 0xab, 0xf6, 0xd5, 0x21, 0xbf, 0xff, 0x29, 0x8f, 0x9d, 0xe1, 0xe3, 0x60, 0x3c, 0x2f, 0x6f, 0x77, 0xb7, 0x57, 0xdf, 0xbf, 0xfe, 0xf8, 0xfd, 0x74, 0xfc, 0x44, 0x0d, 0x0b, 0x1c, 0xe0, 0xd9, 0x69, 0xf3, 0x63, 0x8b, 0xe1, 0xbb, 0x1f, 0xf6, 0x7f, 0x39, 0x13, 0x73, 0x91, 0x99, 0xc7, 0x58, 0xa8, 0x24, 0x15, 0x20, 0xab, 0x15, 0xc8, 0x46, 0x2b, 0x34, 0xcb, 0xbe, 0x6a, 0x70, 0x0b, 0xb8, 0x46, 0xe6, 0xa7, 0x11, 0x73, 0xac, 0x4e, 0xd7, 0xe2, 0x32, 0xa4, 0x5c, 0x45, 0x46, 0x29, 0xd4, 0xd9, 0xe0, 0x90, 0x51, 0xc9, 0x35, 0x93, 0x52, 0x71, 0x1c, 0xd5, 0x6f, 0x58, 0xf6, 0x5d, 0xbd, 0xbe, 0x3e, 0x6c, 0x3f, 0x1e, 0xee, 0xae, 0xcb, 0x85, 0x6c, 0x26, 0xb1, 0xe3, 0x79, 0x40, 0x1d, 0xf2, 0x0c, 0x15, 0x04, 0x34, 0x56, 0x5a, 0x64, 0xa0, 0x49, 0xb0, 0x4e, 0x0a, 0xda, 0x18, 0xf4, 0x43, 0xae, 0x0d, 0xd0, 0x92, 0x48, 0x7b, 0x09, 0xf3, 0x33, 0x37, 0x1a, 0xfa, 0x11, 0x22, 0x0e, 0x3a, 0xc3, 0x43, 0xa1, 0x40, 0xdf, 0x72, 0x9f, 0x8a, 0xb4, 0xa3, 0xe0, 0x4a, 0x35, 0xfe, 0x74, 0xd8, 0x6f, 0x4f, 0xf5, 0x78, 0x29, 0xed, 0x56, 0xf3, 0x97, 0xcf, 0xd7, 0x2f, 0x5e, 0xac, 0xcf, 0x79, 0x4a, 0x4a, 0x6a, 0xab, 0x0d, 0xdf, 0xea, 0xad, 0xb7, 0x31, 0xa0, 0x73, 0x8b, 0xd5, 0x1a, 0xd8, 0x60, 0x8d, 0x88, 0xf0, 0x98, 0xb1, 0x5e, 0x19, 0x28, 0x3b, 0x7b, 0x89, 0x4b, 0x51, 0xf3, 0x94, 0x96, 0xa0, 0x1f, 0x21, 0x41, 0x4e, 0xda, 0xa6, 0xcc, 0x52, 0x0e, 0x8e, 0xe5, 0x82, 0xaf, 0x94, 0xb4, 0xcc, 0x51, 0x0d, 0xab, 0x5e, 0xbd, 0xfe, 0xd3, 0xa5, 0x1a, 0x16, 0x0c, 0xfa, 0xbd, 0x9c, 0x98, 0xab, 0x55, 0x10, 0x39, 0xa0, 0x9a, 0xc9, 0xec, 0x98, 0x03, 0xf9, 0x49, 0x14, 0x5e, 0xef, 0xe5, 0x48, 0xf4, 0xdf, 0xbd, 0xb8, 0xc4, 0xcb, 0xc9, 0xa3, 0x41, 0x90, 0x51, 0x31, 0xa3, 0x38, 0x82, 0xe8, 0xc1, 0x5a, 0x90, 0x44, 0x05, 0xe8, 0x00, 0x81, 0x79, 0x55, 0x01, 0x8b, 0xa9, 0xba, 0xde, 0xa7, 0xfd, 0x7d, 0x62, 0xef, 0x4e, 0x37, 0xd7, 0x86, 0x3d }; struct uint8_block chunk_block1 = { 3085, gzip_chunk1 }; uint8_t gzip_chunk2[] = { 0xd4, 0xdb, 0xac, 0xd4, 0x9b, 0xc3, 0x25, 0xb1, 0xad, 0xb3, 0x55, 0x06, 0x54, 0xe6, 0x92, 0x81, 0x82, 0xcd, 0xd0, 0x26, 0x29, 0x89, 0xcc, 0x04, 0x00, 0x94, 0x90, 0xda, 0x51, 0xb9, 0x32, 0xf6, 0xa6, 0x11, 0x9d, 0x9a, 0xc5, 0x96, 0x84, 0x47, 0x29, 0xd3, 0x15, 0x64, 0x1d, 0xa0, 0x21, 0xf0, 0x1b, 0xba, 0x80, 0x14, 0x6a, 0xa5, 0xb6, 0xe3, 0x42, 0x6f, 0xfa, 0x94, 0x29, 0xfa, 0x62, 0xdf, 0x2e, 0xdf, 0x5c, 0x8a, 0x9b, 0x2d, 0xc5, 0x54, 0xc8, 0x5d, 0xdb, 0x38, 0x24, 0x2a, 0xaa, 0x09, 0x4b, 0x15, 0x9d, 0x0b, 0x74, 0x44, 0xd6, 0xb1, 0xa1, 0x04, 0x97, 0x31, 0x6e, 0xf3, 0xd7, 0x97, 0x7a, 0x53, 0xd4, 0x3b, 0xd4, 0xc0, 0x0c, 0xc5, 0x61, 0x8b, 0x1a, 0x90, 0x1d, 0x79, 0x40, 0xf0, 0xe0, 0xe6, 0xd2, 0x0a, 0x5c, 0x21, 0xc6, 0x7a, 0x3a, 0x56, 0x9f, 0xed, 0xe9, 0xe3, 0xee, 0x74, 0x3a, 0xfe, 0x96, 0xb5, 0xe7, 0x57, 0x3f, 0x4b, 0xba, 0x90, 0x98, 0x74, 0x2a, 0xe2, 0x75, 0xe7, 0xa3, 0xf1, 0x40, 0xb6, 0x9f, 0x9c, 0x58, 0x3a, 0xf8, 0xf6, 0xa3, 0x07, 0x04, 0xa7, 0xca, 0xf6, 0x14, 0x38, 0xd8, 0xa6, 0xb5, 0xae, 0x40, 0xb0, 0x42, 0x28, 0xa0, 0x0e, 0xa1, 0xc7, 0x42, 0x05, 0x93, 0x18, 0x0e, 0x95, 0xe0, 0x05, 0x12, 0xc2, 0xfe, 0xd2, 0x67, 0x5f, 0x5f, 0xd5, 0xd3, 0x76, 0xbe, 0x8f, 0xd7, 0x9f, 0x4e, 0xbb, 0xfc, 0xa5, 0x57, 0xd4, 0xe3, 0x7e, 0x6c, 0x3c, 0xd8, 0xb1, 0xfd, 0x94, 0x97, 0x09, 0x8e, 0xff, 0x94, 0x06, 0x4d, 0x4b, 0x6e, 0xdd, 0x70, 0xae, 0xf5, 0x70, 0x07, 0xc3, 0x00, 0xe4, 0x4f, 0x30, 0x0a, 0xbd, 0xb1, 0xd2, 0x0f, 0x0f, 0x87, 0x1e, 0xce, 0x21, 0xd1, 0xca, 0xa1, 0x6d, 0x46, 0x01, 0xb6, 0x8f, 0x59, 0x42, 0xe0, 0xab, 0x88, 0xea, 0x92, 0xcb, 0x09, 0x3f, 0x82, 0x72, 0xb2, 0xe5, 0x14, 0x23, 0x1a, 0x14, 0x5c, 0xba, 0xc0, 0xc1, 0xb5, 0x97, 0xdc, 0x92, 0x0b, 0x3a, 0x52, 0x14, 0x3c, 0x44, 0x13, 0x61, 0x04, 0x41, 0xb0, 0xd0, 0x84, 0x67, 0x50, 0x78, 0x36, 0x62, 0xc9, 0xec, 0x8b, 0xff, 0xcf, 0x14, 0x76, 0xd9, 0xff, 0x22, 0x91, 0xcb, 0x9f, 0x11, 0xf9, 0xe5, 0x99, 0xba, 0xc0, 0x7c, 0xb2, 0x12, 0x7f, 0x8b, 0x40, 0x8d, 0x1f, 0x00, 0x6f, 0x8f, 0xf1, 0x43, 0xbd, 0x10, 0x2b, 0x20, 0xd8, 0xa0, 0xbf, 0xab, 0xde, 0x63, 0x5a, 0xd2, 0x25, 0x3a, 0x01, 0xbc, 0x49, 0xa0, 0xd9, 0x97, 0xda, 0x8b, 0x24, 0x43, 0x88, 0x16, 0x82, 0x67, 0x3c, 0x6d, 0x40, 0x73, 0x6e, 0x24, 0x7a, 0xd1, 0x90, 0x49, 0xc2, 0xa3, 0xd0, 0xa0, 0x40, 0x10, 0xf1, 0xdb, 0x9c, 0x81, 0xf7, 0x66, 0x78, 0x9b, 0xda, 0xab, 0x26, 0x9a, 0x76, 0xbc, 0xe0, 0x59, 0xc8, 0xd8, 0x99, 0x27, 0xc1, 0x69, 0x51, 0x32, 0x5b, 0xb2, 0x2d, 0x73, 0x07, 0x1c, 0x88, 0xc9, 0xe2, 0xeb, 0x43, 0xba, 0xf8, 0xd1, 0xee, 0x93, 0x88, 0xe5, 0xa9, 0xe7, 0x6b, 0x43, 0x0b, 0xf0, 0xb1, 0x1e, 0x0f, 0x37, 0x75, 0xf9, 0x2b, 0x3d, 0xbb, 0xfa, 0xa2, 0x67, 0x07, 0x89, 0x7a, 0x60, 0x2a, 0xb3, 0x12, 0x3c, 0x65, 0x7a, 0xae, 0x70, 0x03, 0x8a, 0x60, 0x45, 0x57, 0xed, 0x3d, 0x14, 0xbb, 0x2d, 0x53, 0x6b, 0x07, 0x45, 0x5d, 0x25, 0xb2, 0x8c, 0x29, 0xa8, 0x62, 0x48, 0xee, 0x02, 0x6a, 0xcf, 0xa6, 0x9f, 0xf5, 0xc8, 0x24, 0x82, 0x12, 0x31, 0x4c, 0x8d, 0xb8, 0x00, 0xc2, 0xb2, 0xe1, 0x91, 0x79, 0x53, 0xe8, 0xf0, 0x02, 0x12, 0x3d, 0x28, 0xe3, 0x98, 0x8d, 0xf4, 0x89, 0x75, 0x74, 0xd9, 0xb8, 0xa9, 0x0d, 0x45, 0x17, 0x20, 0x32, 0x3a, 0x0d, 0xa6, 0x5c, 0x44, 0xea, 0x36, 0x70, 0xa1, 0xe7, 0xd5, 0x31, 0x89, 0x56, 0xb3, 0x39, 0xc0, 0x46, 0xeb, 0x38, 0x1d, 0xe0, 0xe0, 0x45, 0x9f, 0xd0, 0xf8, 0x06, 0x81, 0xb5, 0x75, 0x4c, 0x34, 0xbf, 0x4d, 0x68, 0xbd, 0x6a, 0x43, 0xb6, 0x23, 0x57, 0xea, 0x34, 0xab, 0x10, 0xd1, 0xb6, 0x86, 0x66, 0x35, 0xf2, 0xca, 0xa9, 0x11, 0x47, 0xf8, 0x7d, 0xaa, 0x4c, 0xa6, 0x28, 0x42, 0xe0, 0x06, 0x99, 0x94, 0xa6, 0xf6, 0xde, 0x28, 0x99, 0x0d, 0xa0, 0xa1, 0xb2, 0xc6, 0xd0, 0x00, 0x37, 0x47, 0x8d, 0xc0, 0x5a, 0x0e, 0x46, 0x36, 0x60, 0x90, 0x70, 0x3e, 0xed, 0xca, 0xa6, 0xd8, 0x16, 0xa3, 0x63, 0x1e, 0x65, 0x11, 0xe1, 0x07, 0xb2, 0x3c, 0x76, 0x8f, 0x1f, 0x55, 0x02, 0xaf, 0x74, 0x30, 0x63, 0xa6, 0xee, 0x1a, 0xe1, 0x6a, 0xb9, 0x24, 0x66, 0x2d, 0xa7, 0xbe, 0xd0, 0x73, 0x20, 0x05, 0x6e, 0xe3, 0xe8, 0x0a, 0x5d, 0xa9, 0x16, 0x89, 0xdf, 0xce, 0x27, 0x01, 0x29, 0x55, 0x67, 0x50, 0x12, 0x2c, 0x41, 0x15, 0x69, 0xce, 0x7c, 0x70, 0x16, 0xa5, 0x2d, 0xcb, 0xc4, 0x41, 0x82, 0xd9, 0x4f, 0xdb, 0xaa, 0x36, 0xe6, 0xcc, 0xbd, 0x65, 0x12, 0xf7, 0x89, 0xe7, 0x24, 0xf3, 0xbe, 0x7a, 0x86, 0x36, 0x5a, 0x54, 0x5b, 0x8b, 0xe6, 0x22, 0x9d, 0x8f, 0xdb, 0x2c, 0x74, 0xbd, 0x93, 0x30, 0x9a, 0xfa, 0x93, 0x1c, 0x1a, 0x15, 0x1a, 0x04, 0xaf, 0xa6, 0xa4, 0xa4, 0x43, 0xd7, 0x62, 0xd5, 0x79, 0x5b, 0x9e, 0x5b, 0x0f, 0x3f, 0x05, 0x90, 0x0b, 0x42, 0x50, 0xd1, 0x97, 0x69, 0x90, 0x69, 0x0e, 0x95, 0x67, 0xb4, 0x53, 0xc1, 0x37, 0x31, 0x39, 0x2b, 0x35, 0xe8, 0x3c, 0x84, 0x47, 0xc1, 0xe7, 0x4c, 0x03, 0x97, 0xd0, 0xcb, 0xd8, 0x60, 0xaa, 0xde, 0xe6, 0x88, 0x86, 0x52, 0x27, 0x3d, 0x0e, 0x8d, 0x5c, 0xc7, 0xe0, 0x21, 0x1a, 0x15, 0x77, 0xf4, 0xf7, 0x08, 0xb0, 0x3a, 0x04, 0x74, 0xc6, 0x3e, 0xe9, 0x12, 0x73, 0x6c, 0xaa, 0xc8, 0x69, 0x28, 0x50, 0x8c, 0xac, 0x4a, 0x81, 0x59, 0xa5, 0xe8, 0xc8, 0xd2, 0x91, 0x4b, 0xa9, 0xa1, 0x82, 0xc2, 0x29, 0x05, 0xd1, 0x72, 0xee, 0x7c, 0xc2, 0x12, 0x45, 0x4b, 0x0d, 0x4a, 0xb3, 0x68, 0x87, 0xa1, 0x41, 0x01, 0xaf, 0x5a, 0x2b, 0x86, 0xb2, 0x9f, 0x5b, 0xd0, 0x16, 0x02, 0x63, 0x1a, 0x9a, 0xb2, 0x12, 0x92, 0xe8, 0x0e, 0xba, 0x11, 0x2d, 0xa2, 0x22, 0x0f, 0xa0, 0x3b, 0x64, 0xf0, 0x9f, 0x53, 0x39, 0x35, 0x6b, 0xc5, 0x94, 0xd7, 0x5c, 0x00, 0x1c, 0xd8, 0x1a, 0xb6, 0x45, 0x07, 0x47, 0x2a, 0x51, 0x08, 0xa0, 0x5f, 0x6c, 0xe4, 0xce, 0x42, 0x58, 0x14, 0x5e, 0xa6, 0x53, 0x0b, 0xed, 0xb2, 0x8a, 0x60, 0x70, 0xd4, 0x16, 0xea, 0x9e, 0x2d, 0xe2, 0xe6, 0x05, 0xe2, 0x90, 0xe1, 0xef, 0x2a, 0xab, 0x2a, 0xe8, 0x9f, 0xa7, 0x63, 0x93, 0x92, 0x25, 0x3a, 0xd3, 0xc2, 0x60, 0x05, 0xb2, 0xa0, 0x62, 0x47, 0x48, 0x0b, 0x08, 0x35, 0xa1, 0x21, 0xda, 0x40, 0x7d, 0x3a, 0x4c, 0x70, 0x69, 0xc5, 0xea, 0x14, 0x29, 0xef, 0x04, 0x1d, 0x63, 0x42, 0x98, 0x23, 0x0b, 0x02, 0x66, 0xf5, 0x20, 0x69, 0x8e, 0xbc, 0x03, 0x98, 0xa6, 0x2c, 0x70, 0xa6, 0xc9, 0xe2, 0xc1, 0x3c, 0x06, 0x7a, 0x0f, 0xf3, 0x03, 0x59, 0xcd, 0x58, 0x06, 0x58, 0x01, 0x58, 0x52, 0x26, 0xcd, 0xcf, 0xb3, 0x7a, 0xfa, 0x6b, 0x16, 0x18, 0x80, 0xa6, 0x14, 0xb3, 0x72, 0x47, 0x78, 0x45, 0x4f, 0x95, 0x7d, 0x8e, 0xc8, 0x39, 0x5e, 0xc2, 0xd9, 0x00, 0x64, 0x48, 0x04, 0xb1, 0x61, 0x47, 0xb1, 0x21, 0xb0, 0xc8, 0x11, 0x64, 0x59, 0xa2, 0x97, 0x6c, 0x41, 0xeb, 0xef, 0xa3, 0x3c, 0xf3, 0x80, 0x93, 0x4a, 0xe5, 0xd8, 0x23, 0x69, 0xe9, 0x74, 0xd6, 0x0a, 0x02, 0x61, 0x65, 0x19, 0x4a, 0xb1, 0xa9, 0xe4, 0x4a, 0x4a, 0x93, 0x07, 0xb4, 0x6f, 0xc0, 0x4f, 0x24, 0x95, 0xaa, 0x2b, 0xa9, 0x54, 0x49, 0x69, 0xd8, 0xcf, 0xd1, 0x95, 0x29, 0xce, 0x72, 0xdb, 0x26, 0xca, 0x30, 0xb9, 0xd5, 0x10, 0xb3, 0x61, 0x3d, 0x64, 0xa0, 0x34, 0xc8, 0x1a, 0xd4, 0x0b, 0x66, 0x43, 0x45, 0x99, 0x85, 0x02, 0x4f, 0x65, 0x0a, 0x6c, 0x74, 0x86, 0x57, 0x63, 0xe9, 0xd8, 0x82, 0xc8, 0xd2, 0x70, 0x22, 0x6c, 0x10, 0x11, 0x80, 0x1b, 0x2d, 0x76, 0x09, 0x29, 0x3b, 0x19, 0xd0, 0x2c, 0xd2, 0xd7, 0x70, 0x0f, 0xb9, 0x45, 0xe7, 0x61, 0x02, 0xb9, 0x92, 0x88, 0x88, 0x8c, 0x53, 0x2d, 0x23, 0x08, 0x5e, 0xa6, 0x7a, 0xf6, 0x6b, 0x90, 0x88, 0x39, 0xc8, 0x98, 0xce, 0xb3, 0x81, 0x57, 0x90, 0x07, 0xc0, 0xc4, 0x38, 0xf0, 0x16, 0xac, 0xca, 0x90, 0xe8, 0xe7, 0x32, 0xa0, 0x8b, 0xe4, 0x09, 0x65, 0xcd, 0xa4, 0x06, 0xb8, 0x24, 0xb0, 0x11, 0xc0, 0x06, 0xbc, 0x36, 0x6c, 0x51, 0x14, 0x11, 0xaa, 0x9e, 0xe0, 0xa2, 0xa0, 0x83, 0x9d, 0x10, 0x8e, 0x35, 0x89, 0x04, 0xd0, 0x06, 0xf2, 0x2c, 0xc9, 0x08, 0x37, 0x38, 0xeb, 0x2c, 0x79, 0x2a, 0xba, 0x29, 0xb7, 0x82, 0x6d, 0x56, 0x55, 0xb2, 0xd5, 0x85, 0x44, 0x94, 0x91, 0x08, 0x59, 0xe0, 0x25, 0x9b, 0x40, 0x4f, 0x5c, 0x3b, 0x35, 0x9d, 0x28, 0x7c, 0x79, 0x3e, 0x8d, 0x74, 0xb9, 0xa8, 0x62, 0xab, 0x01, 0x3f, 0x04, 0x58, 0xc9, 0x15, 0xb1, 0x67, 0x44, 0xd8, 0x04, 0x32, 0x07, 0xac, 0x01, 0x78, 0x27, 0x67, 0xb2, 0xfb, 0x2c, 0x06, 0x12, 0x7a, 0x42, 0x93, 0x43, 0x64, 0xcd, 0x45, 0x40, 0x37, 0x20, 0x21, 0x88, 0xe2, 0x59, 0xb6, 0xd6, 0x69, 0xb0, 0x95, 0x80, 0x04, 0xf9, 0x35, 0x31, 0xf0, 0xff, 0xed, 0xea, 0x16, 0x6f, 0x2e, 0x09, 0x5e, 0x6e, 0x60, 0x0d, 0x92, 0x8a, 0x90, 0xe7, 0xe9, 0x73, 0x81, 0x04, 0x67, 0x16, 0x89, 0xf2, 0x8b, 0xc2, 0x28, 0x53, 0x6b, 0x69, 0x92, 0xa5, 0xb7, 0xc7, 0x9b, 0xc3, 0xed, 0xf1, 0x09, 0x07, 0x23, 0x29, 0x3a, 0x1e, 0x89, 0x96, 0x9c, 0x48, 0x94, 0xce, 0x28, 0x44, 0x5e, 0x20, 0xf1, 0x44, 0x8a, 0xca, 0x9b, 0x28, 0x92, 0x31, 0x63, 0x45, 0x2f, 0xf5, 0xc3, 0x4c, 0x44, 0x34, 0x56, 0x1c, 0x10, 0x16, 0x88, 0x87, 0x16, 0x28, 0x9c, 0xbe, 0xe8, 0xec, 0x8a, 0x37, 0x60, 0x8f, 0x1c, 0xcd, 0x85, 0xc5, 0xa0, 0x49, 0x8c, 0xd5, 0x68, 0xeb, 0x61, 0xab, 0x21, 0x9a, 0x01, 0xc6, 0x51, 0x6d, 0x59, 0x43, 0x95, 0x44, 0x63, 0x14, 0xd1, 0x47, 0x97, 0xc7, 0x87, 0x56, 0xdf, 0x3a, 0xb5, 0xe1, 0x8b, 0xc5, 0xa5, 0xd8, 0x3e, 0xfd, 0x30, 0xea, 0xc1, 0x87, 0x05, 0xa7, 0xd3, 0x5d, 0xfd, 0xfb, 0x6f, 0xf9, 0x61, 0x01, 0xd2, 0xdf, 0x45, 0xd4, 0x3d, 0xec, 0xa4, 0xf0, 0xea, 0xb9, 0xf2, 0x1e, 0xe8, 0xf7, 0x97, 0x54, 0x2a, 0x34, 0x84, 0x35, 0x30, 0x9c, 0x3e, 0xc2, 0xa1, 0xe3, 0x6d, 0x8e, 0x5e, 0x4e, 0x5a, 0xf4, 0x32, 0x0e, 0x22, 0x48, 0x9a, 0x54, 0xed, 0xd4, 0x12, 0x3d, 0x15, 0x98, 0xbf, 0xf1, 0x71, 0xc3, 0xfd, 0xbe, 0xd4, 0x86, 0x96, 0xa6, 0xfc, 0xae, 0xa7, 0x78, 0x4f }; struct uint8_block chunk_block2 = { 1484, gzip_chunk2 }; uint8_t gzip_chunk3[] = { 0x3d, 0x4b, 0x79, 0x92, 0x04, 0x7f, 0xca, 0x4c, 0x44, 0x3b, 0x4f, 0x74, 0x02, 0xd9, 0x77, 0x3a, 0x9c, 0xe2, 0xf5, 0xf6, 0xc1, 0x5f, 0x5a, 0x1a, 0x75, 0xbe, 0xfb, 0xc8, 0x10, 0x2f, 0xfb, 0xa9, 0x67, 0xbd, 0xfb, 0xb0, 0xeb, 0x1f, 0x46, 0x3d, 0x7b, 0x75, 0x57, 0x8f, 0x95, 0x3e, 0x98, 0xfa, 0xf7, 0xff, 0x01, 0xa9, 0xdf, 0x53, 0x30, 0xd6, 0x29, 0x00, 0x00 }; struct uint8_block chunk_block3 = { 59, gzip_chunk3 }; pubnub_init(pbp, "demo", "demo"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url("/v2/presence/sub-key/demo?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\n" "Content-Length: 197\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_global_here_now(pbp), equals(PNR_OK)); attest(pubnub_get(pbp), streqs("{\"status\":200,\"message\":\"OK\",\"service\":\"Presence\"," "\"payload\":{channels:{\"ch1\":{\"uuids\":[uuid1,uuid2," "uuid3],\"occupancy\":3},\"ch2\":{\"uuids\":[uuid3,uuid4]," "\"occupancy\":2},\"ch3\":{\"uuids\":[uuid7],\"occupancy\":1}" ",\"ch4\":{\"uuids\":[],\"occupancy\":0},\"ch5\":{\"uuids\":[" "tricycle, mother, swоrd], " "\"occupancy\":3}},\"total_channels\":5,\"total_occupancy\":" "12}}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/v2/presence/sub-key/demo?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\n" "Content-Encoding: gzip\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "c0d\r\n", &chunk_block1); incoming("\r\n5cc\r\n", &chunk_block2); incoming("\r\n3b\r\n", &chunk_block3); incoming("\r\n0\r\n", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_global_here_now(pbp), equals(PNR_STARTED)); attest(pubnub_global_here_now(pbp), equals(PNR_IN_PROGRESS)); /* 'push' until finished */ attest(pbnc_fsm(pbp), equals(0)); attest(pbnc_fsm(pbp), equals(0)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_OK)); attest( pubnub_get(pbp), streqs( "{\"status\": 200, \"message\": \"OK\", \"payload\": " "{\"channels\": {\"ripan-hallonet-sensors\": {\"occupancy\": 1, " "\"uuids\": [\"872edf50-bc2e-4b8a-afa1-9b59337a5938\"]}, " "\"Proxy_Check_Online_3\": {\"occupancy\": 1, \"uuids\": " "[\"27.74.130.107\"]}, \"adminportal\": {\"occupancy\": 2, " "\"uuids\": [\"d20f27b1-e66f-4247-a9b4-264432e86a6b\", " "\"10e68d24-0243-484c-8960-2745cbe1e4cb\"]}, " "\"Shield_Proxy_Check_Online2\": {\"occupancy\": 150, \"uuids\": " "[\"124.105.121.168\", \"110.54.237.164\", \"49.147.193.93\", " "\"113.161.55.100\", \"46.36.65.210\", \"61.230.8.134\", " "\"112.203.148.75\", \"120.29.109.119\", \"36.236.21.126\", " "\"190.128.164.182\", \"27.247.130.198\", \"180.191.87.114\", " "\"37.186.42.64\", \"119.93.3.144\", \"116.98.166.96\", " "\"36.233.101.191\", \"203.223.190.120\", \"94.59.105.19\", " "\"58.186.197.134\", \"116.103.108.180\", \"157.42.142.181\", " "\"122.3.39.211\", \"49.148.82.61\", \"175.212.79.101\", " "\"106.1.39.214\", \"122.116.225.76\", \"112.200.206.156\", " "\"195.74.224.132\", \"192.228.175.13\", \"112.198.103.175\", " "\"119.93.251.171\", \"84.95.232.171\", \"103.5.1.130\", " "\"49.145.111.128\", \"88.152.11.108\", \"122.118.113.171\", " "\"115.75.176.149\", \"61.58.185.188\", \"36.230.35.157\", " "\"116.73.196.128\", \"1.168.235.43\", \"112.204.192.160\", " "\"122.2.2.82\", \"110.54.236.21\", \"89.44.219.209\", " "\"124.218.3.139\", \"175.158.216.8\", \"49.150.144.4\", " "\"24.55.29.95\", \"175.138.51.98\", \"14.191.38.227\", " "\"141.237.206.22\", \"210.14.20.141\", \"80.195.130.215\", " "\"124.105.59.59\", \"112.210.170.50\", \"42.113.115.85\", " "\"49.159.60.50\", \"117.5.143.136\", \"74.96.121.172\", " "\"112.198.76.48\", \"183.88.2.123\", \"188.51.32.230\", " "\"111.246.152.41\", \"36.239.5.235\", \"60.50.141.170\", " "\"37.210.221.192\", \"103.107.253.21\", \"60.54.102.90\", " "\"36.77.153.130\", \"123.19.132.135\", \"89.210.97.166\", " "\"103.100.137.14\", \"2.50.134.250\", \"20.20.20.12\", " "\"117.2.85.215\", \"42.113.199.181\", \"2.51.120.235\", " "\"125.230.143.195\", \"111.249.142.245\", \"91.154.147.79\", " "\"49.149.79.61\", \"204.210.112.99\", \"115.73.204.227\", " "\"42.61.247.152\", \"218.111.17.141\", \"175.140.218.141\", " "\"49.144.204.206\", \"120.29.112.54\", \"171.98.135.43\", " "\"113.160.148.136\", \"14.167.123.54\", \"220.136.166.148\", " "\"115.78.94.12\", \"80.69.52.8\", \"113.174.79.114\", " "\"31.167.28.6\", \"37.104.170.14\", \"113.190.58.53\", " "\"175.180.108.173\", \"1.52.33.98\", \"180.190.183.65\", " "\"203.177.67.222\", \"14.231.46.148\", \"77.31.208.165\", " "\"58.187.117.235\", \"60.50.64.155\", \"178.59.63.21\", " "\"119.94.246.152\", \"113.188.244.76\", \"77.69.247.229\", " "\"219.74.81.16\", \"88.69.184.178\", \"122.2.248.94\", " "\"83.110.227.99\", \"112.198.243.105\", \"121.54.54.43\", " "\"1.53.33.124\", \"180.191.130.13\", \"180.190.78.41\", " "\"124.107.126.101\", \"42.119.183.166\", \"123.26.62.36\", " "\"14.176.202.239\", \"37.106.87.156\", \"180.191.119.71\", " "\"95.235.77.103\", \"31.146.212.78\", \"14.174.109.180\", " "\"51.218.186.86\", \"45.46.5.49\", \"60.50.30.176\", " "\"188.50.236.115\", \"27.76.199.154\", \"2.49.41.238\", " "\"110.54.242.122\", \"49.145.103.189\", \"14.173.101.131\", " "\"101.51.135.82\", \"78.100.181.211\", \"125.161.130.53\", " "\"120.29.79.44\", \"36.234.215.106\", \"94.200.33.34\", " "\"14.229.179.29\", \"111.253.91.112\", \"113.254.192.231\", " "\"78.93.246.65\", \"112.206.68.198\", \"94.77.228.34\"]}, " "\"34547ead-0423-4983-a7d1-11cbc554ffa4\": {\"occupancy\": 1, " "\"uuids\": [\"34547ead-0423-4983-a7d1-11cbc554ffa4\"]}, \"HNG\": " "{\"occupancy\": 1, \"uuids\": " "[\"c0f7e1bb-2e2e-4105-b0a8-cfa828b3b0eb\"]}, \"DLG\": " "{\"occupancy\": 1, \"uuids\": " "[\"aab9bb83-42a9-4336-a549-c219d665852b\"]}, " "\"fasci_geckodeSuscriber\": {\"occupancy\": 1, \"uuids\": " "[\"pn-f8c944f9-dc6d-4cef-875d-58832267facf\"]}, " "\"e60fd1b1f9489513a044f24f9e8a166820ebaf8c|sensor_pod-454916|user-" "755668\": {\"occupancy\": 6, \"uuids\": " "[\"pn-a40f7f29-b74c-4b29-94b6-6b69d65d1de9\", " "\"pn-86df1b4a-3320-4158-914e-3a9a05273f82\", " "\"pn-ea7115ed-d8af-449a-8e11-8dd680a1b0d0\", " "\"pn-bac9ffc3-cf16-460f-a60a-ee3aff5f2ab9\", " "\"pn-714a7de3-3d49-41d8-8b0c-6252f5e9afc9\", " "\"pn-7df15a84-dd9d-47e3-83f1-0fd3740cda51\"]}, " "\"__notifications__47738\": {\"occupancy\": 1, \"uuids\": " "[\"90efdade-954f-4796-a8f4-e72842fe1cab\"]}, \"mymaps\": " "{\"occupancy\": 1, \"uuids\": " "[\"4f423cfc-286c-4cf4-8c2b-cc6c25074b31\"]}, " "\"CoinNoti_Binance\": {\"occupancy\": 1, \"uuids\": " "[\"pn-72e185b7-69ce-4d13-b41e-2040f8cc79e8\"]}, \"my_channel\": " "{\"occupancy\": 14, \"uuids\": " "[\"pn-E854CD01-3A29-4CB9-8A24-CFB9F35AED20\", " "\"pn-80736E22-05D6-4F62-A2AF-5FD2D408F56A\", " "\"pn-DE7F81F9-C9A5-4537-962D-7DA996575877\", " "\"pn-90C900A3-A290-486D-A992-BD7D0E3036EE\", " "\"pn-D15433B6-65B9-41AF-A99D-E346A6D8E182\", " "\"pn-4ECA5927-3E72-4C44-89A5-7E5056CF8113\", " "\"pn-2E955FBA-90FA-4317-A2A1-29827B32CBD2\", " "\"pn-393259F4-1DD4-4D4C-A6AA-84CE507D2E8E\", " "\"pn-d87d4ebd-e974-4371-a52d-48b78c314a82\", " "\"pn-17886F1B-3C33-4065-9799-A3FF22C7BE18\", " "\"pn-36E5669B-DFFD-4F2E-A28C-EF8EF1CE44CC\", " "\"pn-98743f84-0d79-4585-abf2-0313a768ccb9\", " "\"pn-C29278DA-9DA5-4926-B927-ADBB223DB296\", " "\"pn-A31B3215-E8B6-40B2-B120-61BCEB7489D2\"]}, " "\"jm_ae571630-9194-45b8-b159-9b64de9c7c8a_uplink\": " "{\"occupancy\": 1, \"uuids\": " "[\"6e84858b-e07a-4ffd-9787-56a5437185f7\"]}, \"pgday\": " "{\"occupancy\": 1, \"uuids\": " "[\"7cf35f2c-afb3-4a32-a24a-f584c1d02af9\"]}, " "\"sisvi_geckodeSuscriber\": {\"occupancy\": 1, \"uuids\": " "[\"pn-f8c944f9-dc6d-4cef-875d-58832267facf\"]}, \"a7bdb71a\": " "{\"occupancy\": 2, \"uuids\": " "[\"77a2ccd1-78ad-419e-b251-019d6b9a5a0b\", " "\"66e4b3a6-c647-4166-a320-76a20f0313f9\"]}, \"puravida\": " "{\"occupancy\": 1, \"uuids\": " "[\"0400b6ea-d5d4-421e-8d25-e062cedee30e\"]}, \"BAY\": " "{\"occupancy\": 1, \"uuids\": " "[\"84b2393a-93a8-4a33-8e91-87b48db33bd4\"]}, " "\"SENSEMO-OI0FX9N3\": {\"occupancy\": 2, \"uuids\": " "[\"b227eada-216f-4021-b77f-6df6c69d6c6c\", " "\"42b53d89-0c8b-4105-96d6-d588c22ecf2a\"]}, " "\"slim_geckodeSuscriber\": {\"occupancy\": 1, \"uuids\": " "[\"pn-f8c944f9-dc6d-4cef-875d-58832267facf\"]}, \"chat\": " "{\"occupancy\": 1, \"uuids\": " "[\"f7e0a7bf-7ccd-4e58-a18f-4ffd288c992f\"]}, \"Youtube_CM_VS4\": " "{\"occupancy\": 18, \"uuids\": [\"37.150.146.135-YGERCDlDr0\", " "\"91.192.44.33-h7inBdhIO8\", \"109.173.92.236-yyanZt9JjB\", " "\"5.254.65.220-XJeTsi7BJd\", \"77.111.244.68-Iun9ywA91u\", " "\"93.84.141.230-tvceiijjL0\", \"95.97.235.215-KCg83f1R84\", " "\"213.230.102.11-92ADwcJL9F\", \"185.59.58.77-1gbNOL1VPp\", " "\"77.111.244.50-mEcoc41ePn\", \"188.113.156.146-9ZfhaRDPG4\", " "\"78.36.204.66-oQ6qWl2I4r\", \"109.169.174.71-NO7HZmaujt\", " "\"109.200.159.26-0z4LpzUdNI\", \"188.113.156.146-ZwpAjOIHBq\", " "\"95.135.255.83-e6Pocjkc99\", \"109.173.92.236-IdgipOXRwX\", " "\"141.101.8.78-tFZfa9TYnW\"]}, " "\"jm_d2c0aad1-a5dd-4fd9-b614-c8e44197a22c_uplink\": " "{\"occupancy\": 1, \"uuids\": " "[\"ae74ed7c-3deb-4344-97d6-b7f5bbd70974\"]}, \"hello_world\": " "{\"occupancy\": 2, \"uuids\": " "[\"pn-78094928-e577-4dfa-bdb5-eb94552537fd\", " "\"72ead2d9-c054-624f-9628-05b4a08bd261\"]}, \"beakon_test\": " "{\"occupancy\": 1, \"uuids\": [\"DANIELLE\"]}, " "\"channel_450_4_86a9106ae65537651a8e456835b316a\": " "{\"occupancy\": 1, \"uuids\": " "[\"de934289-127f-46bc-bc97-cdcdcbb42ca3\"]}, \"ORQ\": " "{\"occupancy\": 1, \"uuids\": " "[\"795246cb-7ee1-4e5c-a2c7-70212ae58829\"]}, \"TLY\": " "{\"occupancy\": 1, \"uuids\": " "[\"b865d2a3-530b-48ef-955d-a5cef83ec8e7\"]}, " "\"pubnub-html5-notification-demo\": {\"occupancy\": 1, \"uuids\": " "[\"94c635cd-7b5e-4c84-bb1c-1ed7b3f1a37d\"]}, " "\"3a21965c-18a6-4e8b-9919-4ed9db9ee0d0\": {\"occupancy\": 1, " "\"uuids\": [\"3a21965c-18a6-4e8b-9919-4ed9db9ee0d0\"]}, \"MCS\": " "{\"occupancy\": 1, \"uuids\": " "[\"d6dd5e62-6f00-46c6-be49-7cfc4af19dd3\"]}, \"ARG\": " "{\"occupancy\": 1, \"uuids\": " "[\"e91239c2-a6d3-4dfa-a09c-a3ecdfded71e\"]}, \"geckode_twitts\": " "{\"occupancy\": 1, \"uuids\": " "[\"pn-f8c944f9-dc6d-4cef-875d-58832267facf\"]}, " "\"Shield_Proxy_Check_Online\": {\"occupancy\": 2, \"uuids\": " "[\"14.184.255.135\", \"49.146.38.83\"]}, \"10chat-demo\": " "{\"occupancy\": 1, \"uuids\": " "[\"6f444ecb-30d0-452c-9e7c-50b2381cbb6b\"]}, " "\"Shield_Proxy_Get_Analytics\": {\"occupancy\": 3, \"uuids\": " "[\"49.145.162.113-1000034174206736\", " "\"49.146.38.83-1000021295333234\", " "\"49.145.162.113-1000020741589926\"]}, " "\"channel_1_1_d1e7b7cb7b79372fcbaa3467b77904fd\": {\"occupancy\": " "1, \"uuids\": [\"6cddad15-c94d-4bc9-9f18-5a06a899c8d8\"]}, " "\"jm_ae571630-9194-45b8-b159-9b64de9c7c8a_dnlink\": " "{\"occupancy\": 2, \"uuids\": " "[\"ae571630-9194-45b8-b159-9b64de9c7c8a\", " "\"6e84858b-e07a-4ffd-9787-56a5437185f7\"]}, \"get_message_save\": " "{\"occupancy\": 3, \"uuids\": " "[\"pn-5154e88a-4135-4b5d-b1f1-2481b299a62f\", " "\"pn-b2fe5222-9cb3-4d70-bd28-06cc883f50f2\", " "\"pn-f1f470d8-09c4-4891-8636-fb6fc0773617\"]}, \"global\": " "{\"occupancy\": 2, \"uuids\": " "[\"3a21965c-18a6-4e8b-9919-4ed9db9ee0d0\", " "\"34547ead-0423-4983-a7d1-11cbc554ffa4\"]}, \"awesomeChannel\": " "{\"occupancy\": 34, \"uuids\": " "[\"pn-35c8aa3c-d98d-4cce-9cd9-e877880406d9\", " "\"pn-bd4e24ec-3402-4adf-9c5e-3a92b1931a97\", " "\"pn-15a0c50a-85dc-4ca8-9357-6a32e8a7c578\", " "\"pn-21e1c6e4-37a0-4f49-80e7-2d79f715944a\", " "\"pn-7a7c8b2d-91df-4aba-856b-afefe7c1e7e8\", " "\"pn-11a6ff79-a0e0-431d-b8be-2ba19905fcbb\", " "\"pn-4532c5f1-3c40-49ad-a491-60fc4550b9e9\", " "\"pn-c5d6faa7-82ae-4835-83a9-83e23716c255\", " "\"pn-3eadfcdb-6603-4a80-8602-04c17de6002f\", " "\"pn-39bbe752-6635-472f-8976-7bc2b010cc88\", " "\"pn-e6acc086-2010-4522-88e8-3211e6ed401b\", " "\"pn-ea688c72-c58b-4c9f-be4c-3ebb3270c863\", " "\"pn-c58068e0-9a34-4fee-84cb-c9e0cb4898f1\", " "\"pn-4bfa5de7-3fef-4454-9203-be86ca78a4b4\", " "\"pn-a04a9878-3073-4886-994a-8b4dacaf3d24\", " "\"pn-cbc70db9-633d-4579-8305-9428dd05f773\", " "\"pn-2a1fbfdd-d47d-493e-9443-d7bcf946ec83\", " "\"pn-bc312f18-9748-439f-b7b4-08673cbf6612\", " "\"pn-018bebfa-3f90-43bf-890b-6a076bb1d0d6\", " "\"pn-47c3a162-50ad-4652-8122-ca68e2e3da5a\", " "\"pn-9dc24a3d-2f1c-4e05-a0cc-b1427f485495\", " "\"pn-fd64bad9-e149-4c99-8092-c89c804e2dfc\", " "\"pn-775f2d81-8597-4a30-8f56-17d7de22b405\", " "\"pn-f8bc2e3d-d589-4075-8320-c8cac6e0d995\", " "\"pn-31da0d8d-4aff-4990-91b9-406d4168a2d9\", " "\"pn-7233ca4a-8b66-4661-88ee-ce58f3b7dbba\", " "\"pn-48fb48a9-124e-46b2-b8b9-43335d7606f7\", " "\"pn-5cfe9ac5-2f18-4ff2-ab64-69e3414a0bd3\", " "\"pn-a750e56e-b219-4500-bd5e-feea64076cba\", " "\"pn-f6b9e508-6f33-41e8-b357-573fc27f82be\", " "\"pn-779290bc-1b4a-4889-ac83-0fbf963c7652\", " "\"pn-f4d20bb8-5bf0-4bdf-bc35-9f46b1d19e46\", " "\"pn-35307117-f286-459c-b2a2-b7676dbbaa71\", " "\"pn-96f63e08-679b-4a8b-8121-36b5f104732a\"]}, " "\"__notifications__48300\": {\"occupancy\": 1, \"uuids\": " "[\"3e5d4095-903f-4aa1-8143-ed4d0db75c78\"]}, " "\"jm_b1095c9a-f7ac-49bf-b193-c6674be717b7_dnlink\": " "{\"occupancy\": 1, \"uuids\": " "[\"ae74ed7c-3deb-4344-97d6-b7f5bbd70974\"]}, \"BSG\": " "{\"occupancy\": 1, \"uuids\": " "[\"057acdc2-8b68-460b-b2d2-fb0422bffbcf\"]}, \"psmopschat\": " "{\"occupancy\": 1, \"uuids\": " "[\"ba70a94a-71bd-46e4-8192-1ba385a1b557\"]}, " "\"dev.1a42c0b8b110441aa38d4c7d85ebfca5\": {\"occupancy\": 1, " "\"uuids\": [\"15456471-2bf5-43b2-a9cd-f5dcc8eaaadd\"]}, " "\"SENSEMO-M73F0BB0\": {\"occupancy\": 1, \"uuids\": " "[\"42b53d89-0c8b-4105-96d6-d588c22ecf2a\"]}, " "\"CoinNoti_Bittrex\": {\"occupancy\": 1, \"uuids\": " "[\"pn-72e185b7-69ce-4d13-b41e-2040f8cc79e8\"]}, " "\"58f7aead8ead0e803885308d\": {\"occupancy\": 1, \"uuids\": " "[\"c5e650c8-3d44-4304-b26a-a79db25be6d3\"]}, " "\"jm_b1095c9a-f7ac-49bf-b193-c6674be717b7_uplink\": " "{\"occupancy\": 1, \"uuids\": " "[\"ae74ed7c-3deb-4344-97d6-b7f5bbd70974\"]}, " "\"undefined_geckodeSuscriber\": {\"occupancy\": 1, \"uuids\": " "[\"pn-f8c944f9-dc6d-4cef-875d-58832267facf\"]}, " "\"jm_d2c0aad1-a5dd-4fd9-b614-c8e44197a22c_dnlink\": " "{\"occupancy\": 2, \"uuids\": " "[\"d2c0aad1-a5dd-4fd9-b614-c8e44197a22c\", " "\"ae74ed7c-3deb-4344-97d6-b7f5bbd70974\"]}}, \"total_channels\": " "53, \"total_occupancy\": 282}, \"service\": \"Presence\"}")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); } Ensure(single_context_pubnub, gzip_bad_compression_format) { uint8_t gzip_body[] = { 0x1f, 0x8b, 0x08, 0x00, 0x61, 0xb3, 0xe4, 0x5a, 0x02, 0x03, 0x8b, 0x8e, 0x2e, 0xc8, 0xcc, 0x4b, 0xd5, 0x49, 0xae, 0x2c, 0x28, 0x4a, 0x2d, 0x2e, 0xd6, 0x29, 0x48, 0xcc, 0xc9, 0x8d, 0xd5, 0x51, 0x32, 0x34, 0x35, 0x34, 0x33, 0x30, 0x34, 0xb1, 0x34, 0xb7, 0xb0, 0x34, 0x32, 0x35, 0x36, 0x32, 0x36, 0x31, 0x37, 0x54, 0x8a, 0x05, 0x00, 0x1b, 0x37, 0xa9, 0x34, 0x2b, 0x00, 0x00, 0x00 }; struct uint8_block body_block = { 63, gzip_body }; uint8_t gzip_body_garbage[] = { 0x1f, 0x8b, 0x08, 0x00, 0x61, 0xb3, 0xe4, 0x5a, 0x02, 0x03, 0x89, 0x5e, 0x1e, 0x18, 0x1c, 0x1b, 0x15, 0x19, 0x2e, 0x0c, 0x88, 0xfa, 0xfd, 0xee, 0xd6, 0xd9, 0x98, 0x3c, 0x29, 0xfd, 0xd5, 0x51, 0x32, 0x34, 0x35, 0x34, 0x33, 0x30, 0x34, 0xb1, 0x34, 0xb7, 0xb0, 0x34, 0x32, 0x35, 0x36, 0x32, 0x36, 0x31, 0x37, 0x54, 0x8a, 0x05, 0x00, 0x1b, 0x37, 0xa9, 0x34, 0x2b, 0x00, 0x00, 0x00 }; struct uint8_block body_garbage_block = { 63, gzip_body_garbage }; uint8_t extra_byte = 0x01; struct uint8_block extra_byte_block = { 1, &extra_byte }; pubnub_init(pbp, "looking-glass", "looking-glass"); expect_have_dns_for_pubnub_origin(); expect_outgoing_with_url( "/subscribe/looking-glass/island/0/0?pnsdk=unit-test-0.1"); incoming("HTTP/1.1 200\r\nContent-Length: " "26\r\n\r\n[[],\"1516014978925123457\"]", NULL); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_OK)); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925123457?pnsdk=unit-test-0.1"); /* Changing 'gzip' format byte into something else */ gzip_body[1]++; incoming("HTTP/1.1 200\r\n" "Content-Length: 63\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_BAD_COMPRESSION_FORMAT)); gzip_body[1] = 0x8b; /* Changing 'deflate' algoritam byte into something else */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925123457?pnsdk=unit-test-0.1"); gzip_body[2]--; body_block.size = sizeof gzip_body; incoming("HTTP/1.1 200\r\n" "Content-Length: 63\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_BAD_COMPRESSION_FORMAT)); gzip_body[2]++; /* Changing 'flags' byte to defer 0(expected by 'pubnub gzip' format: no filename, nor extras in the compressed block) */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925123457?pnsdk=unit-test-0.1"); gzip_body[3]++; body_block.size = sizeof gzip_body; incoming("HTTP/1.1 200\r\n" "Content-Length: 63\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_BAD_COMPRESSION_FORMAT)); gzip_body[3]--; /* Receiving shorter message than it should be */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925123457?pnsdk=unit-test-0.1"); body_block.size = sizeof gzip_body - 1; incoming("HTTP/1.1 200\r\n" "Content-Length: 62\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_BAD_COMPRESSION_FORMAT)); /* Receiving longer message than it should be */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925123457?pnsdk=unit-test-0.1"); body_block.size = sizeof gzip_body; incoming("HTTP/1.1 200\r\n" "Content-Length: 64\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); incoming(NULL, &extra_byte_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_STARTED)); attest(pbnc_fsm(pbp), equals(0)); attest(pbp->core.last_result, equals(PNR_BAD_COMPRESSION_FORMAT)); /* Changing 'isize'(size of decompressed block) value byte into smaller * value */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925123457?pnsdk=unit-test-0.1"); gzip_body[sizeof gzip_body - 4]--; body_block.size = sizeof gzip_body; incoming("HTTP/1.1 200\r\n" "Content-Length: 63\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_BAD_COMPRESSION_FORMAT)); gzip_body[sizeof gzip_body - 4]++; /* Changing 'isize'(size of decompressed block) value byte into greater * value */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925123457?pnsdk=unit-test-0.1"); gzip_body[sizeof gzip_body - 4]++; body_block.size = sizeof gzip_body; incoming("HTTP/1.1 200\r\n" "Content-Length: 63\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_BAD_COMPRESSION_FORMAT)); gzip_body[sizeof gzip_body - 4]--; /* Contaminated content */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925123457?pnsdk=unit-test-0.1"); gzip_body[30]--; gzip_body[32]--; gzip_body[34]--; gzip_body[38]++; body_block.size = sizeof gzip_body; incoming("HTTP/1.1 200\r\n" "Content-Length: 63\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); /* Decompression went through, but result is also contaminated */ attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_FORMAT_ERROR)); gzip_body[30]++; gzip_body[32]++; gzip_body[34]++; gzip_body[38]--; /* Returning to all correct(initial) parameters in the compressed block */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925123457?pnsdk=unit-test-0.1"); body_block.size = sizeof gzip_body; incoming("HTTP/1.1 200\r\n" "Content-Length: 63\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_OK)); attest(pubnub_last_time_token(pbp), streqs("1516014978925323471")); attest(pubnub_get(pbp), streqs("pine")); attest(pubnub_get(pbp), streqs("cypress")); attest(pubnub_get(pbp), streqs("palm")); attest(pubnub_get(pbp), equals(NULL)); attest(pubnub_get_channel(pbp), streqs(NULL)); attest(pubnub_last_http_code(pbp), equals(200)); /* Receiving gzip garbage block */ expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0)); expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0)); expect_outgoing_with_url("/subscribe/looking-glass/island/0/" "1516014978925323471?pnsdk=unit-test-0.1"); body_block.size = sizeof gzip_body; incoming("HTTP/1.1 200\r\n" "Content-Length: 63\r\n" "Content-Encoding: gzip\r\n" "\r\n", &body_garbage_block); expect(pbntf_lost_socket, when(pb, equals(pbp))); expect(pbntf_trans_outcome, when(pb, equals(pbp))); attest(pubnub_subscribe(pbp, "island", NULL), equals(PNR_BAD_COMPRESSION_FORMAT)); } /* Verify ASSERT gets fired */ Ensure(single_context_pubnub, illegal_context_fires_assert) { #if PUBNUB_USE_ADVANCED_HISTORY pubnub_chamebl_t o_msg[1]; size_t io_count; struct pubnub_chan_msg_count chan_msg_counters[1]; int count; #endif pubnub_assert_set_handler((pubnub_assert_handler_t)test_assert_handler); expect_assert_in(pubnub_init(NULL, "k", "u"), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_publish(NULL, "x", "0"), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_last_publish_result(NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_history(NULL, "ch", 22, true), "pubnub_coreapi.c"); expect_assert_in(pubnub_last_time_token(NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_subscribe(NULL, "x", NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_leave(NULL, "x", NULL), "pubnub_coreapi.c"); expect_assert_in(pubnub_cancel(NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_set_uuid(NULL, ""), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_set_uuid(pbp, "50fb7a0b-1688-45b9-9f27-ea83308464d8-ab3817df-07eb-446a-b990-c3b62a31706f"), "pubnub_ccore_pubsub.c"); expect_assert_in(pubnub_uuid_get(NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_set_auth(NULL, ""), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_auth_get(NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_last_http_code(NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_get(NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_get_channel(NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_set_state(NULL, "y", "group", NULL, "{}"), "pubnub_coreapi.c"); expect_assert_in(pubnub_state_get(NULL, "y", "group", NULL), "pubnub_coreapi.c"); expect_assert_in(pubnub_here_now(NULL, "ch", "ch_group"), "pubnub_coreapi.c"); expect_assert_in(pubnub_global_here_now(NULL), "pubnub_coreapi.c"); expect_assert_in(pubnub_heartbeat(NULL, "25", "[37,0Rh-]"), "pubnub_coreapi.c"); expect_assert_in(pubnub_where_now(NULL, "uuid"), "pubnub_coreapi.c"); expect_assert_in(pubnub_where_now(pbp, NULL), "pubnub_ccore.c"); expect_assert_in(pubnub_add_channel_to_group(NULL, "ch", "group"), "pubnub_coreapi.c"); expect_assert_in(pubnub_add_channel_to_group(pbp, NULL, "group"), "pubnub_ccore.c"); expect_assert_in(pubnub_add_channel_to_group(pbp, "ch", NULL), "pubnub_ccore.c"); expect_assert_in(pubnub_remove_channel_from_group(NULL, "ch", "group"), "pubnub_coreapi.c"); expect_assert_in(pubnub_remove_channel_from_group(pbp, NULL, "group"), "pubnub_ccore.c"); expect_assert_in(pubnub_remove_channel_from_group(pbp, "ch", NULL), "pubnub_ccore.c"); expect_assert_in(pubnub_remove_channel_group(NULL, "group"), "pubnub_coreapi.c"); expect_assert_in(pubnub_remove_channel_group(pbp, NULL), "pubnub_ccore.c"); expect_assert_in(pubnub_list_channel_group(NULL, "group"), "pubnub_coreapi.c"); expect_assert_in(pubnub_list_channel_group(pbp, NULL), "pubnub_ccore.c"); expect_assert_in(pubnub_subscribe(NULL, "%22cheesy%22", "[milk, meat]"), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_origin_set(NULL, "origin_server"), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_get_origin(NULL), "pubnub_pubsubapi.c"); expect_assert_in(pubnub_free((pubnub_t*)((char*)pbp + 10000)), "pubnub_alloc_static.c"); #if PUBNUB_USE_ADVANCED_HISTORY expect_assert_in(pubnub_get_error_message(NULL, o_msg), "pubnub_advanced_history.c"); expect_assert_in(pubnub_get_chan_msg_counts_size(NULL), "pubnub_advanced_history.c"); expect_assert_in(pubnub_message_counts(NULL, "ch", "12345"), "pubnub_advanced_history.c"); expect_assert_in(pubnub_message_counts(pbp, NULL, "12345"), "pubnub_advanced_history.c"); expect_assert_in(pubnub_message_counts(pbp, "ch", NULL), "pubnub_advanced_history.c"); expect_assert_in(pubnub_get_chan_msg_counts(NULL, &io_count, chan_msg_counters), "pubnub_advanced_history.c"); expect_assert_in(pubnub_get_chan_msg_counts(pbp, NULL, chan_msg_counters), "pubnub_advanced_history.c"); expect_assert_in(pubnub_get_chan_msg_counts(pbp, &io_count, NULL), "pubnub_advanced_history.c"); expect_assert_in(pubnub_get_message_counts(NULL, "ch", &count), "pubnub_advanced_history.c"); expect_assert_in(pubnub_get_message_counts(pbp, NULL, &count), "pubnub_advanced_history.c"); expect_assert_in(pubnub_get_message_counts(pbp, "ch", NULL), "pubnub_advanced_history.c"); #endif /* -- ADVANCED HISTORY message_counts -- */ } #if 0 int main(int argc, char *argv[]) { TestSuite *suite = create_test_suite(); add_test_with_context(suite, single_context_pubnub, time_in_progress); run_test_suite(suite, create_text_reporter()); } #endif
46.328778
152
0.612302
[ "object" ]
3d18345b1df8d8c8ad13b68af35fc390dab77cce
1,543
h
C
algorithms/hard/1755. Closest Subsequence Sum.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/hard/1755. Closest Subsequence Sum.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/hard/1755. Closest Subsequence Sum.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
// 1755. Closest Subsequence Sum // https://leetcode.com/problems/closest-subsequence-sum/ // Runtime: 676 ms, faster than 69.41% of C++ online submissions for Closest Subsequence Sum. // Memory Usage: 61.5 MB, less than 60.26% of C++ online submissions for Closest Subsequence Sum. class Solution { public: int minAbsDifference(vector<int>& nums, int goal) { if (goal == 0) return 0; const int n = nums.size(); vector<int> sums0{0}, sums1{0}; for (int i = 0; i < n / 2; ++i) { const int m = sums0.size(); for (int j = 0; j < m; ++j) sums0.push_back(sums0[j] + nums[i]); } for (int i = n / 2; i < n; ++i) { const int m = sums1.size(); for (int j = 0; j < m; ++j) sums1.push_back(sums1[j] + nums[i]); } sort(begin(sums1), end(sums1)); int ans = INT_MAX; for (int i = 0; i < sums0.size(); ++i) { // min(|sums0[i] + sums1[j] - goal|) int v = sums0[i] - goal; auto it = lower_bound(begin(sums1), end(sums1), -v); if (it == begin(sums1)) { ans = min(ans, abs(sums0[i] + (*it) - goal)); } else if (it == end(sums1)) { ans = min(ans, abs(sums0[i] + (*(--it)) - goal)); } else { ans = min(ans, abs(sums0[i] + (*it) - goal)); ans = min(ans, abs(sums0[i] + (*(--it)) - goal)); } } return ans; } };
36.738095
97
0.464031
[ "vector" ]
3d198c5a48e56d9f869d575f0c68933c0f5a5956
684
h
C
garageofcode/cpp/sat.h
tpi12jwe/garageofcode
3cfaf01f6d77130bb354887e6ed9921c791db849
[ "MIT" ]
2
2020-02-11T10:32:06.000Z
2020-02-11T17:00:47.000Z
garageofcode/cpp/sat.h
jonatanwestholm/garageofcode
630e99c6fb4c42875beadb6adf8dc958501c5ab8
[ "MIT" ]
null
null
null
garageofcode/cpp/sat.h
jonatanwestholm/garageofcode
630e99c6fb4c42875beadb6adf8dc958501c5ab8
[ "MIT" ]
null
null
null
#include <set> #include <map> #include <vector> #define CLAUSES map<int, set<int>> // a mapping clause_id -> set of literals #define VARS map<int, set<int>> // a mapping var_id -> set of clauses #define CNF_CLAUSES set<int> // a set of clause_id #define CNF_VARS set<int> // a set of var_id #define ASSIGNMENT map<int, int> // a mapping var_id -> bool, may be partial #define VECTOR vector<int> using namespace std; CLAUSES clauses; VARS vars; int sign(int a); void print_map(VARS m); bool assume(CNF_CLAUSES& cnf_clauses, CNF_VARS& cnf_vars, int lit); bool solve(CNF_CLAUSES& cnf_clauses, CNF_VARS& cnf_vars, ASSIGNMENT assignment); int main(int argc, char const *argv[]);
24.428571
80
0.72807
[ "vector" ]
3d1f9b2395e292079dc466bef441165bc072d549
4,444
c
C
components/elm/src/external_models/sbetr/3rd-party/hdf5/src/H5Pfmpl.c
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
42
2015-06-03T15:26:21.000Z
2022-02-28T22:36:03.000Z
components/elm/src/external_models/sbetr/3rd-party/hdf5/src/H5Pfmpl.c
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
60
2015-05-11T21:36:08.000Z
2022-03-29T16:22:42.000Z
components/elm/src/external_models/sbetr/3rd-party/hdf5/src/H5Pfmpl.c
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
27
2016-06-06T21:55:14.000Z
2022-03-18T18:23:28.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*------------------------------------------------------------------------- * * Created: H5Pmtpl.c * November 1 2006 * Quincey Koziol <koziol@hdfgroup.org> * * Purpose: File mount property list class routines * *------------------------------------------------------------------------- */ /****************/ /* Module Setup */ /****************/ #define H5P_PACKAGE /*suppress error about including H5Ppkg */ /***********/ /* Headers */ /***********/ #include "H5private.h" /* Generic Functions */ #include "H5Eprivate.h" /* Error handling */ #include "H5Fprivate.h" /* Files */ #include "H5Iprivate.h" /* IDs */ #include "H5Ppkg.h" /* Property lists */ /****************/ /* Local Macros */ /****************/ /* ======================== File Mount properties ====================*/ /* Definition for whether absolute symlinks local to file. */ #define H5F_MNT_SYM_LOCAL_SIZE sizeof(hbool_t) #define H5F_MNT_SYM_LOCAL_DEF FALSE /******************/ /* Local Typedefs */ /******************/ /********************/ /* Package Typedefs */ /********************/ /********************/ /* Local Prototypes */ /********************/ /* Property class callbacks */ static herr_t H5P_fmnt_reg_prop(H5P_genclass_t *pclass); /*********************/ /* Package Variables */ /*********************/ /* File mount property list class library initialization object */ const H5P_libclass_t H5P_CLS_FMNT[1] = {{ "file mount", /* Class name for debugging */ H5P_TYPE_FILE_MOUNT, /* Class type */ &H5P_CLS_ROOT_g, /* Parent class */ &H5P_CLS_FILE_MOUNT_g, /* Pointer to class */ &H5P_CLS_FILE_MOUNT_ID_g, /* Pointer to class ID */ &H5P_LST_FILE_MOUNT_ID_g, /* Pointer to default property list ID */ H5P_fmnt_reg_prop, /* Default property registration routine */ NULL, /* Class creation callback */ NULL, /* Class creation callback info */ NULL, /* Class copy callback */ NULL, /* Class copy callback info */ NULL, /* Class close callback */ NULL /* Class close callback info */ }}; /*****************************/ /* Library Private Variables */ /*****************************/ /*------------------------------------------------------------------------- * Function: H5P_fmnt_reg_prop * * Purpose: Register the file mount property list class's properties * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * October 31, 2006 *------------------------------------------------------------------------- */ static herr_t H5P_fmnt_reg_prop(H5P_genclass_t *pclass) { hbool_t local = H5F_MNT_SYM_LOCAL_DEF; /* Whether symlinks are local to file */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* Register property of whether symlinks is local to file */ if(H5P_register_real(pclass, H5F_MNT_SYM_LOCAL_NAME, H5F_MNT_SYM_LOCAL_SIZE, &local, NULL, NULL, NULL, NULL, NULL, NULL, NULL) < 0) HGOTO_ERROR(H5E_PLIST, H5E_CANTINSERT, FAIL, "can't insert property into class") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5P_fmnt_reg_prop() */
34.71875
135
0.501125
[ "object" ]
3d223d9797d7590fc4dad478ec1ece10972507ff
6,469
h
C
Nesis/Common/Logbook/Logbook.h
jpoirier/x-gauges
8261b19a9678ad27db44eb8c354f5e66bd061693
[ "BSD-3-Clause" ]
3
2015-11-08T07:17:46.000Z
2019-04-05T17:08:05.000Z
Nesis/Common/Logbook/Logbook.h
jpoirier/x-gauges
8261b19a9678ad27db44eb8c354f5e66bd061693
[ "BSD-3-Clause" ]
null
null
null
Nesis/Common/Logbook/Logbook.h
jpoirier/x-gauges
8261b19a9678ad27db44eb8c354f5e66bd061693
[ "BSD-3-Clause" ]
null
null
null
#ifndef LOGBOOK_H #define LOGBOOK_H /*************************************************************************** * * * Copyright (C) 2007 by Kanardia d.o.o. [see www.kanardia.eu] * * Writen by: * * Ales Krajnc [ales.krajnc@kanardia.eu] * * * * Status: Open Source * * * * License: GPL - GNU General Public License * * See 'COPYING.html' for more details about the license. * * * ***************************************************************************/ #include <QXmlDefaultHandler> #include <QFile> #include "Entry.h" #include "Record.h" #define TAG_LOGBOOK "logbook" #define TAG_VERSION "version" #define TAG_ENTRY "entry" #define TAG_PILOT "pilot" #define TAG_ENGINE "engine" #define TAG_FLIGHT "flight" #define TAG_RECORD "record" #define TAG_FUEL "fuel" #define TAG_SPEED "speed" #define TAG_ALTITUDE "altitude" #define TAG_DISTANCE "distance" #define TAG_ON "on" #define TAG_OFF "off" #define TAG_TAKEOFF "takeoff" #define TAG_LANDING "landing" #define TAG_MIN "min" #define TAG_MAX "max" #define TAG_AVG "avg" #define TAG_TOTAL "total" #define TAG_SPECIFIC "specific" namespace logbook { // ------------------------------------------------------------------------- /** Shared (singletone) logbook object. It is very important, that the system time is not changed when the logging is performed. This may result in an invalid log. */ class Logbook : public QXmlDefaultHandler { public: //! Container of logbook entries. typedef QVector<Entry> Container; //! Constructor is private in order to prevent direct class creation. Logbook(); public: //! Destructor. ~Logbook(); //! Access point to the class. static Logbook* GetInstance() { if(s_pInstance == NULL) s_pInstance = new Logbook(); return s_pInstance; } //! Delete all blog records and xml file. Posible only if not recording. bool DeleteAll(); //! Update the information (updates current record and entry.) void Update(); //! Return true, if the system is recording. bool IsRecording() const { return m_record.IsRecording(); } //! Get a copy of the logbook container. Container GetReverseContainer(int iMaxCount, bool bCurrent) const; //! Load the XML logbook file. int Load(const QString& qsXMLLogFile); private: //! Clear internal variables and set them into initial state. void Clear(); //! Start the recording process. void StartRecording(); //! Stop recording process. void StopRecording(); //! Write current content to the XML file. void WriteXML(); //! Update current entry from given file. QDateTime UpdateEntryFromFile(QFile& file, bool bContinue); //! Update current entry with data. void UpdateEntry(const Record::Data& d, const QDateTime& dtStart); //! Terminate current recording and entry. void TerminateRecord(QFile* pFile); //! XML simple parser - starting element bool startElement(const QString& qsNamespace, const QString& qsLocalName, const QString& qsName, const QXmlAttributes& qaAttributes); //! XML simple parser - closing element. bool endElement( const QString& qsNamespace, const QString& qsLocalName, const QString& qsName); //! XML simple parser - characters between start and end. bool characters(const QString& qs); //! XML simple parser - the error handler. bool fatalError(const QXmlParseException& exception); //! Add distance from last point to this point (lon, lat) in [rad]. void AddDistance(const QPointF& ptNew); //! Update altitude limits [m]. void UpdateAltitudeLimits(int iAlt); //! Update speed limits [m/s]. void UpdateSpeedLimits(float fSpeed); //! Add (integrate) fuel flow [l/s] to get fuel consumption. void AddFuel(float fFuelFlow); //! Reset last coordinate. void ResetLastCoordinate() { m_ptLastCoor = QPointF(); } //! Get minimal recorded altitude [m]. int GetMinAltitude() const { return m_iMinAlt; } //! Get maximal recorded altitude [m]. int GetMaxAltitude() const { return m_iMaxAlt; } //! Get maximal airspeed [m/s]. float GetMaxSpeed() const { return m_fMaxSpeed; } //! Get distance traveled [m](this is not point to point distance). float GetDistance() const { return m_fDistance; } //! Get average speed [m/s] (distance/airborn time). float GetAverageSpeed(float fExtraSec=0.0f) const; //! Get fuel used in this flight [l]. float GetFuelConsumption(float fExtraSec=0.0f) const; //! Get specific fuel consumption [l/h]. float GetSpecificFuelConsumption(float fExtraSec=0.0f) const; private: //! Instance of the logbook object. static Logbook* s_pInstance; //! Remember the file name. QString m_qsFileName; //! Store all the logbook entries. Container m_conBook; //! Working entry variable - works in sync with the record. Entry m_entry; //! Recording object - records to the file. Record m_record; // //! State of the reader. // XmlReaderState m_eState; //! Current content of xml tag. QString m_qsData; // helper variables used to maintain the state of the active entry. OnOff m_ofFlight; //!< Current flight status int m_iFlightCounter; //!< A counter used to detect true flight conditions. int m_iFlightTime; //!< Elapsed time at the detection time even. OnOff m_ofEngine; //!< Current engine status int m_iEngineCounter; //!< A counter used to detect true on/off conditions. int m_iEngineTime; //!< Elapsed time at the detection time even. // Some statistical data variables //! minimal altitude [m]. int m_iMinAlt; //! maximal altitude [m]. int m_iMaxAlt; //! maximal speed [m/s] float m_fMaxSpeed; //! distance traveled [m] float m_fDistance; //! fuel used [l] (Just a sum of fuel flow values.) float m_fFuel; //! Number of fuel add events. Used to calculate dT. int m_iFuelCount; //! Last coordinate (long, lat) in [rad]. QPointF m_ptLastCoor; }; } // namespace // ------------------------------------------------------------------------- #endif
30.952153
77
0.620343
[ "object" ]
2cf4a84d326636566a1c285c65e6a83313121a05
3,265
h
C
cms/include/alibabacloud/cms/model/PutLogMonitorRequest.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
cms/include/alibabacloud/cms/model/PutLogMonitorRequest.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
cms/include/alibabacloud/cms/model/PutLogMonitorRequest.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_CMS_MODEL_PUTLOGMONITORREQUEST_H_ #define ALIBABACLOUD_CMS_MODEL_PUTLOGMONITORREQUEST_H_ #include <string> #include <vector> #include <alibabacloud/core/RpcServiceRequest.h> #include <alibabacloud/cms/CmsExport.h> namespace AlibabaCloud { namespace Cms { namespace Model { class ALIBABACLOUD_CMS_EXPORT PutLogMonitorRequest : public RpcServiceRequest { public: struct ValueFilter { std::string value; std::string key; std::string _operator; }; struct Groupbys { std::string fieldName; std::string alias; }; struct Aggregates { std::string fieldName; std::string function; std::string alias; }; public: PutLogMonitorRequest(); ~PutLogMonitorRequest(); std::string getSlsLogstore()const; void setSlsLogstore(const std::string& slsLogstore); std::string getSlsProject()const; void setSlsProject(const std::string& slsProject); std::vector<ValueFilter> getValueFilter()const; void setValueFilter(const std::vector<ValueFilter>& valueFilter); std::string getMetricExpress()const; void setMetricExpress(const std::string& metricExpress); std::string getSlsRegionId()const; void setSlsRegionId(const std::string& slsRegionId); std::string getMetricName()const; void setMetricName(const std::string& metricName); std::string getGroupId()const; void setGroupId(const std::string& groupId); std::string getTumblingwindows()const; void setTumblingwindows(const std::string& tumblingwindows); std::string getValueFilterRelation()const; void setValueFilterRelation(const std::string& valueFilterRelation); std::string getUnit()const; void setUnit(const std::string& unit); std::vector<Groupbys> getGroupbys()const; void setGroupbys(const std::vector<Groupbys>& groupbys); std::string getLogId()const; void setLogId(const std::string& logId); std::vector<Aggregates> getAggregates()const; void setAggregates(const std::vector<Aggregates>& aggregates); private: std::string slsLogstore_; std::string slsProject_; std::vector<ValueFilter> valueFilter_; std::string metricExpress_; std::string slsRegionId_; std::string metricName_; std::string groupId_; std::string tumblingwindows_; std::string valueFilterRelation_; std::string unit_; std::vector<Groupbys> groupbys_; std::string logId_; std::vector<Aggregates> aggregates_; }; } } } #endif // !ALIBABACLOUD_CMS_MODEL_PUTLOGMONITORREQUEST_H_
32.009804
80
0.708116
[ "vector", "model" ]
2cfb2f593825a5694236abe39ad89564c2ccf366
6,754
h
C
include/GeonlpMAImplSq3.h
t-sagara/geonlp-software
bcb57f55d4790b8f332f44dcb78b5a3cca2f1a63
[ "BSD-2-Clause", "BSD-2-Clause-FreeBSD" ]
1
2019-09-15T07:47:41.000Z
2019-09-15T07:47:41.000Z
include/GeonlpMAImplSq3.h
t-sagara/geonlp-software
bcb57f55d4790b8f332f44dcb78b5a3cca2f1a63
[ "BSD-2-Clause", "BSD-2-Clause-FreeBSD" ]
1
2019-09-13T08:27:35.000Z
2019-09-14T00:43:07.000Z
include/GeonlpMAImplSq3.h
t-sagara/geonlp-software
bcb57f55d4790b8f332f44dcb78b5a3cca2f1a63
[ "BSD-2-Clause", "BSD-2-Clause-FreeBSD" ]
1
2018-10-03T10:56:23.000Z
2018-10-03T10:56:23.000Z
/// /// @file /// @brief 地名語抽出API(インタフェース)実装クラスの定義。 /// @author 国立情報学研究所 /// /// Copyright (c)2010, NII /// #ifndef _GEONLP_MA_IMPL_SQ3_H #define _GEONLP_MA_IMPL_SQ3_H #include "GeonlpMA.h" #include "MeCabAdapter.h" #include "PHBSDefs.h" #include <fstream> #include "darts.h" #ifdef GEOWORD_UNITTEST #define PUBLIC_IF_UNITTEST public: #else #define PUBLIC_IF_UNITTEST #endif namespace geonlp { class MeCabAdapter; class DBAccessor; class Profile; class Suffix; // class Prefix; class Geoword; class Dictionary; class GeowordSubset; class AbstructGeowordFormatter; class NodeExt; typedef boost::shared_ptr<MeCabAdapter> MeCabAdapterPtr; typedef boost::shared_ptr<DBAccessor> DBAccessorPtr; typedef boost::shared_ptr<Profile> ProfilePtr; typedef boost::shared_ptr<AbstructGeowordFormatter> GeowordFormatterPtr; typedef boost::shared_ptr<Darts::DoubleArray> DoubleArrayPtr; /// @brief MAのインタフェース実装クラス。 class MAImpl: public MA { private: /// MeCabにアクセスするためのクラスへのポインタ。 MeCabAdapterPtr mecabp; /// SQLiteにアクセスするためのクラスへのポインタ。 DBAccessorPtr dbap; /// SQLite に登録されている地名語の darts クラスへのポインタ。 DoubleArrayPtr dap; /// 形態素情報リストの出力形式定義クラスへのポインタ。 GeowordFormatterPtr formatter; /// 地名接頭辞集合、地名語の先頭となり得る品詞集合、地名語の部分となり得る品詞集合等の定義 PHBSDefs phbsDefs; /// プロファイルで指定された辞書IDのリスト、リセット用に記憶 std::map<int, Dictionary> defaultDictionaries; /// プロファイルで指定された利用可能クラスのリスト、リセット用に記憶 std::vector<std::string> defaultClasses; /// 利用する辞書 ID のリスト、高速化のため記憶 std::map<int, Dictionary> activeDictionaries; /// 利用するクラスのリスト、高速化のため記憶 std::vector<std::string> activeClasses; typedef MeCabAdapter::NodeList NodeList; typedef std::list<NodeExt> NodeExtList; public: // コンストラクタ MAImpl( MeCabAdapterPtr mp, DBAccessorPtr dp, DoubleArrayPtr dap, ProfilePtr p) throw (std::runtime_error); // デストラクタ ~MAImpl(); /// ID で指定した辞書情報を取得する bool findDictionaryById(int dictionary_id, Dictionary& ret) const; // 辞書一覧を取得する int getDictionaryList(std::map<int, Dictionary>& ret) const; // 引数として渡された自然文を形態素解析し、解析結果をテキストとして返す。 std::string parse(const std::string & sentence) const throw (SqliteNotInitializedException, SqliteErrException, MeCabNotInitializedException, MeCabErrException); // 引数として渡された自然文を形態素解析し、解析結果の各行を要素とするノードの配列を返す。 int parseNode(const std::string & sentence, std::vector<Node>& ret) const throw (SqliteNotInitializedException, SqliteErrException, MeCabNotInitializedException, MeCabErrException); // 引数として渡されたIDを持つ地名語エントリの全ての情報を地名語辞書システムから取得する。 bool getGeowordEntry(const std::string& geonlp_id, Geoword& ret) const throw (SqliteNotInitializedException, SqliteErrException); // 引数に与えられた(上位語)文字列からGeoword候補を取得する。 // 戻り値は、「keyがgeonlp_id、valueがGeowordオブジェクト」のマップ。 int getGeowordEntries(const std::string & geoword, std::map<std::string, Geoword>& ) const throw (SqliteNotInitializedException, SqliteErrException); /// @brief Node が地名語の場合、地名語のリストを得る /// 地名語ではない場合は空のマップを返す /// @arg node idlist を含む Node /// @return 地名語の場合、 idlist を展開し、 keyがgeonlp_id、valueがGeowordオブジェクトのマップ int getGeowordEntries(const Node& node, std::map<std::string, Geoword>& ret) const throw (SqliteNotInitializedException, SqliteErrException); /// 引数に与えられた文字列からGeoword候補を取得する /// @return Wordlist オブジェクト /// @exception SqliteNotInitializedException Sqlite3が未初期化。 /// @exception SqliteErrException Sqlite3でエラー。 bool getWordlistBySurface(const std::string& key, Wordlist&) const throw (SqliteNotInitializedException, SqliteErrException); /// @brief 利用する辞書を辞書IDのリストで指定する。プロファイルのデフォルトに対する差分。 /// @arg @c dics 利用する辞書ID、複数指定した場合は OR、- から始まる場合は除外 /// @return なし void setActiveDictionaries(const std::vector<int>& dics); /// @brief 利用する辞書を追加する /// @arg @c dics 追加する辞書IDのリスト void addActiveDictionaries(const std::vector<int>& dics); /// @brief 利用する辞書から除外する /// @arg @c dics 除外する辞書IDのリスト void removeActiveDictionaries(const std::vector<int>& dics); /// @brief 利用する辞書をプロファイルのデフォルトに戻す。 void resetActiveDictionaries(void); /// @brief アクティブな辞書 ID のリストを取得する。 const std::map<int, Dictionary>& getActiveDictionaries(void) const; /// @brief 利用する固有名クラスをクラス名正規表現のリストで指定する /// @arg @c ne_classes 利用するクラス名、複数指定した場合は OR、- から始まる場合は除外する /// @return なし void setActiveClasses(const std::vector<std::string>& ne_classes); /// @brief 利用する固有名クラスの正規表現を追加する /// @arg @c ne_classes 追加するクラスの正規表現リスト void addActiveClasses(const std::vector<std::string>& ne_classes); /// @brief 利用する固有名クラスの正規表現を除外する /// @arg @c ne_classes 除外するクラスの正規表現リスト void removeActiveClasses(const std::vector<std::string>& ne_classes); /// @brief 利用する固有名クラスをプロファイルのデフォルトに戻す。 void resetActiveClasses(void); /// @brief アクティブな固有名クラスの正規表現リストを取得する。 const std::vector<std::string>& getActiveClasses(void) const; private: PUBLIC_IF_UNITTEST // MeCabによるパース結果を地名語辞書を参照して変換する void convertMeCabNodeToNodeList( NodeList& nodes, std::vector<Node>& nodelist) const throw (SqliteNotInitializedException, SqliteErrException, MeCabNotInitializedException, MeCabErrException); // 形態素情報クラスのリストを、形態素情報拡張クラスのリストに変換する。 void nodeListToNodeExtList( NodeList& nodes, NodeExtList& nodeextlist) const; // 地名語候補を得る。 void getLongestGeowordCandidate( const NodeExtList::iterator start, const NodeExtList::iterator end, NodeExtList::iterator& ex, NodeExtList::iterator& s, NodeExtList::iterator& e) const; // 地名語を得る。 int getLongestGeoword( const NodeExtList::iterator& s, const NodeExtList::iterator& e, NodeExtList::iterator& next, std::vector<Node>& ret) const; // 素性の表層形を連結した文字列を得る。 std::string joinGeowords( NodeExtList::iterator s, NodeExtList::iterator e) const; // 地名語候補から、地名語Nodeを得る。 bool findGeowordNode( const std::string& surface, Node& node) const; // 見出し語IDから地名語Nodeを得る。 Node getGeowordNode(unsigned int id, std::string& alternative) const throw (SqliteNotInitializedException, SqliteErrException); std::string removeSuffix( const std::string& surface, const std::string &suffix) const; // 地名接尾辞を表すNodeを得る。 Node suffixNode( const Suffix& suffix) const; // DARTS で最長一致する候補を得る。 Darts::DoubleArray::result_pair_type getLongestResultWithDarts(const std::string& key, bool bSurfaceOnly = true) const; // 指定した地名語がアクティブな辞書/クラスに含まれているかチェックする bool isInActiveDictionaryAndClass(const Geoword& geo) const; // 指定した地名語の表記が検索表記と一致していれば true を返す bool isSurfaceMatched(const Geoword& geo, const std::string& surface) const; }; } #endif
33.270936
131
0.73053
[ "vector" ]
2cfb6dcde689d54ec22e7c2f87deb1b821edaa34
25,081
h
C
Sources/Engine/External/FBX/SWIG/FBXSDK_ChangedHeaders/fbxsdk/utils/fbxusernotification.h
intensifier/NeoAxisEngine
5c3d6d853c1d420e332aa31c73840f7cf3fd3eef
[ "IJG" ]
1,303
2015-02-15T05:12:55.000Z
2022-03-18T18:23:28.000Z
Sources/Engine/External/FBX/SWIG/FBXSDK_ChangedHeaders/fbxsdk/utils/fbxusernotification.h
intensifier/NeoAxisEngine
5c3d6d853c1d420e332aa31c73840f7cf3fd3eef
[ "IJG" ]
227
2019-09-11T08:40:24.000Z
2020-06-26T14:12:07.000Z
Sources/Engine/External/FBX/SWIG/FBXSDK_ChangedHeaders/fbxsdk/utils/fbxusernotification.h
intensifier/NeoAxisEngine
5c3d6d853c1d420e332aa31c73840f7cf3fd3eef
[ "IJG" ]
538
2015-02-19T21:53:15.000Z
2022-03-11T06:18:05.000Z
/**************************************************************************************** Copyright (C) 2015 Autodesk, Inc. All rights reserved. Use of this software is subject to the terms of the Autodesk license agreement provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. ****************************************************************************************/ //! \file fbxusernotification.h #ifndef _FBXSDK_UTILS_USER_NOTIFICATION_H_ #define _FBXSDK_UTILS_USER_NOTIFICATION_H_ #include <fbxsdk/fbxsdk_def.h> #include <fbxsdk/core/base/fbxarray.h> #include <fbxsdk/core/base/fbxstring.h> #include <fbxsdk/core/base/fbxmultimap.h> #include <fbxsdk/fbxsdk_nsbegin.h> class FbxLogFile; class FbxMessageEmitter; class FbxUserNotificationFilteredIterator; /** This class defines one entry object held by the FbxUserNotification class. * \nosubgrouping * An entry object is a message to show error, warning or information. * Direct manipulation of this object should not be required. At most, access to * its members can be granted for querying purposes. */ class FBXSDK_DLL FbxAccumulatorEntry { public: /** Category of the accumulator entry. */ enum EClass { eError=1, //!< Error message entry. eWarning=2, //!< Warning message entry. eInformation=4, //!< Information message entry. eAny=7 //!< Entry that does not belong to above class. Cannot be used as a class ID }; /** Constructor. * \param pAEClass Specify the category for this entry. * \param pName Identifies this entry (more than one object can have the same name). * \param pDescr The description of the entry. This is the common message. The details * are added separately by the FbxUserNotification classes. * \param pDetail A list of detail string that will be copied into the local array. * \param pMuteState Whether this entry is muted. * \remarks By default the object is muted so it does not get processed by the low level * output routines of the UserNotification accumulator. The entry gets activated * (unmuted) by the calls to AddDetail() in the accumulator. */ FbxAccumulatorEntry(EClass pAEClass, const FbxString& pName, const FbxString& pDescr, FbxString pDetail="", bool pMuteState=true); /** Copy Constructor. * \param pAE Another FbxAccumulatorEntry object to be copied. * \param pSkipDetails Flag to skip details. */ FbxAccumulatorEntry(const FbxAccumulatorEntry& pAE, bool pSkipDetails); //! Destructor. ~FbxAccumulatorEntry(); //! Returns the category class of this entry. EClass GetClass() const; //! Returns the name of this entry. FbxString GetName() const; //! Returns the description of this entry. FbxString GetDescription() const; //! Returns the number of details stored. int GetDetailsCount() const; /** Returns a pointer to one specific detail string (or NULL if the id is invalid). * Detail string is dynamic. One entry can have multiple detail strings to hold extra information. * For example, if one entry message is related to many FBX nodes, user can add these nodes' name as details. * \param id The detail id. * \return Pointer to the specific detail. */ const FbxString* GetDetail(int id) const; //! Returns True if this entry is muted. bool IsMuted() const; private: FbxArray<FbxString*>& GetDetails(); void Mute(bool pState); bool mMute; EClass mAEClass; FbxString mName; FbxString mDescr; FbxArray<FbxString*> mDetails; friend class FbxUserNotification; }; /** This class accumulates user notifications and sends them to any device opened by the derived classes. * If this class is not derived, the data can only be sent to a log file. To send data to a log file, * it must be opened before attempting to send data, otherwise, the messages will be lost. */ class FBXSDK_DLL FbxUserNotification { public: /** * Create and initialize user notification object for the SDK manager. * One SDK manager has one global user notification object. * If the SDK manager already has global user notification object, the function will do nothing. * * \param pManager * \param pLogFileName Name of the log file that will be open in the directory * defined by the GetLogFilePath method. * \param pSessionDescription This string is used to separate session logs in the file. * \return the global user notification object owned by the SDK manager. */ static FbxUserNotification* Create(FbxManager* pManager, const FbxString& pLogFileName, const FbxString& pSessionDescription); /** * Destroy the global user notification object owned by the SDK manager. */ static void Destroy(FbxManager* pManager); /** Instantiate a FbxUserNotification but leave it uninitialized. The caller must * explicitly call InitAccumulator to initialize it and ClearAccumulator when finished * using it. * \param pManager * \param pLogFileName Name of the log file that will be open in the directory * defined by the GetLogFilePath method. * \remarks If pLogFileName is an empty string the log file does not get created and any * output sent to it is lost. * \param pSessionDescription This string is used to separate session logs in the file. * \remarks If the specified log file already exists, messages are appended to it. This * class never deletes the log file. Derived classes may delete the log file * before opening (it must be done in the constructor because the log file is * opened in the InitAccumulator) or at the end of the processing in the * PostTerminate method. */ FbxUserNotification(FbxManager* pManager, FbxString const& pLogFileName, FbxString const& pSessionDescription); //! Destructor. virtual ~FbxUserNotification(); /** * Accumulator is to hold the notification entries. User can add entries to it. * This method must be called before using the Accumulator. It opens the log file and * calls AccumulatorInit followed by OpenExtraDevices. Failing to call this method * will prevent other actions except ClearAccumulator, GetLogFileName and GetLogFilePath. */ void InitAccumulator(); /** This method must be called when the Accumulator is no longer needed. It calls * CloseExtraDevices, followed by the AccumulatorClear, and then closes the log file. */ void ClearAccumulator(); /** IDs for pre-defined message entries. */ enum EEntryID { eBindPoseInvalidObject, eBindPoseInvalidRoot, eBindPoseNotAllAncestorsNodes, eBindPoseNotAllDeformingNodes, eBindPoseNotAllAncestorsDefinitionNodes, eBindPoseRelativeMatrix, eEmbedMediaNotify, eFileIONotify, //!< this is generic for reader and writer to log notifications. eFileIONotifyMaterial, eFileIONotifyDXFNotSupportNurbs, eEntryStartID //!< Starting ID for any Accumulator entry added by derived classes. }; /** * \name Accumulator Management */ //@{ /** Adds one entry into the accumulator. * \param pID This entry unique ID. * \param pName This entry name. * \param pDescr The description of this entry. * \param pClass The category of this entry. * \return The ID of the newly allocated entry. This ID is pEntryId. */ int AddEntry(const int pID, const FbxString& pName, const FbxString& pDescr, FbxAccumulatorEntry::EClass pClass=FbxAccumulatorEntry::eWarning); /** Completes the accumulator entry (there can be more that one detail for each entry) and implicitly defines * the sequence of events. Each call to this method is internally recorded, making it possible to output each * notification in the order they have been defined. Also, when a detail is added to an entry, it is automatically unmuted * so it can be sent to the devices (muted FbxAccumulatorEntry objects are not processed). * \param pEntryId The entry index (as returned by AddEntry). * \return The id of the detail in the recorded sequence of events. This Id should be used when the call to * Output has the eSequencedDetails set as a source. If an error occurs, the returned value is -1 */ int AddDetail(int pEntryId); /** Completes the accumulator entry (there can be more that one detail for each entry) and implicitly defines * the sequence of events. Each call to this method is internally recorded, making it possible to output each * notification in the order they have been defined. Also, when a detail is added to an entry, it is automatically unmuted * so it can be sent to the devices (muted FbxAccumulatorEntry objects are not processed). * \param pEntryId The entry index (as returned by AddEntry). * \param pString The detail string to add to the entry. * \return The id of the detail in the recorded sequence of events. This Id should be used when the call to * Output has the eSequencedDetails set as a source. If an error occurs, the returned value is -1 */ int AddDetail(int pEntryId, FbxString pString); /** Completes the accumulator entry (there can be more that one detail for each entry) and implicitly defines * the sequence of events. Each call to this method is internally recorded, making it possible to output each * notification in the order they have been defined. Also, when a detail is added to an entry, it is automatically unmuted * so it can be sent to the devices (muted FbxAccumulatorEntry objects are not processed). * \param pEntryId The entry index (as returned by AddEntry). * \param pNode The node to add to the entry. * \return The id of the detail in the recorded sequence of events. This Id should be used when the call to * Output has the eSequencedDetails set as a source. If an error occurs, the returned value is -1 */ int AddDetail(int pEntryId, FbxNode* pNode); //! Returns the number of AccumulatorEntries currently stored in this accumulator. int GetNbEntries() const; /** Get the specified FbxAccumulatorEntry. * \param pEntryId ID of the entry to retrieve. * \return Pointer to the specified entry, otherwise \c NULL if either the id is invalid or the Accumulator * is not properly initialized. */ const FbxAccumulatorEntry* GetEntry(int pEntryId); /** Get the FbxAccumulatorEntry at the specified index. * \param pEntryIndex index of the entry to retrieve. * \return Pointer to the specified entry, otherwise \c NULL if either the index is invalid or the Accumulator * is not properly initialized.. */ const FbxAccumulatorEntry* GetEntryAt(int pEntryIndex) const; //! Returns the number of Details recorded so far in this accumulator. int GetNbDetails() const; /** Get the specified detail. * \param pDetailId Index of the detail. This is the id-th detail of type pClass as inserted * when the AddDetail * \param pAE Pointer to the FbxAccumulatorEntry object that contains the requested detail. * The returned valued can be NULL if an error occurred. * \return The index of the detail to be used when calling the GetDetail of the FbxAccumulatorEntry. * \remarks A value of -1 is acceptable and means that the FbxAccumulatorEntry has no details. However, * if pAE is NULL, the return value is meaningless. */ int GetDetail(int pDetailId, const FbxAccumulatorEntry*& pAE) const; //@} /** * \name Accumulator Output */ //@{ /** Specify send what kind of data to output device. */ enum EOutputSource { eAccumulatorEntry, //!< Entry with its details. eSequencedDetails //!< Details in the recorded order. }; /** Send the accumulator entries to the output devices. * This method needs to be explicitly called by the program that uses this * class. * \param pOutSrc Specify which data has to be sent to the output devices. Set to SEQUENCED_DETAILS * to send the Details in the recorded order. Set to ACCUMULATOR_ENTRY to send * each entry with its details regardless of the order in which the events occurred. * \param pIndex If this parameter >= 0, only send the specified entry/detail index to the output devices. * Otherwise send all of them. * \param pExtraDevicesOnly If this parameter is True, the output is not sent to the log file. * \remarks The pExtraDevicesOnly parameter is ignored if the log file has been disabled. */ bool Output(EOutputSource pOutSrc=eAccumulatorEntry, int pIndex = -1, bool pExtraDevicesOnly = false); /** Send the accumulator entry to the output devices. * \param pId Send the entry/detail that matching pIdx to the output devices, * otherwise send all of them. * \param pOutSrc Specify which data has to be sent to the output devices. Set to SEQUENCED_DETAILS * to send the Details in the recorded order. Set to ACCUMULATOR_ENTRY to send * each entry with its details regardless of the order in which the events occurred.. * \param pExtraDevicesOnly If this parameter is True, the output is not sent to the log file. */ bool OutputById(EEntryID pId, EOutputSource pOutSrc=eAccumulatorEntry, bool pExtraDevicesOnly = false); /** Send an immediate entry to the output devices. * This method bypasses the accumulator by sending the entry directly to the output devices * and discarding it right after. The internal accumulator lists are left unchanged by this call. * \param pName This entry name. * \param pDescr The description of this entry. * \param pClass The category of this entry. * \param pExtraDevicesOnly If this parameter is True, the output is not sent to the log file. * \remarks The pExtraDevicesOnly parameter is ignored if the log file has been disabled. */ bool Output(const FbxString& pName, const FbxString& pDescr, FbxAccumulatorEntry::EClass pClass, bool pExtraDevicesOnly = false); /** Sends the content of the iterator to the output devices. * This method bypasses the accumulator by sending each entry in the iterator directly to * the output devices. The internal accumulator lists are left unchanged by this call. * \param pAEFIter The Filtered FbxAccumulatorEntry iterator object. * \param pExtraDevicesOnly If this parameter is True, the output is not sent to the log file. * \remarks The pExtraDevicesOnly parameter is ignored if the log file has been disabled. */ bool Output(FbxUserNotificationFilteredIterator& pAEFIter, bool pExtraDevicesOnly = false); /** Set log message emitter. * \param pLogMessageEmitter The new log message emitter. */ void SetLogMessageEmitter(FbxMessageEmitter * pLogMessageEmitter); /** * \name Utilities */ //@{ /** Returns the absolute path to the log file. If this method is not overridden in a derived class, it * returns the TEMP directory. * \param pPath The returned path. */ virtual void GetLogFilePath(FbxString& pPath); /** Returns the log file name. */ inline FbxString GetLogFileName() { return mLogFileName; } //@} protected: /** * Identify one detail in all accumulator entries by record the entry object and its detail id. */ class AESequence { public: AESequence(FbxAccumulatorEntry* pAE, int pDetailId) : mAE(pAE), mDetailId(pDetailId) { }; //! Return the entry object the detail belongs to. FbxAccumulatorEntry* AE() { return mAE; } //! Return the detail id in the entry object int DetailId() { return mDetailId; } private: FbxAccumulatorEntry* mAE; int mDetailId; }; friend class FbxUserNotificationFilteredIterator; /** Allow a derived class to finalize processing AFTER the log file handle has been * deleted. This may be required if the log file needs to be moved or shown. * \returns True if the object is properly cleaned. */ virtual bool PostTerminate(); /** Allow the implementation class to perform accumulator initializations before * the Extra devices are opened. By default this method does nothing. */ virtual void AccumulatorInit(); /** Allow the implementation class to perform accumulator clear after the Extra devices are * closed. By default this method does nothing. */ virtual void AccumulatorClear(); /** Allow the implementation class to opens its output devices (called by InitAccumulator). * By default this method does nothing. */ virtual void OpenExtraDevices(); /** Allow the implementation class to send all the accumulator entries to the devices. * By default this method loop trough all the elements of the received array and * call the SendToExtraDevices method with the appropriate FbxAccumulatorEntry element and id. * \param pOutputNow Flag indicates whether to output now. * \param pEntries Accumulator entries to output. * \return \c true if successful, \c false otherwise. */ virtual bool SendToExtraDevices(bool pOutputNow, FbxArray<FbxAccumulatorEntry*>& pEntries); /** Allow the implementation class to send all the accumulator entries to the devices. * By default this method loop trough all the elements of the received array and * call the SendToExtraDevices method with the appropriate FbxAccumulatorEntry element and id. * \param pOutputNow Flag indicates whether to output now. * \param pAESequence Accumulator entries to output. * \return \c true if successful, \c false otherwise. */ virtual bool SendToExtraDevices(bool pOutputNow, FbxArray<AESequence*>& pAESequence); /** Allow the implementation class to send one accumulator entry to the devices. * By default this method does nothing. * \param pOutputNow Flag indicates whether to output now. * \param pAccEntry Accumulator entry to output. * \param pDetailId Detail id. * \return \c true if successful, \c false otherwise. * \remarks Derived methods should check for the IsMuted() state to decide if the accumulator * entry should get through or get discarded. See AddDetail for more details. */ virtual bool SendToExtraDevices(bool pOutputNow, const FbxAccumulatorEntry* pAccEntry, int pDetailId = -1); /** Allow the implementation class to close it's output devices (called in the ClearAccumulator) * By default this method does nothing. */ virtual void CloseExtraDevices(); //! Clears the Accumulator list, remove all user notification entries.. void ResetAccumulator(); //! Clears the Sequence list. void ResetSequence(); /** Send the pIdth element of the accumulator or sequence list to the log file. * \param pOutSrc The output source, accumulator or sequence list. * \param pId Element id. */ void SendToLog(EOutputSource pOutSrc, int pId); /** Send the accumulator entry to the log file. * \param pAccEntry The accumulator entry. * \param pDetailId Detail id. */ void SendToLog(const FbxAccumulatorEntry* pAccEntry, int pDetailId = -1); private: FbxString mLogFileName; FbxString* mLog; FbxLogFile* mLogFile; FbxMessageEmitter* mLogMessageEmitter; bool mProperlyInitialized; FbxString mSessionDescription; bool mProperlyCleaned; FbxMultiMap mAccuHT; // The set establish a relationship between an FbxAccumulatorEntry and it's ID FbxArray<FbxAccumulatorEntry*> mAccu; // The array defines the order the FbxAccumulatorEntry objects have been // added to the accumulator (calls to AddEntry) // Both structures share the same pointers. FbxArray<AESequence*> mAESequence; FbxManager* mSdkManager; }; /** This class iterates through the accumulated messages depending on the configuration * flags (filter). The iterator keeps a local copy of the data extracted from the * accumulator. */ class FBXSDK_DLL FbxUserNotificationFilteredIterator { public: /** Constructor. * \param pAccumulator This reference is only used during construction for retrieving * the data required to fill the iterator. * \param pFilterClass The bitwise combination of the EClass identifiers. An FbxAccumulatorEntry * element is copied from the accumulator if its Class matches one of the * bits of this flag. * \param pSrc Specify which data format is extracted from the accumulator. * \param pNoDetail This parameter is used ONLY if pSrc == eAccumulatorEntry and, if set to * false, the details of the FbxAccumulatorEntry are also sent to the output * devices. If left to its default value, only the description of the * FbxAccumulatorEntry is sent. */ FbxUserNotificationFilteredIterator(FbxUserNotification& pAccumulator, int pFilterClass, FbxUserNotification::EOutputSource pSrc = FbxUserNotification::eSequencedDetails, bool pNoDetail = true); virtual ~FbxUserNotificationFilteredIterator(); //! Returns the number of elements contained in this iterator. int GetNbItems() const; //! Put the iterator in its reset state. void Reset(); /** Get this iterator's first item. * \return NULL if the iterator is empty. */ FbxAccumulatorEntry* const First(); /** Get this iterator's previous item. * \return NULL if the iterator reached the beginning (or is empty). * \remarks This method will also return NULL if it is called before * or immediately after a call to First() and reset the iterator to * its reset state (meaning that a call to First() is mandatory * to be able to iterate again). */ FbxAccumulatorEntry* const Previous(); /** Get this iterator's next item. * \return NULL if the iterator reached the end (or is empty). * \remarks This method will also return NULL if it is called while * the iterator is in its reset state (called before * First() or after a preceding call to Previous() reached * beyond the beginning). */ FbxAccumulatorEntry* const Next(); protected: // Called in the constructor. virtual void BuildFilteredList(FbxUserNotification& pAccumulator); int mIterator; int mFilterClass; bool mNoDetail; FbxUserNotification::EOutputSource mAccuSrcData; FbxArray<FbxAccumulatorEntry*> mFilteredAE; }; #include <fbxsdk/fbxsdk_nsend.h> #endif /* _FBXSDK_UTILS_USER_NOTIFICATION_H_ */
47.864504
147
0.64826
[ "object" ]
2cfd7c92048f13ea4a46cdbf8102af82c1d60233
7,368
h
C
base/sdk/interfaces/iviewrenderbeams.h
yuukixdev/fl0whaxx
954915a416d1b3b3f20b50965eb6c0575ff3a140
[ "MIT" ]
6
2020-12-09T16:46:20.000Z
2021-11-20T01:48:35.000Z
base/sdk/interfaces/iviewrenderbeams.h
yuukixdev/fl0whaxx
954915a416d1b3b3f20b50965eb6c0575ff3a140
[ "MIT" ]
null
null
null
base/sdk/interfaces/iviewrenderbeams.h
yuukixdev/fl0whaxx
954915a416d1b3b3f20b50965eb6c0575ff3a140
[ "MIT" ]
3
2020-12-11T02:13:14.000Z
2021-02-12T16:17:04.000Z
#pragma once #pragma region renderbeams_definitions #define TE_BEAMPOINTS 0 // beam effect between two points #define TE_SPRITE 1 // additive sprite, plays 1 cycle #define TE_BEAMDISK 2 // disk that expands to max radius over lifetime #define TE_BEAMCYLINDER 3 // cylinder that expands to max radius over lifetime #define TE_BEAMFOLLOW 4 // create a line of decaying beam segments until entity stops moving #define TE_BEAMRING 5 // connect a beam ring to two entities #define TE_BEAMSPLINE 6 #define TE_BEAMRINGPOINT 7 #define TE_BEAMLASER 8 // fades according to viewpoint #define TE_BEAMTESLA 9 #define MAX_BEAM_ENTS 10 #define NOISE_DIVISIONS 128 #pragma endregion enum EBeamType : unsigned int { FBEAM_STARTENTITY = 0x00000001, FBEAM_ENDENTITY = 0x00000002, FBEAM_FADEIN = 0x00000004, FBEAM_FADEOUT = 0x00000008, FBEAM_SINENOISE = 0x00000010, FBEAM_SOLID = 0x00000020, FBEAM_SHADEIN = 0x00000040, FBEAM_SHADEOUT = 0x00000080, FBEAM_ONLYNOISEONCE = 0x00000100, // only calculate our noise once FBEAM_NOTILE = 0x00000200, FBEAM_USE_HITBOXES = 0x00000400, // attachment indices represent hitbox indices instead when this is set. FBEAM_STARTVISIBLE = 0x00000800, // has this client actually seen this beam's start entity yet? FBEAM_ENDVISIBLE = 0x00001000, // has this client actually seen this beam's end entity yet? FBEAM_ISACTIVE = 0x00002000, FBEAM_FOREVER = 0x00004000, FBEAM_HALOBEAM = 0x00008000, // when drawing a beam with a halo, don't ignore the segments and endwidth FBEAM_REVERSED = 0x00010000, }; struct BeamTrail_t { BeamTrail_t* pNext; float flDie; Vector vecOrigin; Vector vecVelocity; }; struct Beam_t { Beam_t() = default; // Methods of IClientRenderable virtual const Vector& GetRenderOrigin() = 0; virtual const QAngle& GetRenderAngles() = 0; virtual const matrix3x4_t& RenderableToWorldTransform() = 0; virtual void GetRenderBounds(Vector& vecMins, Vector& vecMaxs) = 0; virtual bool ShouldDraw() = 0; virtual bool IsTransparent() = 0; virtual int DrawModel(int nFlags) = 0; virtual void ComputeFxBlend() = 0; virtual int GetFxBlend() = 0; Vector vecMins; Vector vecMaxs; int* pQueryHandleHalo; float flHaloProxySize; Beam_t* pNext; int nType; int nFlags; // Control points for the beam int nAttachments; Vector vecAttachment[MAX_BEAM_ENTS]; Vector vecDelta; // 0 .. 1 over lifetime of beam float flTime; float flFrequence; // Time when beam should die float flDie; float flWidth; float flEndWidth; float flFadeLength; float flAmplitude; float flLife; // Color float r, g, b; float flBrightness; // Speed float flSpeed; // Animation float flFrameRate; float flFrame; int nSegments; // Attachment entities for the beam CBaseHandle hEntity[MAX_BEAM_ENTS]; int nAttachmentIndex[MAX_BEAM_ENTS]; // Model info int nModelIndex; int nHaloIndex; float flHaloScale; int iFrameCount; float flRgNoise[NOISE_DIVISIONS + 1]; // Popcorn trail for beam follows to use BeamTrail_t* pTrail; // for TE_BEAMRINGPOINT float flStartRadius; float flEndRadius; // for FBEAM_ONLYNOISEONCE bool bCalculatedNoise; float flHDRColorScale; }; struct BeamInfo_t { BeamInfo_t() { nType = TE_BEAMPOINTS; nSegments = -1; pszModelName = NULL; pszHaloName = NULL; nModelIndex = -1; nHaloIndex = -1; bRenderable = true; nFlags = 0; } int nType; // Entities CBaseEntity* pStartEntity; int iStartAttachment; CBaseEntity* pEndEntity; int iEndAttachment; // Points Vector vecStart; Vector vecEnd; int nModelIndex; const char* pszModelName; int nHaloIndex; const char* pszHaloName; float flHaloScale; float flLife; float flWidth; float flEndWidth; float flFadeLength; float flAmplitude; float flBrightness; float flSpeed; int iStartFrame; float flFrameRate; float flRed; float flGreen; float flBlue; bool bRenderable; int nSegments; int nFlags; // Rings Vector vecCenter; float flStartRadius; float flEndRadius; }; class CBeam; class IViewRenderBeams { public: virtual void InitBeams() = 0; virtual void ShutdownBeams() = 0; virtual void ClearBeams() = 0; virtual void UpdateTempEntBeams() = 0; virtual void DrawBeam(CBeam* pBeam, const RenderableInstance_t& instance, ITraceFilter* pEntityBeamTraceFilter = nullptr) = 0; virtual void DrawBeam(Beam_t* pBeam) = 0; virtual void KillDeadBeams(CBaseEntity* pEntity) = 0; virtual Beam_t* CreateBeamEnts(BeamInfo_t& beamInfo) = 0; virtual Beam_t* CreateBeamEntPoint(BeamInfo_t& beamInfo) = 0; virtual Beam_t* CreateBeamPoints(BeamInfo_t& beamInfo) = 0; virtual Beam_t* CreateBeamRing(BeamInfo_t& beamInfo) = 0; virtual Beam_t* CreateBeamRingPoint(BeamInfo_t& beamInfo) = 0; virtual Beam_t* CreateBeamCirclePoints(BeamInfo_t& beamInfo) = 0; virtual Beam_t* CreateBeamFollow(BeamInfo_t& beamInfo) = 0; virtual void FreeBeam(Beam_t* pBeam) = 0; virtual void UpdateBeamInfo(Beam_t* pBeam, BeamInfo_t& beamInfo) = 0; virtual void CreateBeamEnts(int iStartEntity, int iEndEntity, int nModelIndex, int iHaloIndex, float flHaloScale, float flLife, float flWidth, float flEndWidth, float flFadeLength, float flAmplitude, float flBrightness, float flSpeed, int flStartFrame, float flFrameRate, float r, float g, float b, int iType = -1) = 0; virtual void CreateBeamEntPoint(int iStartEntity, const Vector* pStart, int iEndEntity, const Vector* pEnd, int nModelIndex, int iHaloIndex, float flHaloScale, float flLife, float flWidth, float flEndWidth, float flFadeLength, float flAmplitude, float flBrightness, float flSpeed, int iStartFrame, float flFrameRate, float r, float g, float b) = 0; virtual void CreateBeamPoints(Vector& vecStart, Vector& vecEnd, int nModelIndex, int iHaloIndex, float flHaloScale, float flLife, float flWidth, float flEndWidth, float flFadeLength, float flAmplitude, float flBrightness, float flSpeed, int iStartFrame, float flFrameRate, float r, float g, float b) = 0; virtual void CreateBeamRing(int iStartEntity, int iEndEntity, int nModelIndex, int iHaloIndex, float flHaloScale, float flLife, float flWidth, float flEndWidth, float flFadeLength, float flAmplitude, float flBrightness, float flSpeed, int iStartFrame, float flFrameRate, float r, float g, float b, int iFlags = 0) = 0; virtual void CreateBeamRingPoint(const Vector& vecCenter, float flStartRadius, float flEndRadius, int nModelIndex, int iHaloIndex, float flHaloScale, float flLife, float flWidth, float flEndWidth, float flFadeLength, float flAmplitude, float flBrightness, float flSpeed, int iStartFrame, float flFrameRate, float r, float g, float b, int iFlags = 0) = 0; virtual void CreateBeamCirclePoints(int iType, Vector& vecStart, Vector& vecEnd, int nModelIndex, int iHaloIndex, float flHaloScale, float flLife, float flWidth, float flEndWidth, float flFadeLength, float flAmplitude, float flBrightness, float flSpeed, int iStartFrame, float flFrameRate, float r, float g, float b) = 0; virtual void CreateBeamFollow(int startEnt, int nModelIndex, int iHaloIndex, float flHaloScale, float flLife, float flWidth, float flEndWidth, float flFadeLength, float r, float g, float b, float flBrightness) = 0; };
32.174672
150
0.746336
[ "vector", "model" ]
fa044e577939bb4cada4d2adc16b49a4de2a9850
2,170
c
C
d/henshan/npc/hunter.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
null
null
null
d/henshan/npc/hunter.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
null
null
null
d/henshan/npc/hunter.c
zhangyifei/mud
b2090bbd2a8d3d82b86148d794a7ca59cd2429f3
[ "MIT" ]
null
null
null
#include <ansi.h> inherit NPC; mixed teach_hunting(); void create() { set_name( "猎人", ({ "hunter" }) ); set( "gender", "男性" ); set( "class", "swordman" ); set( "age", 45 ); set( "str", 200 ); set( "con", 26 ); set( "int", 28 ); set( "dex", 200 ); set( "combat_exp", 12000000 ); set( "attitude", "peaceful" ); set_skill( "unarmed", 300 ); set_skill( "dodge", 300 ); set_skill( "training", 300 ); set_skill( "hunting", 300 ); set( "max_qi", 4500 ); set( "max_jing", 2000 ); set( "neili", 4000 ); set( "max_neili", 4000 ); set( "jiali", 150 ); set( "inquiry", ([ "hunting" : (: teach_hunting:), "捕猎" : (: teach_hunting:), ]) ); setup(); carry_object( "/clone/cloth/cloth" )->wear(); } int accept_object( object me, object ob ) { if ( !me || environment( me ) != environment() ) return(0); if ( !objectp( ob ) ) return(0); if ( !present( ob, me ) ) return(notify_fail( "你没有这件东西。" ) ); if ( (string) ob->query( "id" ) == "bushou jia" ) { command( "nod" ); command( "say 这个我正用得着,在下无以为报,如果你愿意,我\n可以" "教你一些捕猎的技巧。" ); me->set_temp( "marks/hunter", 1 ); return(1); }else { command( "shake" ); command( "say 这是什么东西,我不需要!" ); } return(1); } mixed teach_hunting() { object me = this_player(); int jing, add; jing = me->query( "jing" ); add = me->query_int() + random( me->query_int() / 2 ); if ( !me->query_temp( "marks/hunter" ) ) return("你我素无往来,何出此言?\n"); if ( me->is_busy() || me->is_fighting() ) { write( "你现在正忙着。\n" ); return(1); } if ( jing < 20 ) { write( "你的精神无法集中。\n" ); return(1); } if ( (me->query( "potential" ) - me->query( "learned_points" ) ) < 1 ) { write( "你的潜能不够,无法继续学习。\n" ); return(1); } write( HIW "猎人给你讲解了有关捕猎的一些技巧。\n" NOR ); write( HIY "你听了猎人的指导,似乎有所心得。\n" NOR ); me->add( "learned_points", 1 ); me->improve_skill( "hunting", add ); me->add( "jing", -(5 + random( 6 ) ) ); return(1); } int recognize_apprentice( object me, string skill ) { if ( !(int) me->query_temp( "marks/hunter" ) ) return(0); if ( skill != "training" && skill != "hunting" ) { command( "say 我只传授训兽术(training)和狩猎技巧(hunting)。" ); return(-1); } return(1); }
19.20354
71
0.562212
[ "object" ]
fa07e189361bbe4f9c882db3c8e2f2bec5a48c67
23,816
h
C
libkroll/win32/string_util.h
appcelerator/kroll
50b9788d2c391db7676ad0d32f6d8271f51e2a66
[ "Apache-2.0" ]
17
2015-01-23T08:23:12.000Z
2019-07-24T11:44:31.000Z
kroll/libkroll/win32/string_util.h
MChorfa/TideSDK
fae6a35e39a0171942060948084f884391cf6f8a
[ "Apache-2.0" ]
1
2016-03-04T06:11:37.000Z
2016-03-04T06:11:37.000Z
kroll/libkroll/win32/string_util.h
MChorfa/TideSDK
fae6a35e39a0171942060948084f884391cf6f8a
[ "Apache-2.0" ]
9
2015-02-10T17:22:04.000Z
2019-05-17T08:45:05.000Z
// Copyright (c) 2006-2008 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. // // This file defines utility functions for working with strings. #ifndef BASE_STRING_UTIL_H_ #define BASE_STRING_UTIL_H_ #include <string> #include <vector> #include <stdarg.h> // va_list #include "basictypes.h" #include "string16.h" // Safe standard library wrappers for all platforms. namespace base { // C standard-library functions like "strncasecmp" and "snprintf" that aren't // cross-platform are provided as "base::strncasecmp", and their prototypes // are listed below. These functions are then implemented as inline calls // to the platform-specific equivalents in the platform-specific headers. // Compare the two strings s1 and s2 without regard to case using // the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if // s2 > s1 according to a lexicographic comparison. int strcasecmp(const char* s1, const char* s2); // Compare up to count characters of s1 and s2 without regard to case using // the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if // s2 > s1 according to a lexicographic comparison. int strncasecmp(const char* s1, const char* s2, size_t count); // Wrapper for vsnprintf that always null-terminates and always returns the // number of characters that would be in an untruncated formatted // string, even when truncation occurs. int vsnprintf(char* buffer, size_t size, const char* format, va_list arguments); // vswprintf always null-terminates, but when truncation occurs, it will either // return -1 or the number of characters that would be in an untruncated // formatted string. The actual return value depends on the underlying // C library's vswprintf implementation. int vswprintf(wchar_t* buffer, size_t size, const wchar_t* format, va_list arguments); // Some of these implementations need to be inlined. inline int snprintf(char* buffer, size_t size, const char* format, ...) { va_list arguments; va_start(arguments, format); int result = vsnprintf(buffer, size, format, arguments); va_end(arguments); return result; } inline int swprintf(wchar_t* buffer, size_t size, const wchar_t* format, ...) { va_list arguments; va_start(arguments, format); int result = vswprintf(buffer, size, format, arguments); va_end(arguments); return result; } // BSD-style safe and consistent string copy functions. // Copies |src| to |dst|, where |dst_size| is the total allocated size of |dst|. // Copies at most |dst_size|-1 characters, and always NULL terminates |dst|, as // long as |dst_size| is not 0. Returns the length of |src| in characters. // If the return value is >= dst_size, then the output was truncated. // NOTE: All sizes are in number of characters, NOT in bytes. size_t strlcpy(char* dst, const char* src, size_t dst_size); size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size); // Scan a wprintf format string to determine whether it's portable across a // variety of systems. This function only checks that the conversion // specifiers used by the format string are supported and have the same meaning // on a variety of systems. It doesn't check for other errors that might occur // within a format string. // // Nonportable conversion specifiers for wprintf are: // - 's' and 'c' without an 'l' length modifier. %s and %c operate on char // data on all systems except Windows, which treat them as wchar_t data. // Use %ls and %lc for wchar_t data instead. // - 'S' and 'C', which operate on wchar_t data on all systems except Windows, // which treat them as char data. Use %ls and %lc for wchar_t data // instead. // - 'F', which is not identified by Windows wprintf documentation. // - 'D', 'O', and 'U', which are deprecated and not available on all systems. // Use %ld, %lo, and %lu instead. // // Note that there is no portable conversion specifier for char data when // working with wprintf. // // This function is intended to be called from base::vswprintf. bool IsWprintfFormatPortable(const wchar_t* format); } // namespace base #if defined(OS_WIN32) #include "string_util_win.h" #elif defined(OS_POSIX) #include "base/string_util_posix.h" #else #error Define string operations appropriately for your platform #endif // Returns a reference to a globally unique empty string that functions can // return. Use this to avoid static construction of strings, not to replace // any and all uses of "std::string()" as nicer-looking sugar. // These functions are threadsafe. const std::string& EmptyString(); const std::wstring& EmptyWString(); extern const wchar_t kWhitespaceWide[]; extern const char kWhitespaceASCII[]; // Names of codepages (charsets) understood by icu. extern const char* const kCodepageUTF8; // Removes characters in trim_chars from the beginning and end of input. // NOTE: Safe to use the same variable for both input and output. bool TrimString(const std::wstring& input, const wchar_t trim_chars[], std::wstring* output); bool TrimString(const std::string& input, const char trim_chars[], std::string* output); // Trims any whitespace from either end of the input string. Returns where // whitespace was found. The non-wide version of this function only looks for // ASCII whitespace; UTF-8 code-points are not searched for (use the wide // version instead). // NOTE: Safe to use the same variable for both input and output. enum TrimPositions { TRIM_NONE = 0, TRIM_LEADING = 1 << 0, TRIM_TRAILING = 1 << 1, TRIM_ALL = TRIM_LEADING | TRIM_TRAILING, }; TrimPositions TrimWhitespace(const std::wstring& input, TrimPositions positions, std::wstring* output); TrimPositions TrimWhitespace(const std::string& input, TrimPositions positions, std::string* output); // Searches for CR or LF characters. Removes all contiguous whitespace // strings that contain them. This is useful when trying to deal with text // copied from terminals. // Returns |text, with the following three transformations: // (1) Leading and trailing whitespace is trimmed. // (2) If |trim_sequences_with_line_breaks| is true, any other whitespace // sequences containing a CR or LF are trimmed. // (3) All other whitespace sequences are converted to single spaces. std::wstring CollapseWhitespace(const std::wstring& text, bool trim_sequences_with_line_breaks); // These convert between ASCII (7-bit) and UTF16 strings. std::string KROLL_API WideToASCII(const std::wstring& wide); std::wstring KROLL_API ASCIIToWide(const std::string& ascii); // These convert between UTF-8, -16, and -32 strings. They are potentially slow, // so avoid unnecessary conversions. The low-level versions return a boolean // indicating whether the conversion was 100% valid. In this case, it will still // do the best it can and put the result in the output buffer. The versions that // return strings ignore this error and just return the best conversion // possible. KROLL_API bool WideToUTF8(const wchar_t* src, size_t src_len, std::string* output); KROLL_API std::string WideToUTF8(const std::wstring& wide); KROLL_API bool UTF8ToWide(const char* src, size_t src_len, std::wstring* output); KROLL_API std::wstring UTF8ToWide(const std::string& utf8); bool KROLL_API WideToUTF16(const wchar_t* src, size_t src_len, string16* output); string16 KROLL_API WideToUTF16(const std::wstring& wide); bool KROLL_API UTF16ToWide(const char16* src, size_t src_len, std::wstring* output); std::wstring KROLL_API UTF16ToWide(const string16& utf8); bool KROLL_API UTF8ToUTF16(const char* src, size_t src_len, string16* output); string16 KROLL_API UTF8ToUTF16(const std::string& utf8); bool KROLL_API UTF16ToUTF8(const char16* src, size_t src_len, std::string* output); std::string KROLL_API UTF16ToUTF8(const string16& utf16); // Defines the error handling modes of WideToCodepage and CodepageToWide. class OnStringUtilConversionError { public: enum Type { // The function will return failure. The output buffer will be empty. FAIL, // The offending characters are skipped and the conversion will proceed as // if they did not exist. SKIP, }; private: OnStringUtilConversionError(); }; // Converts between wide strings and the encoding specified. If the // encoding doesn't exist or the encoding fails (when on_error is FAIL), // returns false. bool WideToCodepage(const std::wstring& wide, const char* codepage_name, OnStringUtilConversionError::Type on_error, std::string* encoded); bool CodepageToWide(const std::string& encoded, const char* codepage_name, OnStringUtilConversionError::Type on_error, std::wstring* wide); // Converts the given wide string to the corresponding Latin1. This will fail // (return false) if any characters are more than 255. bool WideToLatin1(const std::wstring& wide, std::string* latin1); // Returns true if the specified string matches the criteria. How can a wide // string be 8-bit or UTF8? It contains only characters that are < 256 (in the // first case) or characters that use only 8-bits and whose 8-bit // representation looks like a UTF-8 string (the second case). bool IsString8Bit(const std::wstring& str); bool IsStringUTF8(const std::string& str); bool IsStringWideUTF8(const std::wstring& str); bool IsStringASCII(const std::wstring& str); bool IsStringASCII(const std::string& str); // ASCII-specific tolower. The standard library's tolower is locale sensitive, // so we don't want to use it here. template <class Char> inline Char ToLowerASCII(Char c) { return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c; } // Converts the elements of the given string. This version uses a pointer to // clearly differentiate it from the non-pointer variant. template <class str> inline void StringToLowerASCII(str* s) { for (typename str::iterator i = s->begin(); i != s->end(); ++i) *i = ToLowerASCII(*i); } template <class str> inline str StringToLowerASCII(const str& s) { // for std::string and std::wstring str output(s); StringToLowerASCII(&output); return output; } // Compare the lower-case form of the given string against the given ASCII // string. This is useful for doing checking if an input string matches some // token, and it is optimized to avoid intermediate string copies. This API is // borrowed from the equivalent APIs in Mozilla. bool LowerCaseEqualsASCII(const std::string& a, const char* b); bool LowerCaseEqualsASCII(const std::wstring& a, const char* b); // Same thing, but with string iterators instead. bool LowerCaseEqualsASCII(std::string::const_iterator a_begin, std::string::const_iterator a_end, const char* b); bool LowerCaseEqualsASCII(std::wstring::const_iterator a_begin, std::wstring::const_iterator a_end, const char* b); bool LowerCaseEqualsASCII(const char* a_begin, const char* a_end, const char* b); bool LowerCaseEqualsASCII(const wchar_t* a_begin, const wchar_t* a_end, const char* b); // Returns true if str starts with search, or false otherwise. bool StartsWithASCII(const std::string& str, const std::string& search, bool case_sensitive); bool StartsWith(const std::wstring& str, const std::wstring& search, bool case_sensitive); // Determines the type of ASCII character, independent of locale (the C // library versions will change based on locale). template <typename Char> inline bool IsAsciiWhitespace(Char c) { return c == ' ' || c == '\r' || c == '\n' || c == '\t'; } template <typename Char> inline bool IsAsciiAlpha(Char c) { return ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')); } template <typename Char> inline bool IsAsciiDigit(Char c) { return c >= '0' && c <= '9'; } // Returns true if it's a whitespace character. inline bool IsWhitespace(wchar_t c) { return wcschr(kWhitespaceWide, c) != NULL; } // TODO(mpcomplete): Decide if we should change these names to KIBI, etc, // or if we should actually use metric units, or leave as is. enum DataUnits { DATA_UNITS_BYTE = 0, DATA_UNITS_KILOBYTE, DATA_UNITS_MEGABYTE, DATA_UNITS_GIGABYTE, }; // Return the unit type that is appropriate for displaying the amount of bytes // passed in. DataUnits GetByteDisplayUnits(int64 bytes); // Return a byte string in human-readable format, displayed in units appropriate // specified by 'units', with an optional unit suffix. // Ex: FormatBytes(512, DATA_UNITS_KILOBYTE, true) => "0.5 KB" // Ex: FormatBytes(10*1024, DATA_UNITS_MEGABYTE, false) => "0.1" std::wstring FormatBytes(int64 bytes, DataUnits units, bool show_units); // As above, but with "/s" units. // Ex: FormatSpeed(512, DATA_UNITS_KILOBYTE, true) => "0.5 KB/s" // Ex: FormatSpeed(10*1024, DATA_UNITS_MEGABYTE, false) => "0.1" std::wstring FormatSpeed(int64 bytes, DataUnits units, bool show_units); // Return a number formated with separators in the user's locale way. // Ex: FormatNumber(1234567) => 1,234,567 std::wstring FormatNumber(int64 number); // Starting at |start_offset| (usually 0), look through |str| and replace all // instances of |find_this| with |replace_with|. // // This does entire substrings; use std::replace in <algorithm> for single // characters, for example: // std::replace(str.begin(), str.end(), 'a', 'b'); void ReplaceSubstringsAfterOffset(std::wstring* str, std::wstring::size_type start_offset, const std::wstring& find_this, const std::wstring& replace_with); void ReplaceSubstringsAfterOffset(std::string* str, std::string::size_type start_offset, const std::string& find_this, const std::string& replace_with); // Specialized string-conversion functions. std::string IntToString(int value); std::wstring IntToWString(int value); std::string UintToString(unsigned int value); std::wstring UintToWString(unsigned int value); std::string Int64ToString(int64 value); std::wstring Int64ToWString(int64 value); std::string Uint64ToString(uint64 value); std::wstring Uint64ToWString(uint64 value); // The DoubleToString methods convert the double to a string format that // ignores the locale. If you want to use locale specific formatting, use ICU. std::string DoubleToString(double value); std::wstring DoubleToWString(double value); // Perform a best-effort conversion of the input string to a numeric type, // setting |*output| to the result of the conversion. Returns true for // "perfect" conversions; returns false in the following cases: // - Overflow/underflow. |*output| will be set to the maximum value supported // by the data type. // - Trailing characters in the string after parsing the number. |*output| // will be set to the value of the number that was parsed. // - No characters parseable as a number at the beginning of the string. // |*output| will be set to 0. // - Empty string. |*output| will be set to 0. bool StringToInt(const std::string& input, int* output); bool StringToInt(const std::wstring& input, int* output); bool StringToInt64(const std::string& input, int64* output); bool StringToInt64(const std::wstring& input, int64* output); bool HexStringToInt(const std::string& input, int* output); bool HexStringToInt(const std::wstring& input, int* output); // For floating-point conversions, only conversions of input strings in decimal // form are defined to work. Behavior with strings representing floating-point // numbers in hexadecimal, and strings representing non-fininte values (such as // NaN and inf) is undefined. Otherwise, these behave the same as the integral // variants. This expects the input string to NOT be specific to the locale. // If your input is locale specific, use ICU to read the number. bool StringToDouble(const std::string& input, double* output); bool StringToDouble(const std::wstring& input, double* output); // Convenience forms of the above, when the caller is uninterested in the // boolean return value. These return only the |*output| value from the // above conversions: a best-effort conversion when possible, otherwise, 0. int StringToInt(const std::string& value); int StringToInt(const std::wstring& value); int64 StringToInt64(const std::string& value); int64 StringToInt64(const std::wstring& value); int HexStringToInt(const std::string& value); int HexStringToInt(const std::wstring& value); double StringToDouble(const std::string& value); double StringToDouble(const std::wstring& value); // Return a C++ string given printf-like input. std::string StringPrintf(const char* format, ...); std::wstring StringPrintf(const wchar_t* format, ...); // Store result into a supplied string and return it const std::string& SStringPrintf(std::string* dst, const char* format, ...); const std::wstring& SStringPrintf(std::wstring* dst, const wchar_t* format, ...); // Append result to a supplied string void StringAppendF(std::string* dst, const char* format, ...); void StringAppendF(std::wstring* dst, const wchar_t* format, ...); // Lower-level routine that takes a va_list and appends to a specified // string. All other routines are just convenience wrappers around it. void StringAppendV(std::string* dst, const char* format, va_list ap); void StringAppendV(std::wstring* dst, const wchar_t* format, va_list ap); // This is mpcomplete's pattern for saving a string copy when dealing with // a function that writes results into a wchar_t[] and wanting the result to // end up in a std::wstring. It ensures that the std::wstring's internal // buffer has enough room to store the characters to be written into it, and // sets its .length() attribute to the right value. // // The reserve() call allocates the memory required to hold the string // plus a terminating null. This is done because resize() isn't // guaranteed to reserve space for the null. The resize() call is // simply the only way to change the string's 'length' member. // // XXX-performance: the call to wide.resize() takes linear time, since it fills // the string's buffer with nulls. I call it to change the length of the // string (needed because writing directly to the buffer doesn't do this). // Perhaps there's a constant-time way to change the string's length. template <class char_type> inline char_type* WriteInto( std::basic_string<char_type, std::char_traits<char_type>, std::allocator<char_type> >* str, size_t length_including_null) { str->reserve(length_including_null); str->resize(length_including_null - 1); return &((*str)[0]); } inline char16* WriteInto(string16* str, size_t length_including_null) { str->reserve(length_including_null); str->resize(length_including_null - 1); return &((*str)[0]); } //----------------------------------------------------------------------------- // Function objects to aid in comparing/searching strings. template<typename Char> struct CaseInsensitiveCompare { public: bool operator()(Char x, Char y) const { return tolower(x) == tolower(y); } }; template<typename Char> struct CaseInsensitiveCompareASCII { public: bool operator()(Char x, Char y) const { return ToLowerASCII(x) == ToLowerASCII(y); } }; //----------------------------------------------------------------------------- // Splits |str| into a vector of strings delimited by |s|. Append the results // into |r| as they appear. If several instances of |s| are contiguous, or if // |str| begins with or ends with |s|, then an empty string is inserted. // // Every substring is trimmed of any leading or trailing white space. void SplitString(const std::wstring& str, wchar_t s, std::vector<std::wstring>* r); void SplitString(const std::string& str, char s, std::vector<std::string>* r); // The same as SplitString, but don't trim white space. void SplitStringDontTrim(const std::wstring& str, wchar_t s, std::vector<std::wstring>* r); void SplitStringDontTrim(const std::string& str, char s, std::vector<std::string>* r); // WARNING: this uses whitespace as defined by the HTML5 spec. If you need // a function similar to this but want to trim all types of whitespace, then // factor this out into a function that takes a string containing the characters // that are treated as whitespace. // // Splits the string along whitespace (where whitespace is the five space // characters defined by HTML 5). Each contiguous block of non-whitespace // characters is added to result. void SplitStringAlongWhitespace(const std::wstring& str, std::vector<std::wstring>* result); // Replace $1-$2-$3 in the format string with |a| and |b| respectively. // Additionally, $$ is replaced by $. The offset/offsets parameter here can be // NULL. std::wstring ReplaceStringPlaceholders(const std::wstring& format_string, const std::wstring& a, size_t* offset); std::wstring ReplaceStringPlaceholders(const std::wstring& format_string, const std::wstring& a, const std::wstring& b, std::vector<size_t>* offsets); std::wstring ReplaceStringPlaceholders(const std::wstring& format_string, const std::wstring& a, const std::wstring& b, const std::wstring& c, std::vector<size_t>* offsets); std::wstring ReplaceStringPlaceholders(const std::wstring& format_string, const std::wstring& a, const std::wstring& b, const std::wstring& c, const std::wstring& d, std::vector<size_t>* offsets); // If the size of |input| is more than |max_len|, this function returns true and // |input| is shortened into |output| by removing chars in the middle (they are // replaced with up to 3 dots, as size permits). // Ex: ElideString(L"Hello", 10, &str) puts Hello in str and returns false. // ElideString(L"Hello my name is Tom", 10, &str) puts "Hell...Tom" in str and // returns true. bool ElideString(const std::wstring& input, int max_len, std::wstring* output); // Returns true if the string passed in matches the pattern. The pattern // string can contain wildcards like * and ? // TODO(iyengar) This function may not work correctly for CJK strings as // it does individual character matches. // The backslash character (\) is an escape character for * and ? bool MatchPattern(const std::wstring& string, const std::wstring& pattern); bool MatchPattern(const std::string& string, const std::string& pattern); #endif // BASE_STRING_UTIL_H_
44.682927
84
0.686513
[ "vector" ]
fa0d1b7b8b1bdde4a67926a54ca6d707a272a257
14,149
h
C
dbms/src/Interpreters/Context.h
189569400/ClickHouse
0b8683c8c9f0e17446bef5498403c39e9cb483b8
[ "Apache-2.0" ]
null
null
null
dbms/src/Interpreters/Context.h
189569400/ClickHouse
0b8683c8c9f0e17446bef5498403c39e9cb483b8
[ "Apache-2.0" ]
null
null
null
dbms/src/Interpreters/Context.h
189569400/ClickHouse
0b8683c8c9f0e17446bef5498403c39e9cb483b8
[ "Apache-2.0" ]
1
2019-11-25T10:32:51.000Z
2019-11-25T10:32:51.000Z
#pragma once #include <functional> #include <memory> #include <Core/Types.h> #include <Core/NamesAndTypes.h> #include <Interpreters/Settings.h> #include <Interpreters/ClientInfo.h> #include <IO/CompressedStream.h> namespace Poco { namespace Net { class IPAddress; } } namespace zkutil { class ZooKeeper; } namespace DB { struct ContextShared; class QuotaForIntervals; class TableFunctionFactory; class AggregateFunctionFactory; class EmbeddedDictionaries; class ExternalDictionaries; class InterserverIOHandler; class BackgroundProcessingPool; class ReshardingWorker; class MergeList; class Cluster; class Compiler; class MarkCache; class UncompressedCache; class ProcessList; struct ProcessListElement; class Macros; struct Progress; class Clusters; class QueryLog; class PartLog; struct MergeTreeSettings; class IDatabase; class DDLGuard; class IStorage; using StoragePtr = std::shared_ptr<IStorage>; using Tables = std::map<String, StoragePtr>; class IAST; using ASTPtr = std::shared_ptr<IAST>; class IBlockInputStream; class IBlockOutputStream; using BlockInputStreamPtr = std::shared_ptr<IBlockInputStream>; using BlockOutputStreamPtr = std::shared_ptr<IBlockOutputStream>; class Block; /// (имя базы данных, имя таблицы) using DatabaseAndTableName = std::pair<String, String>; /// Таблица -> множество таблиц-представлений, которые деляют SELECT из неё. using ViewDependencies = std::map<DatabaseAndTableName, std::set<DatabaseAndTableName>>; using Dependencies = std::vector<DatabaseAndTableName>; /** Набор известных объектов, которые могут быть использованы в запросе. * Состоит из разделяемой части (всегда общей для всех сессий и запросов) * и копируемой части (которая может быть своей для каждой сессии или запроса). * * Всё инкапсулировано для всяких проверок и блокировок. */ class Context { private: using Shared = std::shared_ptr<ContextShared>; Shared shared; ClientInfo client_info; std::shared_ptr<QuotaForIntervals> quota; /// Current quota. By default - empty quota, that have no limits. String current_database; Settings settings; /// Setting for query execution. using ProgressCallback = std::function<void(const Progress & progress)>; ProgressCallback progress_callback; /// Callback for tracking progress of query execution. ProcessListElement * process_list_elem = nullptr; /// For tracking total resource usage for query. String default_format; /// Format, used when server formats data by itself and if query does not have FORMAT specification. /// Thus, used in HTTP interface. If not specified - then some globally default format is used. Tables external_tables; /// Temporary tables. Context * session_context = nullptr; /// Session context or nullptr. Could be equal to this. Context * global_context = nullptr; /// Global context or nullptr. Could be equal to this. using DatabasePtr = std::shared_ptr<IDatabase>; using Databases = std::map<String, std::shared_ptr<IDatabase>>; public: Context(); ~Context(); String getPath() const; String getTemporaryPath() const; String getFlagsPath() const; void setPath(const String & path); void setTemporaryPath(const String & path); void setFlagsPath(const String & path); using ConfigurationPtr = Poco::AutoPtr<Poco::Util::AbstractConfiguration>; /** Забрать список пользователей, квот и профилей настроек из этого конфига. * Список пользователей полностью заменяется. * Накопленные значения у квоты не сбрасываются, если квота не удалена. */ void setUsersConfig(const ConfigurationPtr & config); ConfigurationPtr getUsersConfig(); /// Must be called before getClientInfo. void setUser(const String & name, const String & password, const Poco::Net::SocketAddress & address, const String & quota_key); ClientInfo & getClientInfo() { return client_info; }; const ClientInfo & getClientInfo() const { return client_info; }; void setQuota(const String & name, const String & quota_key, const String & user_name, const Poco::Net::IPAddress & address); QuotaForIntervals & getQuota(); void addDependency(const DatabaseAndTableName & from, const DatabaseAndTableName & where); void removeDependency(const DatabaseAndTableName & from, const DatabaseAndTableName & where); Dependencies getDependencies(const String & database_name, const String & table_name) const; /// Проверка существования таблицы/БД. database может быть пустой - в этом случае используется текущая БД. bool isTableExist(const String & database_name, const String & table_name) const; bool isDatabaseExist(const String & database_name) const; void assertTableExists(const String & database_name, const String & table_name) const; /** Параметр check_database_access_rights существует, чтобы не проверить повторно права доступа к БД, * когда assertTableDoesnExist или assertDatabaseExists вызывается внутри другой функции, которая уже * сделала эту проверку. */ void assertTableDoesntExist(const String & database_name, const String & table_name, bool check_database_acccess_rights = true) const; void assertDatabaseExists(const String & database_name, bool check_database_acccess_rights = true) const; void assertDatabaseDoesntExist(const String & database_name) const; Tables getExternalTables() const; StoragePtr tryGetExternalTable(const String & table_name) const; StoragePtr getTable(const String & database_name, const String & table_name) const; StoragePtr tryGetTable(const String & database_name, const String & table_name) const; void addExternalTable(const String & table_name, StoragePtr storage); void addDatabase(const String & database_name, const DatabasePtr & database); DatabasePtr detachDatabase(const String & database_name); /// Получить объект, который защищает таблицу от одновременного выполнения нескольких DDL операций. /// Если такой объект уже есть - кидается исключение. std::unique_ptr<DDLGuard> getDDLGuard(const String & database, const String & table, const String & message) const; /// Если таблица уже есть - возвращается nullptr, иначе создаётся guard. std::unique_ptr<DDLGuard> getDDLGuardIfTableDoesntExist(const String & database, const String & table, const String & message) const; String getCurrentDatabase() const; String getCurrentQueryId() const; void setCurrentDatabase(const String & name); void setCurrentQueryId(const String & query_id); String getDefaultFormat() const; /// Если default_format не задан - возвращается некоторый глобальный формат по-умолчанию. void setDefaultFormat(const String & name); const Macros & getMacros() const; void setMacros(Macros && macros); Settings getSettings() const; void setSettings(const Settings & settings_); Limits getLimits() const; /// Установить настройку по имени. void setSetting(const String & name, const Field & value); /// Установить настройку по имени. Прочитать значение в текстовом виде из строки (например, из конфига, или из параметра URL). void setSetting(const String & name, const std::string & value); const TableFunctionFactory & getTableFunctionFactory() const; const AggregateFunctionFactory & getAggregateFunctionFactory() const; const EmbeddedDictionaries & getEmbeddedDictionaries() const; const ExternalDictionaries & getExternalDictionaries() const; void tryCreateEmbeddedDictionaries() const; void tryCreateExternalDictionaries() const; /// Форматы ввода-вывода. BlockInputStreamPtr getInputFormat(const String & name, ReadBuffer & buf, const Block & sample, size_t max_block_size) const; BlockOutputStreamPtr getOutputFormat(const String & name, WriteBuffer & buf, const Block & sample) const; InterserverIOHandler & getInterserverIOHandler(); /// Как другие серверы могут обратиться к этому для скачивания реплицируемых данных. void setInterserverIOAddress(const String & host, UInt16 port); std::pair<String, UInt16> getInterserverIOAddress() const; /// Порт, который сервер слушает для выполнения SQL-запросов. UInt16 getTCPPort() const; /// Получить запрос на CREATE таблицы. ASTPtr getCreateQuery(const String & database_name, const String & table_name) const; const DatabasePtr getDatabase(const String & database_name) const; DatabasePtr getDatabase(const String & database_name); const DatabasePtr tryGetDatabase(const String & database_name) const; DatabasePtr tryGetDatabase(const String & database_name); const Databases getDatabases() const; Databases getDatabases(); /// For methods below you may need to acquire a lock by yourself. std::unique_lock<Poco::Mutex> getLock() const; const Context & getSessionContext() const; Context & getSessionContext(); const Context & getGlobalContext() const; Context & getGlobalContext(); void setSessionContext(Context & context_) { session_context = &context_; } void setGlobalContext(Context & context_) { global_context = &context_; } const Settings & getSettingsRef() const { return settings; }; Settings & getSettingsRef() { return settings; }; void setProgressCallback(ProgressCallback callback); /// Используется в InterpreterSelectQuery, чтобы передать его в IProfilingBlockInputStream. ProgressCallback getProgressCallback() const; /** Устанавливается в executeQuery и InterpreterSelectQuery. Затем используется в IProfilingBlockInputStream, * чтобы обновлять и контролировать информацию об общем количестве потраченных на запрос ресурсов. */ void setProcessListElement(ProcessListElement * elem); /// Может вернуть nullptr, если запрос не был вставлен в ProcessList. ProcessListElement * getProcessListElement(); /// Список всех запросов. ProcessList & getProcessList(); const ProcessList & getProcessList() const; MergeList & getMergeList(); const MergeList & getMergeList() const; /// Создать кэш разжатых блоков указанного размера. Это можно сделать только один раз. void setUncompressedCache(size_t max_size_in_bytes); std::shared_ptr<UncompressedCache> getUncompressedCache() const; void setZooKeeper(std::shared_ptr<zkutil::ZooKeeper> zookeeper); /// Если в момент вызова текущая сессия просрочена, синхронно создает и возвращает новую вызовом startNewSession(). std::shared_ptr<zkutil::ZooKeeper> getZooKeeper() const; /// Создать кэш засечек указанного размера. Это можно сделать только один раз. void setMarkCache(size_t cache_size_in_bytes); std::shared_ptr<MarkCache> getMarkCache() const; BackgroundProcessingPool & getBackgroundPool(); void setReshardingWorker(std::shared_ptr<ReshardingWorker> resharding_worker); ReshardingWorker & getReshardingWorker(); /** Очистить кэши разжатых блоков и засечек. * Обычно это делается при переименовании таблиц, изменении типа столбцов, удалении таблицы. * - так как кэши привязаны к именам файлов, и становятся некорректными. * (при удалении таблицы - нужно, так как на её месте может появиться другая) * const - потому что изменение кэша не считается существенным. */ void resetCaches() const; Clusters & getClusters() const; std::shared_ptr<Cluster> getCluster(const std::string & cluster_name) const; std::shared_ptr<Cluster> tryGetCluster(const std::string & cluster_name) const; void setClustersConfig(const ConfigurationPtr & config); Compiler & getCompiler(); QueryLog & getQueryLog(); std::shared_ptr<PartLog> getPartLog(); const MergeTreeSettings & getMergeTreeSettings(); /// Prevents DROP TABLE if its size is greater than max_size (50GB by default, max_size=0 turn off this check) void setMaxTableSizeToDrop(size_t max_size); void checkTableCanBeDropped(const String & database, const String & table, size_t table_size); /// Позволяет выбрать метод сжатия по условиям, описанным в конфигурационном файле. CompressionMethod chooseCompressionMethod(size_t part_size, double part_size_ratio) const; /// Получить аптайм сервера в секундах. time_t getUptimeSeconds() const; void shutdown(); enum class ApplicationType { SERVER, /// The program is run as clickhouse-server daemon (default behavior) CLIENT, /// clickhouse-client LOCAL_SERVER /// clickhouse-local }; ApplicationType getApplicationType() const; void setApplicationType(ApplicationType type); /// Set once String getDefaultProfileName() const; void setDefaultProfileName(const String & name); private: /** Проверить, имеет ли текущий клиент доступ к заданной базе данных. * Если доступ запрещён, кинуть исключение. * NOTE: Этот метод надо всегда вызывать при захваченном мьютексе shared->mutex. */ void checkDatabaseAccessRights(const std::string & database_name) const; const EmbeddedDictionaries & getEmbeddedDictionariesImpl(bool throw_on_error) const; const ExternalDictionaries & getExternalDictionariesImpl(bool throw_on_error) const; StoragePtr getTableImpl(const String & database_name, const String & table_name, Exception * exception) const; }; /// Puts an element into the map, erases it in the destructor. /// If the element already exists in the map, throws an exception containing provided message. class DDLGuard { public: /// Element name -> message. /// NOTE: using std::map here (and not std::unordered_map) to avoid iterator invalidation on insertion. using Map = std::map<String, String>; DDLGuard(Map & map_, std::mutex & mutex_, std::unique_lock<std::mutex> && lock, const String & elem, const String & message); ~DDLGuard(); private: Map & map; Map::iterator it; std::mutex & mutex; }; }
40.658046
138
0.738003
[ "vector" ]
fa0dc426ca37650770ab908f6ade7d870771386e
6,954
h
C
3rdParty/rocksdb/v5.6.X/include/rocksdb/perf_context.h
Deckhandfirststar01/arangodb
a8c079252f9c7127ef6860f5ad46ec38055669ce
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
3rdParty/rocksdb/v5.6.X/include/rocksdb/perf_context.h
Deckhandfirststar01/arangodb
a8c079252f9c7127ef6860f5ad46ec38055669ce
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
3rdParty/rocksdb/v5.6.X/include/rocksdb/perf_context.h
Deckhandfirststar01/arangodb
a8c079252f9c7127ef6860f5ad46ec38055669ce
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #ifndef STORAGE_ROCKSDB_INCLUDE_PERF_CONTEXT_H #define STORAGE_ROCKSDB_INCLUDE_PERF_CONTEXT_H #include <stdint.h> #include <string> #include "rocksdb/perf_level.h" namespace rocksdb { // A thread local context for gathering performance counter efficiently // and transparently. // Use SetPerfLevel(PerfLevel::kEnableTime) to enable time stats. struct PerfContext { void Reset(); // reset all performance counters to zero std::string ToString(bool exclude_zero_counters = false) const; uint64_t user_key_comparison_count; // total number of user key comparisons uint64_t block_cache_hit_count; // total number of block cache hits uint64_t block_read_count; // total number of block reads (with IO) uint64_t block_read_byte; // total number of bytes from block reads uint64_t block_read_time; // total nanos spent on block reads uint64_t block_checksum_time; // total nanos spent on block checksum uint64_t block_decompress_time; // total nanos spent on block decompression // total number of internal keys skipped over during iteration. // There are several reasons for it: // 1. when calling Next(), the iterator is in the position of the previous // key, so that we'll need to skip it. It means this counter will always // be incremented in Next(). // 2. when calling Next(), we need to skip internal entries for the previous // keys that are overwritten. // 3. when calling Next(), Seek() or SeekToFirst(), after previous key // before calling Next(), the seek key in Seek() or the beginning for // SeekToFirst(), there may be one or more deleted keys before the next // valid key that the operation should place the iterator to. We need // to skip both of the tombstone and updates hidden by the tombstones. The // tombstones are not included in this counter, while previous updates // hidden by the tombstones will be included here. // 4. symmetric cases for Prev() and SeekToLast() // internal_recent_skipped_count is not included in this counter. // uint64_t internal_key_skipped_count; // Total number of deletes and single deletes skipped over during iteration // When calling Next(), Seek() or SeekToFirst(), after previous position // before calling Next(), the seek key in Seek() or the beginning for // SeekToFirst(), there may be one or more deleted keys before the next valid // key. Every deleted key is counted once. We don't recount here if there are // still older updates invalidated by the tombstones. // uint64_t internal_delete_skipped_count; // How many times iterators skipped over internal keys that are more recent // than the snapshot that iterator is using. // uint64_t internal_recent_skipped_count; // How many values were fed into merge operator by iterators. // uint64_t internal_merge_count; uint64_t get_snapshot_time; // total nanos spent on getting snapshot uint64_t get_from_memtable_time; // total nanos spent on querying memtables uint64_t get_from_memtable_count; // number of mem tables queried // total nanos spent after Get() finds a key uint64_t get_post_process_time; uint64_t get_from_output_files_time; // total nanos reading from output files // total nanos spent on seeking memtable uint64_t seek_on_memtable_time; // number of seeks issued on memtable // (including SeekForPrev but not SeekToFirst and SeekToLast) uint64_t seek_on_memtable_count; // number of Next()s issued on memtable uint64_t next_on_memtable_count; // number of Prev()s issued on memtable uint64_t prev_on_memtable_count; // total nanos spent on seeking child iters uint64_t seek_child_seek_time; // number of seek issued in child iterators uint64_t seek_child_seek_count; uint64_t seek_min_heap_time; // total nanos spent on the merge min heap uint64_t seek_max_heap_time; // total nanos spent on the merge max heap // total nanos spent on seeking the internal entries uint64_t seek_internal_seek_time; // total nanos spent on iterating internal entries to find the next user entry uint64_t find_next_user_entry_time; // total nanos spent on writing to WAL uint64_t write_wal_time; // total nanos spent on writing to mem tables uint64_t write_memtable_time; // total nanos spent on delaying write uint64_t write_delay_time; // total nanos spent on writing a record, excluding the above three times uint64_t write_pre_and_post_process_time; uint64_t db_mutex_lock_nanos; // time spent on acquiring DB mutex. // Time spent on waiting with a condition variable created with DB mutex. uint64_t db_condition_wait_nanos; // Time spent on merge operator. uint64_t merge_operator_time_nanos; // Time spent on reading index block from block cache or SST file uint64_t read_index_block_nanos; // Time spent on reading filter block from block cache or SST file uint64_t read_filter_block_nanos; // Time spent on creating data block iterator uint64_t new_table_block_iter_nanos; // Time spent on creating a iterator of an SST file. uint64_t new_table_iterator_nanos; // Time spent on seeking a key in data/index blocks uint64_t block_seek_nanos; // Time spent on finding or creating a table reader uint64_t find_table_nanos; // total number of mem table bloom hits uint64_t bloom_memtable_hit_count; // total number of mem table bloom misses uint64_t bloom_memtable_miss_count; // total number of SST table bloom hits uint64_t bloom_sst_hit_count; // total number of SST table bloom misses uint64_t bloom_sst_miss_count; // Total time spent in Env filesystem operations. These are only populated // when TimedEnv is used. uint64_t env_new_sequential_file_nanos; uint64_t env_new_random_access_file_nanos; uint64_t env_new_writable_file_nanos; uint64_t env_reuse_writable_file_nanos; uint64_t env_new_random_rw_file_nanos; uint64_t env_new_directory_nanos; uint64_t env_file_exists_nanos; uint64_t env_get_children_nanos; uint64_t env_get_children_file_attributes_nanos; uint64_t env_delete_file_nanos; uint64_t env_create_dir_nanos; uint64_t env_create_dir_if_missing_nanos; uint64_t env_delete_dir_nanos; uint64_t env_get_file_size_nanos; uint64_t env_get_file_modification_time_nanos; uint64_t env_rename_file_nanos; uint64_t env_link_file_nanos; uint64_t env_lock_file_nanos; uint64_t env_unlock_file_nanos; uint64_t env_new_logger_nanos; }; // Get Thread-local PerfContext object pointer // if defined(NPERF_CONTEXT), then the pointer is not thread-local PerfContext* get_perf_context(); } #endif
43.192547
80
0.770779
[ "object" ]
fa0f7936e315873657bdff7bad005ea97a15c9d7
8,388
h
C
service_apis/calendar/google/calendar_api/free_busy_request.h
jeramy-chen/google-api-cpp-client
27fee6855ab0e40e718cbba5738a259cee8c9bda
[ "Apache-2.0" ]
264
2015-01-20T12:08:14.000Z
2022-03-28T17:58:30.000Z
service_apis/calendar/google/calendar_api/free_busy_request.h
jeramy-chen/google-api-cpp-client
27fee6855ab0e40e718cbba5738a259cee8c9bda
[ "Apache-2.0" ]
52
2015-01-01T10:25:31.000Z
2019-06-26T21:40:40.000Z
service_apis/calendar/google/calendar_api/free_busy_request.h
jeramy-chen/google-api-cpp-client
27fee6855ab0e40e718cbba5738a259cee8c9bda
[ "Apache-2.0" ]
126
2015-01-03T05:39:20.000Z
2022-02-08T06:52:10.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. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Calendar API (calendar/v3) // Generated from: // Version: v3 // Revision: 20171010 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.5 #ifndef GOOGLE_CALENDAR_API_FREE_BUSY_REQUEST_H_ #define GOOGLE_CALENDAR_API_FREE_BUSY_REQUEST_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/calendar_api/free_busy_request_item.h" namespace Json { class Value; } // namespace Json namespace google_calendar_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class FreeBusyRequest : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static FreeBusyRequest* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FreeBusyRequest(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FreeBusyRequest(Json::Value* storage); /** * Standard destructor. */ virtual ~FreeBusyRequest(); /** * Returns a string denoting the type of this data object. * * @return <code>google_calendar_api::FreeBusyRequest</code> */ const char* GetTypeName() const { return "google_calendar_api::FreeBusyRequest"; } /** * Determine if the '<code>calendarExpansionMax</code>' attribute was set. * * @return true if the '<code>calendarExpansionMax</code>' attribute was set. */ bool has_calendar_expansion_max() const { return Storage().isMember("calendarExpansionMax"); } /** * Clears the '<code>calendarExpansionMax</code>' attribute. */ void clear_calendar_expansion_max() { MutableStorage()->removeMember("calendarExpansionMax"); } /** * Get the value of the '<code>calendarExpansionMax</code>' attribute. */ int32 get_calendar_expansion_max() const { const Json::Value& storage = Storage("calendarExpansionMax"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>calendarExpansionMax</code>' attribute. * * Maximal number of calendars for which FreeBusy information is to be * provided. Optional. * * @param[in] value The new value. */ void set_calendar_expansion_max(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("calendarExpansionMax")); } /** * Determine if the '<code>groupExpansionMax</code>' attribute was set. * * @return true if the '<code>groupExpansionMax</code>' attribute was set. */ bool has_group_expansion_max() const { return Storage().isMember("groupExpansionMax"); } /** * Clears the '<code>groupExpansionMax</code>' attribute. */ void clear_group_expansion_max() { MutableStorage()->removeMember("groupExpansionMax"); } /** * Get the value of the '<code>groupExpansionMax</code>' attribute. */ int32 get_group_expansion_max() const { const Json::Value& storage = Storage("groupExpansionMax"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>groupExpansionMax</code>' attribute. * * Maximal number of calendar identifiers to be provided for a single group. * Optional. An error will be returned for a group with more members than this * value. * * @param[in] value The new value. */ void set_group_expansion_max(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("groupExpansionMax")); } /** * Determine if the '<code>items</code>' attribute was set. * * @return true if the '<code>items</code>' attribute was set. */ bool has_items() const { return Storage().isMember("items"); } /** * Clears the '<code>items</code>' attribute. */ void clear_items() { MutableStorage()->removeMember("items"); } /** * Get a reference to the value of the '<code>items</code>' attribute. */ const client::JsonCppArray<FreeBusyRequestItem > get_items() const; /** * Gets a reference to a mutable value of the '<code>items</code>' property. * * List of calendars and/or groups to query. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<FreeBusyRequestItem > mutable_items(); /** * Determine if the '<code>timeMax</code>' attribute was set. * * @return true if the '<code>timeMax</code>' attribute was set. */ bool has_time_max() const { return Storage().isMember("timeMax"); } /** * Clears the '<code>timeMax</code>' attribute. */ void clear_time_max() { MutableStorage()->removeMember("timeMax"); } /** * Get the value of the '<code>timeMax</code>' attribute. */ client::DateTime get_time_max() const { const Json::Value& storage = Storage("timeMax"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>timeMax</code>' attribute. * * The end of the interval for the query. * * @param[in] value The new value. */ void set_time_max(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("timeMax")); } /** * Determine if the '<code>timeMin</code>' attribute was set. * * @return true if the '<code>timeMin</code>' attribute was set. */ bool has_time_min() const { return Storage().isMember("timeMin"); } /** * Clears the '<code>timeMin</code>' attribute. */ void clear_time_min() { MutableStorage()->removeMember("timeMin"); } /** * Get the value of the '<code>timeMin</code>' attribute. */ client::DateTime get_time_min() const { const Json::Value& storage = Storage("timeMin"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>timeMin</code>' attribute. * * The start of the interval for the query. * * @param[in] value The new value. */ void set_time_min(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("timeMin")); } /** * Determine if the '<code>timeZone</code>' attribute was set. * * @return true if the '<code>timeZone</code>' attribute was set. */ bool has_time_zone() const { return Storage().isMember("timeZone"); } /** * Clears the '<code>timeZone</code>' attribute. */ void clear_time_zone() { MutableStorage()->removeMember("timeZone"); } /** * Get the value of the '<code>timeZone</code>' attribute. */ const StringPiece get_time_zone() const { const Json::Value& v = Storage("timeZone"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>timeZone</code>' attribute. * * Time zone used in the response. Optional. The default is UTC. * * @param[in] value The new value. */ void set_time_zone(const StringPiece& value) { *MutableStorage("timeZone") = value.data(); } private: void operator=(const FreeBusyRequest&); }; // FreeBusyRequest } // namespace google_calendar_api #endif // GOOGLE_CALENDAR_API_FREE_BUSY_REQUEST_H_
27.058065
80
0.669289
[ "object" ]
fa1150bc6577afb3fff4db25ec7bd11078d0823a
8,313
h
C
include/mysqlx/common_constants.h
dveeden/mysql-connector-cpp
7abcdc88c8235f02096e21b5bcd72e8312508f61
[ "Artistic-1.0-Perl" ]
null
null
null
include/mysqlx/common_constants.h
dveeden/mysql-connector-cpp
7abcdc88c8235f02096e21b5bcd72e8312508f61
[ "Artistic-1.0-Perl" ]
null
null
null
include/mysqlx/common_constants.h
dveeden/mysql-connector-cpp
7abcdc88c8235f02096e21b5bcd72e8312508f61
[ "Artistic-1.0-Perl" ]
null
null
null
/* * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, as * published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, * as designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an * additional permission to link the program and your derivative works * with the separately licensed software that they have included with * MySQL. * * Without limiting anything contained in the foregoing, this file, * which is part of MySQL Connector/C++, is also subject to the * Universal FOSS Exception, version 1.0, a copy of which can be found at * http://oss.oracle.com/licenses/universal-foss-exception. * * 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, version 2.0, for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MYSQL_COMMON_CONSTANTS_H #define MYSQL_COMMON_CONSTANTS_H #define DEFAULT_MYSQL_PORT 3306 #define DEFAULT_MYSQLX_PORT 33060 // ---------------------------------------------------------------------------- /* Common constants ================ Warning: Values of these constants are part of the public API. Changing them is a non backward compatible API change. Note: Value of 0 is reserved for special uses and thus constant values are always > 0. */ /* Note: the empty END_LIST macro at the end of list macros helps Doxygen correctly interpret documentation for the list item. */ #undef END_LIST #define END_LIST #define SESSION_OPTION_LIST(x) \ OPT_STR(x,URI,1) /*!< connection URI or string */ \ /*! DNS name of the host, IPv4 address or IPv6 address */ \ OPT_STR(x,HOST,2) \ OPT_NUM(x,PORT,3) /*!< X Plugin port to connect to */ \ /*! Assign a priority (a number in range 1 to 100) to the last specified host; these priorities are used to determine the order in which multiple hosts are tried by the connection fail-over logic (see description of `Session` class) */ \ OPT_NUM(x,PRIORITY,4) \ OPT_STR(x,USER,5) /*!< user name */ \ OPT_STR(x,PWD,6) /*!< password */ \ OPT_STR(x,DB,7) /*!< default database */ \ OPT_ANY(x,SSL_MODE,8) /*!< define `SSLMode` option to be used */ \ /*! path to a PEM file specifying trusted root certificates*/ \ OPT_STR(x,SSL_CA,9) \ OPT_ANY(x,AUTH,10) /*!< authentication method, PLAIN, MYSQL41, etc.*/ \ OPT_STR(x,SOCKET,11) END_LIST #define OPT_STR(X,Y,N) X##_str(Y,N) #define OPT_NUM(X,Y,N) X##_num(Y,N) #define OPT_ANY(X,Y,N) X##_any(Y,N) /* Names for options supported in the query part of a connection string and how they map to session options above. */ #define URI_OPTION_LIST(X) \ X("ssl-mode", SSL_MODE) \ X("ssl-ca", SSL_CA) \ X("auth", AUTH) \ END_LIST #define SSL_MODE_LIST(x) \ x(DISABLED,1) /*!< Establish an unencrypted connection. */ \ x(REQUIRED,2) /*!< Establish a secure connection if the server supports secure connections. The connection attempt fails if a secure connection cannot be established. This is the default if `SSL_MODE` is not specified. */ \ x(VERIFY_CA,3) /*!< Like `REQUIRED`, but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates (defined by `SSL_CA` Option). The connection attempt fails if no valid matching CA certificates are found.*/ \ x(VERIFY_IDENTITY,4) /*!< Like `VERIFY_CA`, but additionally verify that the server certificate matches the host to which the connection is attempted.*/\ END_LIST #define AUTH_METHOD_LIST(x)\ x(PLAIN,1) /*!< Plain text authentication method. The password is sent as a clear text. This method is used by default in encrypted connections. */ \ x(MYSQL41,2) /*!< Authentication method supported by MySQL 4.1 and newer. The password is hashed before being sent to the server. This authentication method works over unencrypted connections */ \ x(EXTERNAL,3) /*!< External authentication when the server establishes the user authenticity by other means such as SSL/x509 certificates. Currently not supported by X Plugin */ \ x(SHA256_MEMORY,4) /*!< Authentication using SHA256 password hashes stored in server-side cache. This authentication method works over unencrypted connections. */ \ END_LIST /* Types that can be reported by MySQL server. */ #define RESULT_TYPE_LIST(X) \ X(BIT, 1) \ X(TINYINT, 2) \ X(SMALLINT, 3) \ X(MEDIUMINT, 4) \ X(INT, 5) \ X(BIGINT, 6) \ X(FLOAT, 7) \ X(DECIMAL, 8) \ X(DOUBLE, 9) \ X(JSON, 10) \ X(STRING, 11) \ X(BYTES, 12) \ X(TIME, 13) \ X(DATE, 14) \ X(DATETIME, 15) \ X(TIMESTAMP, 16) \ X(SET, 17) \ X(ENUM, 18) \ X(GEOMETRY, 19) \ END_LIST /* Check options for an updatable view. @see https://dev.mysql.com/doc/refman/en/view-check-option.html */ #define VIEW_CHECK_OPTION_LIST(x) \ x(CASCADED,1) \ x(LOCAL,2) \ END_LIST /* Algorithms used to process views. @see https://dev.mysql.com/doc/refman/en/view-algorithms.html */ #define VIEW_ALGORITHM_LIST(x) \ x(UNDEFINED,1) \ x(MERGE,2) \ x(TEMPTABLE,3) \ END_LIST /* View security settings. @see https://dev.mysql.com/doc/refman/en/stored-programs-security.html */ #define VIEW_SECURITY_LIST(x) \ x(DEFINER,1) \ x(INVOKER,2) \ END_LIST #define LOCK_MODE_LIST(X) \ X(SHARED,1) /*!< Sets a shared mode lock on any rows that are read. Other sessions can read the rows, but cannot modify them until your transaction commits. If any of these rows were changed by another transaction that has not yet committed, your query waits until that transaction ends and then uses the latest values. */ \ X(EXCLUSIVE,2) /*!< For index records the search encounters, locks the rows and any associated index entries, the same as if you issued an UPDATE statement for those rows. Other transactions are blocked from updating those rows, from doing locking in LOCK_SHARED, or from reading the data in certain transaction isolation levels. */ \ END_LIST #define LOCK_CONTENTION_LIST(X) \ X(DEFAULT,0) /*!< Block query until existing row locks are released. */ \ X(NOWAIT,1) /*!< Return error if lock could not be obtained immediately. */ \ X(SKIP_LOCKED,2) /*!< Execute query immediately, excluding items that are locked from the query results. */ \ END_LIST // ---------------------------------------------------------------------------- #endif
38.308756
80
0.587032
[ "geometry" ]
fa1a0664b30c90f59371f45f2eeb8f21e8b36d82
5,554
h
C
include/oboe/AudioStreamBase.h
ShariqM/oboe-358
9c368ed83663f3ecc022ca7762c6758e66c369e9
[ "Apache-2.0" ]
547
2019-04-07T14:34:01.000Z
2022-03-25T08:58:50.000Z
include/oboe/AudioStreamBase.h
ShariqM/oboe-358
9c368ed83663f3ecc022ca7762c6758e66c369e9
[ "Apache-2.0" ]
514
2018-03-22T00:31:38.000Z
2019-04-06T21:16:45.000Z
include/oboe/AudioStreamBase.h
ShariqM/oboe-358
9c368ed83663f3ecc022ca7762c6758e66c369e9
[ "Apache-2.0" ]
120
2019-04-15T18:36:25.000Z
2022-03-03T01:11:34.000Z
/* * Copyright 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef OBOE_STREAM_BASE_H_ #define OBOE_STREAM_BASE_H_ #include <memory> #include "oboe/AudioStreamCallback.h" #include "oboe/Definitions.h" namespace oboe { /** * Base class containing parameters for audio streams and builders. **/ class AudioStreamBase { public: AudioStreamBase() {} virtual ~AudioStreamBase() = default; // This class only contains primitives so we can use default constructor and copy methods. /** * Default copy constructor */ AudioStreamBase(const AudioStreamBase&) = default; /** * Default assignment operator */ AudioStreamBase& operator=(const AudioStreamBase&) = default; /** * @return number of channels, for example 2 for stereo, or kUnspecified */ int32_t getChannelCount() const { return mChannelCount; } /** * @return Direction::Input or Direction::Output */ Direction getDirection() const { return mDirection; } /** * @return sample rate for the stream or kUnspecified */ int32_t getSampleRate() const { return mSampleRate; } /** * @return the number of frames in each callback or kUnspecified. */ int32_t getFramesPerCallback() const { return mFramesPerCallback; } /** * @return the audio sample format (e.g. Float or I16) */ AudioFormat getFormat() const { return mFormat; } /** * Query the maximum number of frames that can be filled without blocking. * If the stream has been closed the last known value will be returned. * * @return buffer size */ virtual int32_t getBufferSizeInFrames() { return mBufferSizeInFrames; } /** * @return capacityInFrames or kUnspecified */ virtual int32_t getBufferCapacityInFrames() const { return mBufferCapacityInFrames; } /** * @return the sharing mode of the stream. */ SharingMode getSharingMode() const { return mSharingMode; } /** * @return the performance mode of the stream. */ PerformanceMode getPerformanceMode() const { return mPerformanceMode; } /** * @return the device ID of the stream. */ int32_t getDeviceId() const { return mDeviceId; } /** * @return the callback object for this stream, if set. */ AudioStreamCallback* getCallback() const { return mStreamCallback; } /** * @return the usage for this stream. */ Usage getUsage() const { return mUsage; } /** * @return the stream's content type. */ ContentType getContentType() const { return mContentType; } /** * @return the stream's input preset. */ InputPreset getInputPreset() const { return mInputPreset; } /** * @return the stream's session ID allocation strategy (None or Allocate). */ SessionId getSessionId() const { return mSessionId; } protected: /** The callback which will be fired when new data is ready to be read/written **/ AudioStreamCallback *mStreamCallback = nullptr; /** Number of audio frames which will be requested in each callback */ int32_t mFramesPerCallback = kUnspecified; /** Stream channel count */ int32_t mChannelCount = kUnspecified; /** Stream sample rate */ int32_t mSampleRate = kUnspecified; /** Stream audio device ID */ int32_t mDeviceId = kUnspecified; /** Stream buffer capacity specified as a number of audio frames */ int32_t mBufferCapacityInFrames = kUnspecified; /** Stream buffer size specified as a number of audio frames */ int32_t mBufferSizeInFrames = kUnspecified; /** * Number of frames which will be copied to/from the audio device in a single read/write * operation */ int32_t mFramesPerBurst = kUnspecified; /** Stream sharing mode */ SharingMode mSharingMode = SharingMode::Shared; /** Format of audio frames */ AudioFormat mFormat = AudioFormat::Unspecified; /** Stream direction */ Direction mDirection = Direction::Output; /** Stream performance mode */ PerformanceMode mPerformanceMode = PerformanceMode::None; /** Stream usage. Only active on Android 28+ */ Usage mUsage = Usage::Media; /** Stream content type. Only active on Android 28+ */ ContentType mContentType = ContentType::Music; /** Stream input preset. Only active on Android 28+ */ InputPreset mInputPreset = InputPreset::VoiceRecognition; /** Stream session ID allocation strategy. Only active on Android 28+ */ SessionId mSessionId = SessionId::None; }; } // namespace oboe #endif /* OBOE_STREAM_BASE_H_ */
32.290698
94
0.634318
[ "object" ]
fa1dcc89e5ee0fa113c34765b5291e754e81a532
8,309
h
C
src/connectivity/bluetooth/core/bt-host/common/inspectable.h
Prajwal-Koirala/fuchsia
ca7ae6c143cd4c10bad9aa1869ffcc24c3e4b795
[ "BSD-2-Clause" ]
4
2020-02-23T09:02:06.000Z
2022-01-08T17:06:28.000Z
src/connectivity/bluetooth/core/bt-host/common/inspectable.h
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
src/connectivity/bluetooth/core/bt-host/common/inspectable.h
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
1
2021-08-23T11:33:57.000Z
2021-08-23T11:33:57.000Z
// Copyright 2020 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. #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_INSPECTABLE_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_INSPECTABLE_H_ #include <lib/fit/function.h> #include <lib/inspect/cpp/vmo/types.h> #include <lib/sys/inspect/cpp/component.h> #include <zircon/assert.h> #include <iterator> #include <string> #include <type_traits> #include <fbl/macros.h> namespace bt { // InspectableGuard is returned by |Inspectable::Mutable()|. // It will update the corresponding Inspect property when it is destroyed. // Therefore, the lifetime of InspectableGuard should usually be that of a temporary, or be scoped // for a single update. // // InspectableGuard's primary use cases are calling non-const methods on objects and assigning // member variable values in structs. // // Example: // StringInspectable<hci_spec::LMPFeatureSet> lmp_features; // lmp_features.Mutable()->SetPage(page, features); template <typename ValueT> class InspectableGuard { public: InspectableGuard(ValueT& value, fit::closure update_cb) : value_(value), update_cb_(std::move(update_cb)) {} ~InspectableGuard() { update_cb_(); } ValueT& operator*() { return value_; } ValueT* operator->() { return &value_; } private: ValueT& value_; fit::closure update_cb_; DISALLOW_COPY_ASSIGN_AND_MOVE(InspectableGuard); }; // Inspectable is a utility class for keeping inspected values in sync with their corresponding // Inspect property. // // PropertyT must be an Inspect property type such that PropertyT::Set(PropertyInnerT) is valid. // PropertyInnerT corresponds to the type contained in PropertyT (e.g. string is contained by // inspect::StringProperty). // // Example: // inspect::Inspector inspector; // auto& root = inspector.GetRoot(); // Inspectable inspectable(std::string("A"), root.CreateString("property_name", "foo")); // // // Hierarchy: { root: property_name: "A" } // // inspectable.Set("B"); // // // Hierarchy: { root: property_name: "B" } template <typename ValueT, typename PropertyT, typename PropertyInnerT = ValueT> class Inspectable { public: // When the desired property type DOES NOT match ValueT, a conversion function |convert| is // necessary. This is often the case when using optionals or when converting a number/enum into a // string is desired. Example: // auto convert = [](std::optional<hci_spec::HCIVersion> version) -> std::string { // return version ? HCIVersionToString(*version) : "null"; // }; // Inspectable<std::optional<HCIVersion>> hci_version( // HCIVersion::k5_0, // inspect_node.CreateString("hci", ""), // convert); using ConvertFunction = fit::function<PropertyInnerT(const ValueT&)>; Inspectable(ValueT initial_value, PropertyT property, ConvertFunction convert = Inspectable::DefaultConvert) : value_(std::move(initial_value)), property_(std::move(property)), convert_(std::move(convert)) { // Update property immediately to ensure consistency between property and initial value. UpdateProperty(); } // Construct with null property (updates will be no-ops). explicit Inspectable(ValueT initial_value, ConvertFunction convert = &Inspectable::DefaultConvert) : value_(std::move(initial_value)), convert_(std::move(convert)) {} // Construct with null property and with default value for ValueT. explicit Inspectable(ConvertFunction convert = &Inspectable::DefaultConvert) : Inspectable(ValueT(), std::move(convert)) { static_assert(std::is_default_constructible<ValueT>(), "ValueT is not default constructable"); } Inspectable(Inspectable&&) = default; Inspectable& operator=(Inspectable&&) = default; virtual ~Inspectable() = default; const ValueT& value() const { return value_; } const ValueT& operator*() const { return value_; } const ValueT* operator->() const { return &value_; } // Update value and property. This is the ONLY place the value should be updated directly. const ValueT& Set(const ValueT& value) { value_ = value; UpdateProperty(); return value_; } void SetProperty(PropertyT property) { property_ = std::move(property); UpdateProperty(); } virtual void AttachInspect(inspect::Node& node, std::string name) { ZX_ASSERT_MSG(false, "AttachInspect not implemented for PropertyT"); } // Returns a InspectableGuard wrapper around the contained value that allows for non-const methods // to be called. The returned value should only be used as a temporary. InspectableGuard<ValueT> Mutable() { return InspectableGuard(value_, fit::bind_member(this, &Inspectable::UpdateProperty)); } static PropertyInnerT DefaultConvert(const ValueT& value) { return value; } private: void UpdateProperty() { property_.Set(convert_(value_)); } ValueT value_; PropertyT property_; ConvertFunction convert_; static_assert(!std::is_pointer_v<ValueT>, "Pointer passed to Inspectable"); static_assert(!std::is_reference_v<ValueT>, "Reference passed to Inspectable"); DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(Inspectable); }; // Convenience Inspectable types: #define CREATE_INSPECTABLE_TYPE(property_t, inner_t) \ template <typename ValueT> \ class property_t##Inspectable \ : public Inspectable<ValueT, inspect::property_t##Property, inner_t> { \ public: \ using Inspectable<ValueT, inspect::property_t##Property, inner_t>::Inspectable; \ void AttachInspect(inspect::Node& node, std::string name) override { \ this->SetProperty(node.Create##property_t(name, inner_t())); \ } \ }; \ template <typename ValueT> \ property_t##Inspectable(ValueT, ...)->property_t##Inspectable<ValueT> CREATE_INSPECTABLE_TYPE(Int, int64_t); CREATE_INSPECTABLE_TYPE(Uint, uint64_t); CREATE_INSPECTABLE_TYPE(Bool, bool); CREATE_INSPECTABLE_TYPE(String, std::string); // A common practice in the Bluetooth stack is to define ToString() for classes. // MakeToStringInspectConvertFunction allows these classes to be used with StringInspectable. // Example: // class Foo { // public: // std::string ToString() { ... } // }; // // StringInspectable foo(Foo(), inspect_node.CreateString("foo", ""), // MakeToStringInspectConvertFunction()); inline auto MakeToStringInspectConvertFunction() { return [](auto value) { return value.ToString(); }; } // Similar to ToStringInspectable, but for containers of types that implement ToString(). The // resulting string property will be formatted using the ContainerOfToStringOptions provided. // Example: // std::vector<Foo> values(2); // StringInspectable foo(std::move(values), inspect_node.CreateString("foo", ""), // MakeContainerOfToStringInspectConvertFunction()); // // This does not generate an node hierarchy based on the container contents and is more appropriate // for sequential containers at leaves of the inspect tree. More complex data structures, especially // associative ones, should export full inspect trees. struct ContainerOfToStringOptions { const char* prologue = "{ "; const char* delimiter = ", "; const char* epilogue = " }"; }; inline auto MakeContainerOfToStringConvertFunction(ContainerOfToStringOptions options = {}) { return [options](auto value) { std::string out(options.prologue); for (auto iter = std::begin(value); iter != std::end(value); std::advance(iter, 1)) { out += iter->ToString(); if (std::next(iter) == std::end(value)) { continue; } out += options.delimiter; } out += options.epilogue; return out; }; } } // namespace bt #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_COMMON_INSPECTABLE_H_
38.827103
100
0.682032
[ "vector" ]
fa1e3f9ea872b6e31338b21faa810e1b79d6f750
3,665
h
C
aws-cpp-sdk-workspaces-web/include/aws/workspaces-web/model/ListPortalsResult.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-workspaces-web/include/aws/workspaces-web/model/ListPortalsResult.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-workspaces-web/include/aws/workspaces-web/model/ListPortalsResult.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/workspaces-web/WorkSpacesWeb_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/workspaces-web/model/PortalSummary.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace WorkSpacesWeb { namespace Model { class AWS_WORKSPACESWEB_API ListPortalsResult { public: ListPortalsResult(); ListPortalsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); ListPortalsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The pagination token used to retrieve the next page of results for this * operation. </p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p>The pagination token used to retrieve the next page of results for this * operation. </p> */ inline void SetNextToken(const Aws::String& value) { m_nextToken = value; } /** * <p>The pagination token used to retrieve the next page of results for this * operation. </p> */ inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); } /** * <p>The pagination token used to retrieve the next page of results for this * operation. </p> */ inline void SetNextToken(const char* value) { m_nextToken.assign(value); } /** * <p>The pagination token used to retrieve the next page of results for this * operation. </p> */ inline ListPortalsResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p>The pagination token used to retrieve the next page of results for this * operation. </p> */ inline ListPortalsResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * <p>The pagination token used to retrieve the next page of results for this * operation. </p> */ inline ListPortalsResult& WithNextToken(const char* value) { SetNextToken(value); return *this;} /** * <p>The portals in the list.</p> */ inline const Aws::Vector<PortalSummary>& GetPortals() const{ return m_portals; } /** * <p>The portals in the list.</p> */ inline void SetPortals(const Aws::Vector<PortalSummary>& value) { m_portals = value; } /** * <p>The portals in the list.</p> */ inline void SetPortals(Aws::Vector<PortalSummary>&& value) { m_portals = std::move(value); } /** * <p>The portals in the list.</p> */ inline ListPortalsResult& WithPortals(const Aws::Vector<PortalSummary>& value) { SetPortals(value); return *this;} /** * <p>The portals in the list.</p> */ inline ListPortalsResult& WithPortals(Aws::Vector<PortalSummary>&& value) { SetPortals(std::move(value)); return *this;} /** * <p>The portals in the list.</p> */ inline ListPortalsResult& AddPortals(const PortalSummary& value) { m_portals.push_back(value); return *this; } /** * <p>The portals in the list.</p> */ inline ListPortalsResult& AddPortals(PortalSummary&& value) { m_portals.push_back(std::move(value)); return *this; } private: Aws::String m_nextToken; Aws::Vector<PortalSummary> m_portals; }; } // namespace Model } // namespace WorkSpacesWeb } // namespace Aws
29.32
124
0.664666
[ "vector", "model" ]
fa23e02866d8545914beda05a6617baaef58cdf6
45,484
c
C
vendors/st/boards/stm32l475_discovery/ports/secure_sockets/iot_secure_sockets.c
1NCE-GmbH/amazon-freertos
9f97b3cf4919ecc8c6578e47894ed47681da4b36
[ "MIT" ]
null
null
null
vendors/st/boards/stm32l475_discovery/ports/secure_sockets/iot_secure_sockets.c
1NCE-GmbH/amazon-freertos
9f97b3cf4919ecc8c6578e47894ed47681da4b36
[ "MIT" ]
null
null
null
vendors/st/boards/stm32l475_discovery/ports/secure_sockets/iot_secure_sockets.c
1NCE-GmbH/amazon-freertos
9f97b3cf4919ecc8c6578e47894ed47681da4b36
[ "MIT" ]
null
null
null
/* * FreeRTOS Secure Sockets for STM32L4 Discovery kit IoT node V1.0.0 Beta 4 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /** * @file iot_secure_sockets.c * @brief WiFi and Secure Socket interface implementation for ST board. */ /* Define _SECURE_SOCKETS_WRAPPER_NOT_REDEFINE to prevent secure sockets functions * from redefining in iot_secure_sockets_wrapper_metrics.h */ #define _SECURE_SOCKETS_WRAPPER_NOT_REDEFINE /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "semphr.h" /* TLS includes. */ #include "iot_tls.h" /* WiFi driver includes. */ #include "es_wifi.h" #include "es_wifi_io.h" /* Socket and WiFi interface includes. */ #include "iot_secure_sockets.h" #include "iot_wifi.h" /* WiFi configuration includes. */ #include "aws_wifi_config.h" /* Credentials includes. */ #include "aws_clientcredential.h" #include "iot_default_root_certificates.h" #undef _SECURE_SOCKETS_WRAPPER_NOT_REDEFINE /** * @brief A Flag to indicate whether or not a socket is * secure i.e. it uses TLS or not. */ #define stsecuresocketsSOCKET_SECURE_FLAG ( 1UL << 0 ) /** * @brief A flag to indicate whether or not a socket is closed * for receive. */ #define stsecuresocketsSOCKET_READ_CLOSED_FLAG ( 1UL << 1 ) /** * @brief A flag to indicate whether or not a socket is closed * for send. */ #define stsecuresocketsSOCKET_WRITE_CLOSED_FLAG ( 1UL << 2 ) /** * @brief A flag to indicate whether or not the socket is connected. */ #define stsecuresocketsSOCKET_IS_CONNECTED_FLAG ( 1UL << 3 ) /** * @brief The maximum timeout accepted by the Inventek module. * * This value is dictated by the hardware and should not be * modified. */ #define stsecuresocketsMAX_TIMEOUT ( 30000 ) /** * @brief Delay used between network read attempts when effecting a receive timeout. * * If receive timeouts are implemented by the Inventek module then * the SPI driver will poll for extended periods, preventing lower * priority tasks from executing. Therefore timeouts are mocked in * the secure sockets layer, and this constant sets the sleep time * between each read attempt during the receive timeout period. */ #define stsecuresocketsFIVE_MILLISECONDS ( pdMS_TO_TICKS( 5 ) ) /** * @brief The timeout supplied to the Inventek module in receive operation. * * Receive timeout are emulated in secure sockets layer and therefore we * do not want the Inventek module to block. Setting to zero means * no timeout, so one is the smallest value we can set it to. */ #define stsecuresocketsONE_MILLISECOND ( 1 ) /** * @brief The credential set to use for TLS on the Inventek module. * * @note This is hard-coded to 3 because we are using re-writable * credential slot. */ #define stsecuresocketsOFFLOAD_SSL_CREDS_SLOT ( 3 ) /*-----------------------------------------------------------*/ /** * @brief Represents the WiFi module. * * Since there is only one WiFi module on the ST board, only * one instance of this type is needed. All the operations on * the WiFi module must be serialized because a single operation * (like socket connect, send etc) consists of multiple AT Commands * sent over the same SPI bus. A semaphore is therefore used to * serialize all the operations. */ typedef struct STWiFiModule { ES_WIFIObject_t xWifiObject; /**< Internal WiFi object. */ SemaphoreHandle_t xSemaphoreHandle; /**< Semaphore used to serialize all the operations on the WiFi module. */ } STWiFiModule_t; /** * @brief Represents a secure socket. */ typedef struct STSecureSocket { uint8_t ucInUse; /**< Tracks whether the socket is in use or not. */ ES_WIFI_ConnType_t xSocketType; /**< Type of the socket. @see ES_WIFI_ConnType_t. */ uint32_t ulFlags; /**< Various properties of the socket (secured etc.). */ uint32_t ulSendTimeout; /**< Send timeout. */ uint32_t ulReceiveTimeout; /**< Receive timeout. */ char * pcDestination; /**< Destination URL. Set using SOCKETS_SO_SERVER_NAME_INDICATION option in SOCKETS_SetSockOpt function. */ void * pvTLSContext; /**< The TLS Context. */ char * pcServerCertificate; /**< Server certificate. Set using SOCKETS_SO_TRUSTED_SERVER_CERTIFICATE option in SOCKETS_SetSockOpt function. */ uint32_t ulServerCertificateLength; /**< Length of the server certificate. */ } STSecureSocket_t; /*-----------------------------------------------------------*/ /** * @brief Secure socket objects. * * An index in this array is returned to the user from SOCKETS_Socket * function. */ static STSecureSocket_t xSockets[ wificonfigMAX_SOCKETS ]; /** * @brief WiFi module object. * * Since the ST board contains only one WiFi module, only one instance * is needed and there is no need to pass this to the user. */ extern STWiFiModule_t xWiFiModule; /** * @brief Maximum time to wait in ticks for obtaining the WiFi semaphore * before failing the operation. */ static const TickType_t xSemaphoreWaitTicks = pdMS_TO_TICKS( wificonfigMAX_SEMAPHORE_WAIT_TIME_MS ); /*-----------------------------------------------------------*/ /** * @brief Get a free socket from the free socket pool. * * Iterates over the xSockets array to see if it can find * a free socket. A free or unused socket is indicated by * the zero value of the ucInUse member of STSecureSocket_t. * * @return Index of the socket in the xSockets array, if it is * able to find a free socket, SOCKETS_INVALID_SOCKET otherwise. */ static uint32_t prvGetFreeSocket( void ); /** * @brief Returns the socket back to the free socket pool. * * Marks the socket as free by setting ucInUse member of the * STSecureSocket_t structure as zero. */ static void prvReturnSocket( uint32_t ulSocketNumber ); /** * @brief Checks whether or not the provided socket number is valid. * * Ensures that the provided number is less than wificonfigMAX_SOCKETS * and the socket is "in-use" i.e. ucInUse is set to non-zero in the * socket structure. * * @param[in] ulSocketNumber The provided socket number to check. * * @return pdTRUE if the socket is valid, pdFALSE otherwise. */ static BaseType_t prvIsValidSocket( uint32_t ulSocketNumber ); /** * @brief Sends the provided data over WiFi. * * @param[in] pvContext The caller context. Socket number in our case. * @param[in] pucData The data to send. * @param[in] xDataLength Length of the data. * * @return Number of bytes actually sent if successful, SOCKETS_SOCKET_ERROR * otherwise. */ static BaseType_t prvNetworkSend( void * pvContext, const unsigned char * pucData, size_t xDataLength ); /** * @brief Receives the data over WiFi. * * @param[in] pvContext The caller context. Socket number in our case. * @param[out] pucReceiveBuffer The buffer to receive the data in. * @param[in] xReceiveBufferLength The length of the provided buffer. * * @return The number of bytes actually received if successful, SOCKETS_SOCKET_ERROR * otherwise. */ static BaseType_t prvNetworkRecv( void * pvContext, unsigned char * pucReceiveBuffer, size_t xReceiveBufferLength ); /*-----------------------------------------------------------*/ static uint32_t prvGetFreeSocket( void ) { uint32_t ulIndex; /* Iterate over xSockets array to see if any free socket * is available. */ for( ulIndex = 0; ulIndex < ( uint32_t ) wificonfigMAX_SOCKETS; ulIndex++ ) { /* Since multiple tasks can be accessing this simultaneously, * this has to be in critical section. */ taskENTER_CRITICAL(); if( xSockets[ ulIndex ].ucInUse == 0U ) { /* Mark the socket as "in-use". */ xSockets[ ulIndex ].ucInUse = 1; taskEXIT_CRITICAL(); /* We have found a free socket, so stop. */ break; } else { taskEXIT_CRITICAL(); } } /* Did we find a free socket? */ if( ulIndex == ( uint32_t ) wificonfigMAX_SOCKETS ) { /* Return SOCKETS_INVALID_SOCKET if we fail to * find a free socket. */ ulIndex = ( uint32_t ) SOCKETS_INVALID_SOCKET; } return ulIndex; } /*-----------------------------------------------------------*/ static void prvReturnSocket( uint32_t ulSocketNumber ) { /* Since multiple tasks can be accessing this simultaneously, * this has to be in critical section. */ taskENTER_CRITICAL(); { /* Mark the socket as free. */ xSockets[ ulSocketNumber ].ucInUse = 0; } taskEXIT_CRITICAL(); } /*-----------------------------------------------------------*/ static BaseType_t prvIsValidSocket( uint32_t ulSocketNumber ) { BaseType_t xValid = pdFALSE; /* Check that the provided socket number is within the valid * index range. */ if( ulSocketNumber < ( uint32_t ) wificonfigMAX_SOCKETS ) { /* Since multiple tasks can be accessing this simultaneously, * this has to be in critical section. */ taskENTER_CRITICAL(); { /* Check that this socket is in use. */ if( xSockets[ ulSocketNumber ].ucInUse == 1U ) { /* This is a valid socket number. */ xValid = pdTRUE; } } taskEXIT_CRITICAL(); } return xValid; } /*-----------------------------------------------------------*/ static BaseType_t prvNetworkSend( void * pvContext, const unsigned char * pucData, size_t xDataLength ) { uint32_t ulSocketNumber = ( uint32_t ) pvContext; /*lint !e923 cast is necessary for port. */ STSecureSocket_t * pxSecureSocket; uint16_t usSentBytes = 0; BaseType_t xRetVal = SOCKETS_SOCKET_ERROR; ES_WIFI_Status_t xWiFiResult; /* Shortcut for easy access. */ pxSecureSocket = &( xSockets[ ulSocketNumber ] ); /* Try to acquire the semaphore. */ if( xSemaphoreTake( xWiFiModule.xSemaphoreHandle, xSemaphoreWaitTicks ) == pdTRUE ) { /* Since WiFi module has only one timeout, this needs * to be set per send and receive operation to the * respective send or receive timeout. Also, this * must be done after acquiring the semaphore as the * xWiFiModule is a shared object.*/ if( pxSecureSocket->ulSendTimeout == 0 ) { /* Set the SPI timeout to the maximum uint32_t value. * This is a little over 49 days. */ xWiFiModule.xWifiObject.Timeout = 0xFFFFFFFF; } else { /* The maximum timeout for Inventek module is 30 seconds. * This timeout is about 65 seconds, so the module should * timeout before the SPI. */ xWiFiModule.xWifiObject.Timeout = ES_WIFI_TIMEOUT; } /* Send the data. */ xWiFiResult = ES_WIFI_SendData( &( xWiFiModule.xWifiObject ), ( uint8_t ) ulSocketNumber, ( uint8_t * ) pucData, /*lint !e9005 STM function does not use const. */ ( uint16_t ) xDataLength, &( usSentBytes ), pxSecureSocket->ulSendTimeout ); if( xWiFiResult == ES_WIFI_STATUS_OK ) { /* If the data was successfully sent, return the actual * number of bytes sent. Otherwise return SOCKETS_SOCKET_ERROR. */ xRetVal = ( BaseType_t ) usSentBytes; } /* Return the semaphore. */ ( void ) xSemaphoreGive( xWiFiModule.xSemaphoreHandle ); } /* The following code attempts to revive the Inventek WiFi module * from its unusable state.*/ if( xWiFiResult == ES_WIFI_STATUS_IO_ERROR ) { /* Reset the WiFi Module. Since the WIFI_Reset function * acquires the same semaphore, we must not acquire * it. */ if( WIFI_Reset() == eWiFiSuccess ) { /* Try to acquire the semaphore. */ if( xSemaphoreTake( xWiFiModule.xSemaphoreHandle, portMAX_DELAY ) == pdTRUE ) { /* Reinitialize the socket structures which * marks all sockets as closed and free. */ SOCKETS_Init(); /* Return the semaphore. */ ( void ) xSemaphoreGive( xWiFiModule.xSemaphoreHandle ); } /* Set the error code to indicate that * WiFi needs to be reconnected to network. */ xRetVal = SOCKETS_PERIPHERAL_RESET; } } /* To allow other tasks of equal priority that are using this API to run as * a switch to an equal priority task that is waiting for the mutex will * only otherwise occur in the tick interrupt - at which point the mutex * might have been taken again by the currently running task. */ taskYIELD(); return xRetVal; } /*-----------------------------------------------------------*/ static BaseType_t prvNetworkRecv( void * pvContext, unsigned char * pucReceiveBuffer, size_t xReceiveBufferLength ) { uint32_t ulSocketNumber = ( uint32_t ) pvContext; /*lint !e923 cast is needed for portability. */ STSecureSocket_t * pxSecureSocket; uint16_t usReceivedBytes = 0; BaseType_t xRetVal; ES_WIFI_Status_t xWiFiResult; TickType_t xTimeOnEntering = xTaskGetTickCount(), xSemaphoreWait; /* Shortcut for easy access. */ pxSecureSocket = &( xSockets[ ulSocketNumber ] ); /* WiFi module does not support receiving more than ES_WIFI_PAYLOAD_SIZE * bytes at a time. */ if( xReceiveBufferLength > ( uint32_t ) ES_WIFI_PAYLOAD_SIZE ) { xReceiveBufferLength = ( uint32_t ) ES_WIFI_PAYLOAD_SIZE; } xSemaphoreWait = pxSecureSocket->ulReceiveTimeout + stsecuresocketsFIVE_MILLISECONDS; for( ; ; ) { /* Try to acquire the semaphore. */ if( xSemaphoreTake( xWiFiModule.xSemaphoreHandle, xSemaphoreWait ) == pdTRUE ) { /* Since WiFi module has only one timeout, this needs * to be set per send and receive operation to the * respective send or receive timeout. Also, this * must be done after acquiring the semaphore as the * xWiFiModule is a shared object.*/ if( pxSecureSocket->ulReceiveTimeout == 0 ) { /* Set the SPI timeout to the maximum uint32_t value. * This is a little over 49 days. */ xWiFiModule.xWifiObject.Timeout = 0xFFFFFFFF; } else { /* The maximum timeout for Inventek module is 30 seconds. * This timeout is about 65 seconds, so the module should * timeout before the SPI. */ xWiFiModule.xWifiObject.Timeout = ES_WIFI_TIMEOUT; } /* Receive the data. */ xWiFiResult = ES_WIFI_ReceiveData( &( xWiFiModule.xWifiObject ), ( uint8_t ) ulSocketNumber, ( uint8_t * ) pucReceiveBuffer, ( uint16_t ) xReceiveBufferLength, &( usReceivedBytes ), stsecuresocketsONE_MILLISECOND ); /* Return the semaphore. */ ( void ) xSemaphoreGive( xWiFiModule.xSemaphoreHandle ); if( ( xWiFiResult == ES_WIFI_STATUS_OK ) && ( usReceivedBytes != 0 ) ) { /* Success, return the number of bytes received. */ xRetVal = ( BaseType_t ) usReceivedBytes; break; } else if( ( xWiFiResult == ES_WIFI_STATUS_TIMEOUT ) || ( ( xWiFiResult == ES_WIFI_STATUS_OK ) && ( usReceivedBytes == 0 ) ) ) { /* The WiFi poll timed out, but has the socket timeout expired * too? */ if( ( xTaskGetTickCount() - xTimeOnEntering ) < pxSecureSocket->ulReceiveTimeout ) { /* The socket has not timed out, but the driver supplied * with the board is polling, which would block other tasks, so * block for a short while to allow other tasks to run before * trying again. */ vTaskDelay( stsecuresocketsFIVE_MILLISECONDS ); } else { /* The socket read has timed out too. Returning * SOCKETS_EWOULDBLOCK will cause mBedTLS to fail * and so we must return zero. */ xRetVal = 0; break; } } else { /* xWiFiResult contains an error status. */ xRetVal = SOCKETS_SOCKET_ERROR; break; } } else { /* Semaphore wait time was longer than the receive timeout so this * is also a socket timeout. Returning SOCKETS_EWOULDBLOCK will * cause mBedTLS to fail and so we must return zero.*/ xRetVal = 0; break; } } /* The following code attempts to revive the Inventek WiFi module * from its unusable state.*/ if( xWiFiResult == ES_WIFI_STATUS_IO_ERROR ) { /* Reset the WiFi Module. Since the WIFI_Reset function * acquires the same semaphore, we must not acquire * it. */ if( WIFI_Reset() == eWiFiSuccess ) { /* Try to acquire the semaphore. */ if( xSemaphoreTake( xWiFiModule.xSemaphoreHandle, portMAX_DELAY ) == pdTRUE ) { /* Reinitialize the socket structures which * marks all sockets as closed and free. */ SOCKETS_Init(); /* Return the semaphore. */ ( void ) xSemaphoreGive( xWiFiModule.xSemaphoreHandle ); } /* Set the error code to indicate that * WiFi needs to be reconnected to network. */ xRetVal = SOCKETS_PERIPHERAL_RESET; } } return xRetVal; } /*-----------------------------------------------------------*/ Socket_t SOCKETS_Socket( int32_t lDomain, int32_t lType, int32_t lProtocol ) { uint32_t ulSocketNumber; /* Ensure that only supported values are supplied. */ configASSERT( lDomain == SOCKETS_AF_INET ); configASSERT( ( lType == SOCKETS_SOCK_STREAM && lProtocol == SOCKETS_IPPROTO_TCP ) || ( lType == SOCKETS_SOCK_DGRAM && lProtocol == SOCKETS_IPPROTO_UDP ) ); /* Try to get a free socket. */ ulSocketNumber = prvGetFreeSocket(); /* If we get a free socket, set its attributes. */ if( ulSocketNumber != ( uint32_t ) SOCKETS_INVALID_SOCKET ) { /* Store the socket type. (with UDP support) */ if (lProtocol == SOCKETS_IPPROTO_TCP) { xSockets[ ulSocketNumber ].xSocketType = ES_WIFI_TCP_CONNECTION; } else { xSockets[ ulSocketNumber ].xSocketType = ES_WIFI_UDP_CONNECTION; } /* Initialize all the members to sane values. */ xSockets[ ulSocketNumber ].ulFlags = 0; xSockets[ ulSocketNumber ].ulSendTimeout = socketsconfigDEFAULT_SEND_TIMEOUT; xSockets[ ulSocketNumber ].ulReceiveTimeout = socketsconfigDEFAULT_RECV_TIMEOUT; xSockets[ ulSocketNumber ].pcDestination = NULL; xSockets[ ulSocketNumber ].pvTLSContext = NULL; xSockets[ ulSocketNumber ].pcServerCertificate = NULL; xSockets[ ulSocketNumber ].ulServerCertificateLength = 0; } /* If we fail to get a free socket, we return SOCKETS_INVALID_SOCKET. */ return ( Socket_t ) ulSocketNumber; /*lint !e923 cast required for portability. */ } /*-----------------------------------------------------------*/ int32_t SOCKETS_Connect( Socket_t xSocket, SocketsSockaddr_t * pxAddress, Socklen_t xAddressLength ) { uint32_t ulSocketNumber = ( uint32_t ) xSocket; /*lint !e923 cast required for portability. */ STSecureSocket_t * pxSecureSocket; ES_WIFI_Conn_t xWiFiConnection; int32_t lRetVal = SOCKETS_ERROR_NONE; #ifndef USE_OFFLOAD_SSL TLSParams_t xTLSParams = { 0 }; #endif /* USE_OFFLOAD_SSL */ /* Ensure that a valid socket was passed. */ if( prvIsValidSocket( ulSocketNumber ) == pdTRUE ) { /* Shortcut for easy access. */ pxSecureSocket = &( xSockets[ ulSocketNumber ] ); /* Check that the socket is not already connected. */ if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_IS_CONNECTED_FLAG ) != 0UL ) { /* Connect attempted on an already connected socket. */ lRetVal = SOCKETS_SOCKET_ERROR; } /* Try to acquire the semaphore. */ if( ( lRetVal == SOCKETS_ERROR_NONE ) && ( xSemaphoreTake( xWiFiModule.xSemaphoreHandle, xSemaphoreWaitTicks ) == pdTRUE ) ) { /* Store server certificate if we are using offload SSL * and the socket is a secure socket. */ #ifdef USE_OFFLOAD_SSL if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_SECURE_FLAG ) != 0UL ) { /* Store the custom certificate if needed. */ if( pxSecureSocket->pcServerCertificate != NULL ) { if( ES_WIFI_StoreCA( &( xWiFiModule.xWifiObject ), ES_WIFI_FUNCTION_TLS, stsecuresocketsOFFLOAD_SSL_CREDS_SLOT, ( uint8_t * ) pxSecureSocket->pcServerCertificate, ( uint16_t ) pxSecureSocket->ulServerCertificateLength ) == ES_WIFI_STATUS_OK ) { /* Certificate stored successfully. */ lRetVal = SOCKETS_ERROR_NONE; } else { /* Failed to store certificate. */ lRetVal = SOCKETS_SOCKET_ERROR; } } else { /* If we are not using the ATS endpoint, use the VeriSign root CA. Otherwise * use the Starfield root CA. */ if( strstr( clientcredentialMQTT_BROKER_ENDPOINT, "-ats.iot" ) == NULL ) { /* Store the default certificate. */ if( ES_WIFI_StoreCA( &( xWiFiModule.xWifiObject ), ES_WIFI_FUNCTION_TLS, stsecuresocketsOFFLOAD_SSL_CREDS_SLOT, ( uint8_t * ) tlsVERISIGN_ROOT_CERTIFICATE_PEM, ( uint16_t ) tlsVERISIGN_ROOT_CERTIFICATE_LENGTH ) == ES_WIFI_STATUS_OK ) { /* Certificate stored successfully. */ lRetVal = SOCKETS_ERROR_NONE; } else { /* Failed to store certificate. */ lRetVal = SOCKETS_SOCKET_ERROR; } } else { /* Store the default certificate. */ if( ES_WIFI_StoreCA( &( xWiFiModule.xWifiObject ), ES_WIFI_FUNCTION_TLS, stsecuresocketsOFFLOAD_SSL_CREDS_SLOT, ( uint8_t * ) tlsSTARFIELD_ROOT_CERTIFICATE_PEM, ( uint16_t ) tlsSTARFIELD_ROOT_CERTIFICATE_LENGTH ) == ES_WIFI_STATUS_OK ) { /* Certificate stored successfully. */ lRetVal = SOCKETS_ERROR_NONE; } else { /* Failed to store certificate. */ lRetVal = SOCKETS_SOCKET_ERROR; } } } } #endif /* USE_OFFLOAD_SSL */ if( lRetVal == SOCKETS_ERROR_NONE ) { /* Setup connection parameters. */ xWiFiConnection.Number = ( uint8_t ) ulSocketNumber; xWiFiConnection.Type = pxSecureSocket->xSocketType; xWiFiConnection.RemotePort = SOCKETS_ntohs( pxAddress->usPort ); /* WiFi Module expects the port number in host byte order. */ memcpy( &( xWiFiConnection.RemoteIP ), &( pxAddress->ulAddress ), sizeof( xWiFiConnection.RemoteIP ) ); xWiFiConnection.LocalPort = 0; xWiFiConnection.Name = NULL; /* Start the client connection. */ if( ES_WIFI_StartClientConnection( &( xWiFiModule.xWifiObject ), &( xWiFiConnection ) ) == ES_WIFI_STATUS_OK ) { /* Successful connection is established. */ lRetVal = SOCKETS_ERROR_NONE; /* Mark that the socket is connected. */ pxSecureSocket->ulFlags |= stsecuresocketsSOCKET_IS_CONNECTED_FLAG; } else { /* Connection failed. */ lRetVal = SOCKETS_SOCKET_ERROR; } } /* Return the semaphore. */ ( void ) xSemaphoreGive( xWiFiModule.xSemaphoreHandle ); } else { /* Could not acquire semaphore. */ lRetVal = SOCKETS_SOCKET_ERROR; } } else { /* Invalid socket handle was passed. */ lRetVal = SOCKETS_EINVAL; } /* TLS initialization is needed only if we are not using offload SSL. */ #ifndef USE_OFFLOAD_SSL /* Initialize TLS only if the connection is successful. */ if( ( lRetVal == SOCKETS_ERROR_NONE ) && ( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_SECURE_FLAG ) != 0UL ) ) { /* Setup TLS parameters. */ xTLSParams.ulSize = sizeof( xTLSParams ); xTLSParams.pcDestination = pxSecureSocket->pcDestination; xTLSParams.pcServerCertificate = pxSecureSocket->pcServerCertificate; xTLSParams.ulServerCertificateLength = pxSecureSocket->ulServerCertificateLength; xTLSParams.pvCallerContext = ( void * ) xSocket; xTLSParams.pxNetworkRecv = &( prvNetworkRecv ); xTLSParams.pxNetworkSend = &( prvNetworkSend ); /* Initialize TLS. */ if( TLS_Init( &( pxSecureSocket->pvTLSContext ), &( xTLSParams ) ) == pdFREERTOS_ERRNO_NONE ) { /* Initiate TLS handshake. */ if( TLS_Connect( pxSecureSocket->pvTLSContext ) != pdFREERTOS_ERRNO_NONE ) { /* TLS handshake failed. */ lRetVal = SOCKETS_TLS_HANDSHAKE_ERROR; } } else { /* TLS Initialization failed. */ lRetVal = SOCKETS_TLS_INIT_ERROR; } } #endif /* USE_OFFLOAD_SSL*/ return lRetVal; } /*-----------------------------------------------------------*/ int32_t SOCKETS_Recv( Socket_t xSocket, void * pvBuffer, size_t xBufferLength, uint32_t ulFlags ) { uint32_t ulSocketNumber = ( uint32_t ) xSocket; /*lint !e923 cast required for portability. */ STSecureSocket_t * pxSecureSocket; int32_t lReceivedBytes = SOCKETS_SOCKET_ERROR; /* Remove warning about unused parameters. */ ( void ) ulFlags; /* Ensure that a valid socket was passed and the * passed buffer is not NULL. */ if( ( prvIsValidSocket( ulSocketNumber ) == pdTRUE ) && ( pvBuffer != NULL ) ) { /* Shortcut for easy access. */ pxSecureSocket = &( xSockets[ ulSocketNumber ] ); /* Check that receive is allowed on the socket. */ if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_READ_CLOSED_FLAG ) == 0UL ) { #ifndef USE_OFFLOAD_SSL if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_SECURE_FLAG ) != 0UL ) { /* Receive through TLS pipe, if negotiated. */ lReceivedBytes = TLS_Recv( pxSecureSocket->pvTLSContext, pvBuffer, xBufferLength ); /* Convert the error code. */ if( lReceivedBytes < 0 ) { /* TLS_Recv failed. */ lReceivedBytes = SOCKETS_TLS_RECV_ERROR; } } else { /* Receive un-encrypted. */ lReceivedBytes = prvNetworkRecv( xSocket, pvBuffer, xBufferLength ); } #else /* USE_OFFLOAD_SSL */ /* Always receive using prvNetworkRecv if using offload SSL. */ lReceivedBytes = prvNetworkRecv( xSocket, pvBuffer, xBufferLength ); #endif /* USE_OFFLOAD_SSL */ } else { /* The socket has been closed for read. */ lReceivedBytes = SOCKETS_ECLOSED; } } return lReceivedBytes; } /*-----------------------------------------------------------*/ int32_t SOCKETS_Send( Socket_t xSocket, const void * pvBuffer, size_t xDataLength, uint32_t ulFlags ) { uint32_t ulSocketNumber = ( uint32_t ) xSocket; /*lint !e923 cast required for portability. */ STSecureSocket_t * pxSecureSocket; int32_t lSentBytes = SOCKETS_SOCKET_ERROR; /* Remove warning about unused parameters. */ ( void ) ulFlags; /* Ensure that a valid socket was passed and the passed buffer * is not NULL. */ if( ( prvIsValidSocket( ulSocketNumber ) == pdTRUE ) && ( pvBuffer != NULL ) ) { /* Shortcut for easy access. */ pxSecureSocket = &( xSockets[ ulSocketNumber ] ); /* Check that send is allowed on the socket. */ if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_WRITE_CLOSED_FLAG ) == 0UL ) { #ifndef USE_OFFLOAD_SSL if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_SECURE_FLAG ) != 0UL ) { /* Send through TLS pipe, if negotiated. */ lSentBytes = TLS_Send( pxSecureSocket->pvTLSContext, pvBuffer, xDataLength ); /* Convert the error code. */ if( lSentBytes < 0 ) { /* TLS_Send failed. */ lSentBytes = SOCKETS_TLS_SEND_ERROR; } } else { /* Send un-encrypted. */ lSentBytes = prvNetworkSend( xSocket, pvBuffer, xDataLength ); } #else /* USE_OFFLOAD_SSL */ /* Always send using prvNetworkSend if using offload SSL. */ lSentBytes = prvNetworkSend( xSocket, pvBuffer, xDataLength ); #endif /* USE_OFFLOAD_SSL */ } else { /* The socket has been closed for write. */ lSentBytes = SOCKETS_ECLOSED; } } return lSentBytes; } /*-----------------------------------------------------------*/ int32_t SOCKETS_Shutdown( Socket_t xSocket, uint32_t ulHow ) { uint32_t ulSocketNumber = ( uint32_t ) xSocket; /*lint !e923 cast required for portability. */ STSecureSocket_t * pxSecureSocket; int32_t lRetVal = SOCKETS_SOCKET_ERROR; /* Ensure that a valid socket was passed. */ if( prvIsValidSocket( ulSocketNumber ) == pdTRUE ) { /* Shortcut for easy access. */ pxSecureSocket = &( xSockets[ ulSocketNumber ] ); switch( ulHow ) { case SOCKETS_SHUT_RD: /* Further receive calls on this socket should return error. */ pxSecureSocket->ulFlags |= stsecuresocketsSOCKET_READ_CLOSED_FLAG; /* Return success to the user. */ lRetVal = SOCKETS_ERROR_NONE; break; case SOCKETS_SHUT_WR: /* Further send calls on this socket should return error. */ pxSecureSocket->ulFlags |= stsecuresocketsSOCKET_WRITE_CLOSED_FLAG; /* Return success to the user. */ lRetVal = SOCKETS_ERROR_NONE; break; case SOCKETS_SHUT_RDWR: /* Further send or receive calls on this socket should return error. */ pxSecureSocket->ulFlags |= stsecuresocketsSOCKET_READ_CLOSED_FLAG; pxSecureSocket->ulFlags |= stsecuresocketsSOCKET_WRITE_CLOSED_FLAG; /* Return success to the user. */ lRetVal = SOCKETS_ERROR_NONE; break; default: /* An invalid value was passed for ulHow. */ lRetVal = SOCKETS_EINVAL; break; } } else { /* Invalid socket was passed. */ lRetVal = SOCKETS_EINVAL; } return lRetVal; } /*-----------------------------------------------------------*/ int32_t SOCKETS_Close( Socket_t xSocket ) { uint32_t ulSocketNumber = ( uint32_t ) xSocket; /*lint !e923 cast required for portability. */ STSecureSocket_t * pxSecureSocket; ES_WIFI_Conn_t xWiFiConnection; int32_t lRetVal; /* Ensure that a valid socket was passed. */ if( prvIsValidSocket( ulSocketNumber ) == pdTRUE ) { /* Shortcut for easy access. */ pxSecureSocket = &( xSockets[ ulSocketNumber ] ); /* Mark the socket as closed. */ pxSecureSocket->ulFlags |= stsecuresocketsSOCKET_READ_CLOSED_FLAG; pxSecureSocket->ulFlags |= stsecuresocketsSOCKET_WRITE_CLOSED_FLAG; /* Free the space allocated for pcDestination. */ if( pxSecureSocket->pcDestination != NULL ) { vPortFree( pxSecureSocket->pcDestination ); } /* Free the space allocated for pcServerCertificate. */ if( pxSecureSocket->pcServerCertificate != NULL ) { vPortFree( pxSecureSocket->pcServerCertificate ); } #ifndef USE_OFFLOAD_SSL /* Cleanup TLS. */ if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_SECURE_FLAG ) != 0UL ) { TLS_Cleanup( pxSecureSocket->pvTLSContext ); } #endif /* USE_OFFLOAD_SSL */ /* Initialize the members used by the ES_WIFI_StopClientConnection call. */ xWiFiConnection.Number = ( uint8_t ) ulSocketNumber; /* Try to acquire the semaphore. */ if( xSemaphoreTake( xWiFiModule.xSemaphoreHandle, xSemaphoreWaitTicks ) == pdTRUE ) { /* Stop the client connection. */ if( ES_WIFI_StopClientConnection( &( xWiFiModule.xWifiObject ), &( xWiFiConnection ) ) == ES_WIFI_STATUS_OK ) { /* Connection close successful. */ lRetVal = SOCKETS_ERROR_NONE; } else { /* Couldn't stop WiFi client connection. */ lRetVal = SOCKETS_SOCKET_ERROR; } /* Return the semaphore. */ ( void ) xSemaphoreGive( xWiFiModule.xSemaphoreHandle ); } else { /* Couldn't get semaphore. */ lRetVal = SOCKETS_SOCKET_ERROR; } /* Return the socket back to the free socket pool. */ prvReturnSocket( ulSocketNumber ); } else { /* Bad argument. */ lRetVal = SOCKETS_EINVAL; } return lRetVal; } /*-----------------------------------------------------------*/ int32_t SOCKETS_SetSockOpt( Socket_t xSocket, int32_t lLevel, int32_t lOptionName, const void * pvOptionValue, size_t xOptionLength ) { uint32_t ulSocketNumber = ( uint32_t ) xSocket; /*lint !e923 cast required for portability. */ STSecureSocket_t * pxSecureSocket; int32_t lRetVal = SOCKETS_ERROR_NONE; uint32_t lTimeout; /* Ensure that a valid socket was passed. */ if( prvIsValidSocket( ulSocketNumber ) == pdTRUE ) { /* Shortcut for easy access. */ pxSecureSocket = &( xSockets[ ulSocketNumber ] ); switch( lOptionName ) { case SOCKETS_SO_SERVER_NAME_INDICATION: if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_IS_CONNECTED_FLAG ) == 0 ) { /* Non-NULL destination string indicates that SNI extension should * be used during TLS negotiation. */ pxSecureSocket->pcDestination = ( char * ) pvPortMalloc( 1U + xOptionLength ); if( pxSecureSocket->pcDestination == NULL ) { lRetVal = SOCKETS_ENOMEM; } else { memcpy( pxSecureSocket->pcDestination, pvOptionValue, xOptionLength ); pxSecureSocket->pcDestination[ xOptionLength ] = '\0'; } } else { /* SNI must be set before connection is established. */ lRetVal = SOCKETS_SOCKET_ERROR; } break; case SOCKETS_SO_TRUSTED_SERVER_CERTIFICATE: if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_IS_CONNECTED_FLAG ) == 0 ) { /* Non-NULL server certificate field indicates that the default trust * list should not be used. */ pxSecureSocket->pcServerCertificate = ( char * ) pvPortMalloc( xOptionLength ); if( pxSecureSocket->pcServerCertificate == NULL ) { lRetVal = SOCKETS_ENOMEM; } else { memcpy( pxSecureSocket->pcServerCertificate, pvOptionValue, xOptionLength ); pxSecureSocket->ulServerCertificateLength = xOptionLength; } } else { /* Trusted server certificate must be set before the connection is established. */ lRetVal = SOCKETS_SOCKET_ERROR; } break; case SOCKETS_SO_REQUIRE_TLS: if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_IS_CONNECTED_FLAG ) == 0 ) { /* Mark that it is a secure socket. */ pxSecureSocket->ulFlags |= stsecuresocketsSOCKET_SECURE_FLAG; #ifdef USE_OFFLOAD_SSL /* Set the socket type to SSL to use offload SSL. */ pxSecureSocket->xSocketType = ES_WIFI_TCP_SSL_CONNECTION; #endif /* USE_OFFLOAD_SSL */ } else { /* Require TLS must be set before the connection is established. */ lRetVal = SOCKETS_SOCKET_ERROR; } break; case SOCKETS_SO_SNDTIMEO: lTimeout = *( ( const uint32_t * ) pvOptionValue ); /*lint !e9087 pvOptionValue is passed in as an opaque value, and must be casted for setsockopt. */ /* Valid timeouts are 0 (no timeout) or 1-30000ms. */ if( lTimeout < stsecuresocketsMAX_TIMEOUT ) { /* Store send timeout. */ pxSecureSocket->ulSendTimeout = lTimeout; } else { lRetVal = SOCKETS_EINVAL; } break; case SOCKETS_SO_RCVTIMEO: lTimeout = *( ( const uint32_t * ) pvOptionValue ); /*lint !e9087 pvOptionValue is passed in as an opaque value, and must be casted for setsockopt. */ /* Valid timeouts are 0 (no timeout) or 1-30000ms. */ if( lTimeout < stsecuresocketsMAX_TIMEOUT ) { /* Store receive timeout. */ pxSecureSocket->ulReceiveTimeout = lTimeout; } else { lRetVal = SOCKETS_EINVAL; } break; case SOCKETS_SO_NONBLOCK: if( ( pxSecureSocket->ulFlags & stsecuresocketsSOCKET_IS_CONNECTED_FLAG ) != 0 ) { /* Set the timeouts to the smallest value possible. * This isn't true nonblocking, but as close as we can get. */ pxSecureSocket->ulReceiveTimeout = 1; pxSecureSocket->ulSendTimeout = 1; } else { /* Non blocking option must be set after the connection is * established. Non blocking connect is not supported. */ lRetVal = SOCKETS_SOCKET_ERROR; } break; default: lRetVal = SOCKETS_ENOPROTOOPT; break; } } else { lRetVal = SOCKETS_SOCKET_ERROR; } return lRetVal; } /*-----------------------------------------------------------*/ uint32_t SOCKETS_GetHostByName( const char * pcHostName ) { uint32_t ulIPAddres = 0; /* Try to acquire the semaphore. */ if( xSemaphoreTake( xWiFiModule.xSemaphoreHandle, xSemaphoreWaitTicks ) == pdTRUE ) { /* Do a DNS Lookup. */ if( ES_WIFI_DNS_LookUp( &( xWiFiModule.xWifiObject ), pcHostName, ( uint8_t * ) &( ulIPAddres ) ) != ES_WIFI_STATUS_OK ) { /* Return 0 if the DNS lookup fails. */ ulIPAddres = 0; } /* Return the semaphore. */ ( void ) xSemaphoreGive( xWiFiModule.xSemaphoreHandle ); } return ulIPAddres; } /*-----------------------------------------------------------*/ BaseType_t SOCKETS_Init( void ) { uint32_t ulIndex; /* Mark all the sockets as free and closed. */ for( ulIndex = 0; ulIndex < ( uint32_t ) wificonfigMAX_SOCKETS; ulIndex++ ) { xSockets[ ulIndex ].ucInUse = 0; xSockets[ ulIndex ].ulFlags = 0; xSockets[ ulIndex ].ulFlags |= stsecuresocketsSOCKET_READ_CLOSED_FLAG; xSockets[ ulIndex ].ulFlags |= stsecuresocketsSOCKET_WRITE_CLOSED_FLAG; } /* Empty initialization for ST board. */ return pdPASS; } /*-----------------------------------------------------------*/
37.840266
166
0.551095
[ "object" ]
fa25d086608d966f5671c9a74cdc8ccae6301139
727
c
C
lib/wizards/bulut/forest/forest2.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/bulut/forest/forest2.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/bulut/forest/forest2.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
#include "room.h" object wolf; object snake; extra_reset() { if (!wolf || !living(wolf)) { wolf = clone_object("/wizards/bulut/forest/wolf.c"); move_object(wolf, this_object()); } if (!snake || !living(snake)) { snake = clone_object("/wizards/bulut/forest/snake.c"); move_object(snake, this_object()); } } #undef EXTRA_RESET #define EXTRA_RESET\ extra_reset(); FOUR_EXIT("wizards/bulut/forest/forest3","north", "wizards/bulut/forest/forest1","south", "wizards/bulut/forest/forest20","east", "wizards/bulut/forest/forest10","west", "Crossing", "You are standing on a little path.\n" + "Path continues to east, west, north and south from here.\n", 1)
21.382353
64
0.64099
[ "object" ]
fa2ebb3e61648d5c1cae50209271b337e86b35e2
9,462
h
C
wrappers/7.0.0/vtkImageResliceWrap.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/vtkImageResliceWrap.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/vtkImageResliceWrap.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_VTKIMAGERESLICEWRAP_H #define NATIVE_EXTENSION_VTK_VTKIMAGERESLICEWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkImageReslice.h> #include "vtkThreadedImageAlgorithmWrap.h" #include "../../plus/plus.h" class VtkImageResliceWrap : public VtkThreadedImageAlgorithmWrap { 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); VtkImageResliceWrap(vtkSmartPointer<vtkImageReslice>); VtkImageResliceWrap(); ~VtkImageResliceWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void AutoCropOutputOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void AutoCropOutputOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void BorderOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void BorderOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GenerateStencilOutputOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GenerateStencilOutputOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetAutoCropOutput(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetBackgroundColor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetBackgroundLevel(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetBorder(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetGenerateStencilOutput(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInformationInput(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInterpolate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInterpolationMode(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInterpolationModeAsString(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInterpolationModeMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInterpolationModeMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInterpolator(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetMTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetMirror(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOptimization(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOutputDimensionality(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOutputExtent(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOutputOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOutputScalarType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOutputSpacing(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetResliceAxes(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetResliceAxesDirectionCosines(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetResliceAxesOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetResliceTransform(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetScalarScale(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetScalarShift(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSlabMode(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSlabModeAsString(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSlabModeMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSlabModeMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSlabNumberOfSlices(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSlabSliceSpacingFraction(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSlabTrapezoidIntegration(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStencil(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStencilOutput(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStencilOutputPort(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetTransformInputSampling(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetWrap(const Nan::FunctionCallbackInfo<v8::Value>& info); static void InterpolateOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void InterpolateOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info); static void MirrorOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void MirrorOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void OptimizationOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void OptimizationOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void ReportReferences(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetAutoCropOutput(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetBackgroundColor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetBackgroundLevel(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetBorder(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetGenerateStencilOutput(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInformationInput(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInterpolate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInterpolationMode(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInterpolationModeToCubic(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInterpolationModeToLinear(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInterpolationModeToNearestNeighbor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInterpolator(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetMirror(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOptimization(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputDimensionality(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputExtent(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputExtentToDefault(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputOriginToDefault(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputSpacing(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputSpacingToDefault(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetResliceAxes(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetResliceAxesDirectionCosines(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetResliceAxesOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetResliceTransform(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetScalarScale(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetScalarShift(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSlabMode(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSlabModeToMax(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSlabModeToMean(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSlabModeToMin(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSlabModeToSum(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSlabNumberOfSlices(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSlabSliceSpacingFraction(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSlabTrapezoidIntegration(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetStencilData(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetStencilOutput(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetTransformInputSampling(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetWrap(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SlabTrapezoidIntegrationOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SlabTrapezoidIntegrationOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void TransformInputSamplingOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void TransformInputSamplingOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void WrapOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void WrapOn(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKIMAGERESLICEWRAP_CLASSDEF VTK_NODE_PLUS_VTKIMAGERESLICEWRAP_CLASSDEF #endif }; #endif
67.106383
102
0.795286
[ "object" ]
fa2f2b9566d847ef5577be4506ae9822b7eb57c1
11,257
h
C
crawl-ref/source/book-data.h
kimjoy2002/crawl
1d02117c50939ffffbad45022d6cefe8f5838b49
[ "CC0-1.0" ]
44
2020-04-06T08:56:09.000Z
2021-03-17T18:05:18.000Z
crawl-ref/source/book-data.h
kimjoy2002/crawl
1d02117c50939ffffbad45022d6cefe8f5838b49
[ "CC0-1.0" ]
501
2020-04-06T07:19:01.000Z
2022-02-23T13:04:40.000Z
crawl-ref/source/book-data.h
kimjoy2002/crawl
1d02117c50939ffffbad45022d6cefe8f5838b49
[ "CC0-1.0" ]
74
2020-04-06T07:40:50.000Z
2021-05-21T00:13:36.000Z
using std::vector; /* * These books have a few goals: * 1. Have a variety of spell levels and types, so they're useful to * players who pick them up in different contexts. For example, a book * with a level 5, level 6 and level 9 spell might be helpful to an * mid-game character or a late-game one, or even just provide goals * for an early character. * 2. Group spells in a thematic or meaningful fashion. The Book of Pain, * Book of Storms, Wizard Biographies... these tell stories, and players * love stories. * * Randbooks can play a role in increasing variety, but I do think that * fixed books provide an overall better player experience in general. * * These on average have 3 spells each, so that we can hand them out fairly * frequently without giving the player every spell too quickly. Occasionally * they can have 2 or 4 spells, and that's fine too. It'd also be fine to have * 5 spells for a really special book. * * They're designed so that almost every spell shows up in 2 books. A few show * up in three books, a few in just one (especially lower-level spells that * will rarely be useful to players, level 9 spells, and some level 8 spells * which are intentionally rarer). * A spreadsheet accurate as of June 2021 can be found here: * https://docs.google.com/spreadsheets/d/1RCWRO_fltNQDAlbF2h1wx8ZZyulUsyGmNNvkkogxRoo/edit#gid=0 */ // This needs to be re-ordered when TAG_MAJOR_VERSION changes! static const vector<spell_type> spellbook_templates[] = { { // Book of Minor Magic SPELL_MAGIC_DART, SPELL_CALL_IMP, SPELL_MEPHITIC_CLOUD, }, { // Book of Conjurations SPELL_MAGIC_DART, SPELL_SEARING_RAY, SPELL_FULMINANT_PRISM, }, { // Book of Flames SPELL_FLAME_TONGUE, SPELL_CONJURE_FLAME, SPELL_INNER_FLAME, }, { // Book of Frost SPELL_FREEZE, SPELL_THROW_FROST, SPELL_THROW_ICICLE, }, { // Book of Dryads SPELL_SUMMON_FOREST, SPELL_SUMMON_MANA_VIPER, SPELL_SHADOW_CREATURES, }, { // Book of Fire SPELL_FIREBALL, SPELL_STARBURST, SPELL_IGNITION, }, { // Book of Ice SPELL_BOLT_OF_COLD, SPELL_FREEZING_CLOUD, SPELL_SIMULACRUM, }, { // Book of Spatial Translocations SPELL_BLINK, SPELL_BECKONING, SPELL_MANIFOLD_ASSAULT }, { // Book of Hexes SPELL_INNER_FLAME, SPELL_CAUSE_FEAR, SPELL_DISCORD, }, { // Young Poisoner's Handbook SPELL_STING, SPELL_POISONOUS_VAPOURS, SPELL_OLGREBS_TOXIC_RADIANCE, }, { // Book of Lightning SPELL_DISCHARGE, SPELL_LIGHTNING_BOLT, //SPELL_MAXWELLS_COUPLING }, { // Book of Death SPELL_ANIMATE_DEAD, SPELL_DEATH_CHANNEL, SPELL_HAUNT, }, { // Book of Misfortune SPELL_SLOW, SPELL_CONFUSING_TOUCH, SPELL_VIOLENT_UNRAVELLING, }, { // Book of Changes SPELL_BEASTLY_APPENDAGE, SPELL_STICKS_TO_SNAKES, SPELL_SPIDER_FORM, }, { // Book of Transfigurations SPELL_STONESKIN, SPELL_IRRADIATE, SPELL_DRAGON_FORM, }, { // Fen Folio SPELL_SUMMON_FOREST, SPELL_HYDRA_FORM, SPELL_SUMMON_HYDRA, }, { // Book of Vapours SPELL_POISONOUS_VAPOURS, SPELL_MEPHITIC_CLOUD, SPELL_FREEZING_CLOUD, }, { // Book of Necromancy SPELL_PAIN, SPELL_ANIMATE_SKELETON, SPELL_ANIMATE_DEAD, }, { // Book of Callings SPELL_SUMMON_SMALL_MAMMAL, SPELL_CALL_CANINE_FAMILIAR, SPELL_SUMMON_GUARDIAN_GOLEM, }, { // Book of Maledictions SPELL_CORONA, SPELL_HIBERNATION, SPELL_TUKIMAS_DANCE, }, { // Book of Air SPELL_SHOCK, SPELL_SWIFTNESS, SPELL_AIRSTRIKE, }, { // Book of the Sky SPELL_SUMMON_LIGHTNING_SPIRE, SPELL_STORM_FORM, //SPELL_MAXWELLS_COUPLING }, { // Book of the Warp SPELL_PORTAL_PROJECTILE, SPELL_FORCE_LANCE, SPELL_DISJUNCTION, }, { // Book of Envenomations SPELL_SPIDER_FORM, SPELL_OLGREBS_TOXIC_RADIANCE, SPELL_INTOXICATE, }, { // Book of Unlife SPELL_BORGNJORS_VILE_CLUTCH, SPELL_CIGOTUVIS_PLAGUE, SPELL_INFESTATION, }, { // Book of Control SPELL_CONFUSE, SPELL_CONTROL_UNDEAD, SPELL_ENGLACIATION, }, { // Book of Battle SPELL_INFUSION, SPELL_SONG_OF_SLAYING, SPELL_SPECTRAL_WEAPON, }, { // Book of Geomancy SPELL_SANDBLAST, SPELL_PASSWALL, SPELL_LRD, }, { // Book of Stone SPELL_STONESKIN, SPELL_BOLT_OF_MAGMA, SPELL_STATUE_FORM, }, { // Book of Wizardry SPELL_AGONY, SPELL_INVISIBILITY, SPELL_SPELLFORGED_SERVITOR, }, { // Book of Power SPELL_BATTLESPHERE, SPELL_IRON_SHOT, SPELL_SPELLFORGED_SERVITOR, }, { // Book of Cantrips SPELL_CORONA, SPELL_ANIMATE_SKELETON, SPELL_SUMMON_SMALL_MAMMAL, SPELL_APPORTATION, }, { // Book of Party Tricks SPELL_SUMMON_BUTTERFLIES, SPELL_APPORTATION, SPELL_INTOXICATE, }, { // Akashic Record SPELL_DISPERSAL, SPELL_CONTROLLED_BLINK, SPELL_SINGULARITY, }, { // Book of Debilitation SPELL_SLOW, SPELL_VAMPIRIC_DRAINING, SPELL_CONFUSING_TOUCH, }, { // Book of the Dragon SPELL_CAUSE_FEAR, SPELL_BOLT_OF_FIRE, SPELL_DRAGON_FORM, SPELL_DRAGON_CALL, }, { // Book of Burglary SPELL_SWIFTNESS, SPELL_PASSWALL, SPELL_INVISIBILITY, }, { // Book of Dreams SPELL_HIBERNATION, SPELL_SPIDER_FORM, SPELL_SHADOW_CREATURES, }, { // Book of Alchemy SPELL_SUBLIMATION_OF_BLOOD, SPELL_PETRIFY, SPELL_IRRADIATE, }, { // Book of Beasts SPELL_SUMMON_ICE_BEAST, SPELL_SUMMON_MANA_VIPER, SPELL_MONSTROUS_MENAGERIE, }, { // Book of Annihilations SPELL_CHAIN_LIGHTNING, SPELL_GLACIATE, SPELL_FIRE_STORM, }, { // Grand Grimoire SPELL_MALIGN_GATEWAY, SPELL_SUMMON_HORRIBLE_THINGS, SPELL_ELDRITCH_FORM, }, { // Necronomicon SPELL_BORGNJORS_REVIVIFICATION, SPELL_DEATHS_DOOR, SPELL_NECROMUTATION, }, { // The Memoirs of the virtuoso SPELL_ERINGYAS_ROOTSPIKE, SPELL_POISON_ARROW, SPELL_OLGREBS_LAST_MERCY, }, { // Book of Stalking SPELL_FULSOME_DISTILLATION, SPELL_EVAPORATE, SPELL_PETRIFY, }, { // Book of Frost2 SPELL_FREEZE, SPELL_FROZEN_RAMPARTS, SPELL_HAILSTORM, }, { // Book of the War Chants SPELL_SHRAPNEL_CURTAIN, SPELL_ELENENTAL_WEAPON, SPELL_FLAME_STRIKE, }, { // Tome of Valor SPELL_SONG_OF_SLAYING, SPELL_FLAME_STRIKE, SPELL_RING_OF_FLAMES, }, { // Book of Aid SPELL_SUMMON_HOODED_MALICE, SPELL_SUMMON_LIVELY_MASS, SPELL_HASTE, }, { }, // BOOK_RANDART_LEVEL { }, // BOOK_RANDART_THEME { }, // BOOK_MANUAL { }, // BOOK_BUGGY_DESTRUCTION { // Book of Spectacle SPELL_DAZZLING_SPRAY, SPELL_ISKENDERUNS_MYSTIC_BLAST, SPELL_STARBURST, }, { // Book of Winter SPELL_OZOCUBUS_ARMOUR, SPELL_ENGLACIATION, SPELL_SIMULACRUM, }, { // Book of Spheres SPELL_BATTLESPHERE, SPELL_FIREBALL, SPELL_CONJURE_BALL_LIGHTNING, SPELL_IOOD, }, { // Book of Armaments SPELL_STONE_ARROW, SPELL_ANIMATE_ARMOUR, SPELL_LEHUDIBS_CRYSTAL_SPEAR, }, { // Book of Pain SPELL_PAIN, SPELL_AGONY, SPELL_EXCRUCIATING_WOUNDS, }, { // Book of Decay SPELL_CORPSE_ROT, SPELL_DISPEL_UNDEAD, SPELL_DEATH_CHANNEL, }, { // Book of Displacement SPELL_BECKONING, SPELL_GRAVITAS, SPELL_TELEPORT_OTHER, }, { // Book of Rime SPELL_FROZEN_RAMPARTS, SPELL_ICE_FORM, SPELL_SUMMON_ICE_BEAST, }, { // Everburning Encyclopedia SPELL_CONJURE_FLAME, SPELL_IGNITE_POISON, SPELL_STICKY_FLAME, }, { // Book of Earth SPELL_STONE_ARROW, SPELL_BOLT_OF_MAGMA, SPELL_SHATTER, }, { // Ozocubu's Autobio SPELL_OZOCUBUS_ARMOUR, SPELL_OZOCUBUS_REFRIGERATION, }, { // Book of the Senses SPELL_DAZZLING_SPRAY, SPELL_AGONY, SPELL_SILENCE, }, { // Book of the Moon SPELL_GOLUBRIAS_PASSAGE, SPELL_SILENCE, SPELL_LEHUDIBS_CRYSTAL_SPEAR, }, { // Book of Blasting SPELL_FULMINANT_PRISM, SPELL_ISKENDERUNS_MYSTIC_BLAST, SPELL_LRD, }, { // Book of Iron SPELL_ANIMATE_ARMOUR, SPELL_BLADE_HANDS, SPELL_IRON_SHOT, }, { // Inescapable Atlas SPELL_BLINK, SPELL_MANIFOLD_ASSAULT, SPELL_STORM_FORM, }, { // Book of the Tundra SPELL_HAILSTORM, SPELL_ICE_FORM, SPELL_SIMULACRUM, }, { // Book of Storms SPELL_AIRSTRIKE, SPELL_SUMMON_LIGHTNING_SPIRE, SPELL_LIGHTNING_BOLT, }, { // Book of Weapons SPELL_ELENENTAL_WEAPON, SPELL_EXCRUCIATING_WOUNDS, SPELL_BLADE_HANDS, }, { // Book of Sloth SPELL_PETRIFY, SPELL_ENGLACIATION, SPELL_STATUE_FORM, }, { // Book of Blood SPELL_SUBLIMATION_OF_BLOOD, SPELL_VAMPIRIC_DRAINING, SPELL_SUMMON_HYDRA, }, { // There-And-Back Book SPELL_GRAVITAS, SPELL_TELEPORT_OTHER, SPELL_DISPERSAL, }, { // Book of Dangerous Friends SPELL_SUMMON_GUARDIAN_GOLEM, SPELL_IOOD, SPELL_SPELLFORGED_SERVITOR, }, { // Book of Touch SPELL_DISCHARGE, SPELL_STICKY_FLAME, SPELL_DISPEL_UNDEAD, }, { // Book of Chaos SPELL_CONJURE_BALL_LIGHTNING, SPELL_DISJUNCTION, SPELL_DISCORD, }, { // Unrestrained Analects SPELL_OLGREBS_TOXIC_RADIANCE, SPELL_OZOCUBUS_REFRIGERATION, SPELL_IGNITION, }, { // Great Wizards, Vol. II SPELL_INTOXICATE, SPELL_BORGNJORS_VILE_CLUTCH, SPELL_NOXIOUS_BOG, }, { // Great Wizards, Vol. VII SPELL_TUKIMAS_DANCE, SPELL_GOLUBRIAS_PASSAGE, SPELL_VIOLENT_UNRAVELLING, }, { // Trismegistus Codex SPELL_IGNITE_POISON, SPELL_MEPHITIC_CLOUD, SPELL_BOLT_OF_MAGMA, }, { // Book of the Hunter SPELL_CALL_CANINE_FAMILIAR, SPELL_PORTAL_PROJECTILE, SPELL_LEDAS_LIQUEFACTION, }, { // Book of Enchantments SPELL_CONDENSATION_SHIELD, SPELL_DEFLECT_MISSILES, SPELL_HASTE, }, { // Book of Toxic SPELL_NOXIOUS_BOG, SPELL_ERINGYAS_ROOTSPIKE, SPELL_VENOM_BOLT, }, { // Book of the Tempests SPELL_IGNITION, SPELL_TORNADO, SPELL_SHATTER, }, { // Book of Summonings SPELL_RECALL, SPELL_AURA_OF_ABJURATION, SPELL_SUMMON_LIVELY_MASS, }, { // Book of Pandemonium SPELL_CALL_IMP, SPELL_SUMMON_DEMON, SPELL_SUMMON_GREATER_DEMON, }, { // Book of Liquefaction SPELL_LEDAS_LIQUEFACTION, SPELL_WILL_OF_EARTH, SPELL_WALL_MELTING, }, { // Book of Minor Buff SPELL_REPEL_MISSILES, SPELL_SHROUD_OF_GOLUBRIA, SPELL_REGENERATION, }, { // Book of Shields SPELL_INSULATION, SPELL_CONDENSATION_SHIELD, SPELL_BARRIER, }, { // Book of Darts SPELL_MAGIC_DART, SPELL_THROW_FROST, SPELL_THROW_FLAME, }, { // Book of Mesmerise SPELL_SLOW, SPELL_CONFUSE, SPELL_FORCE_LANCE, }, { // Book of Spy SPELL_WALL_MELTING, SPELL_INVISIBILITY, SPELL_DARKNESS, }, { // Book of Battlemage SPELL_REGENERATION, SPELL_DEFLECT_MISSILES, SPELL_TORNADO, }, { // Book of Plagues SPELL_CIGOTUVIS_PLAGUE, SPELL_BOLT_OF_DRAINING, SPELL_SUMMON_HOODED_MALICE, }, { // Book of Betrayal SPELL_AURA_OF_ABJURATION, SPELL_SUMMON_GREATER_DEMON, SPELL_MALIGN_GATEWAY, }, }; COMPILE_CHECK(ARRAYSZ(spellbook_templates) == NUM_BOOKS);
18.244733
97
0.695301
[ "vector" ]
fa32f11a8432b6492e4c9e2aca78c695a7c5f30a
19,061
c
C
src/slave/kprop.c
quiggs/krb5-krb5-1.2
e9db499babad1b7f40d13813515942cc14e9fae1
[ "MIT", "Unlicense" ]
null
null
null
src/slave/kprop.c
quiggs/krb5-krb5-1.2
e9db499babad1b7f40d13813515942cc14e9fae1
[ "MIT", "Unlicense" ]
null
null
null
src/slave/kprop.c
quiggs/krb5-krb5-1.2
e9db499babad1b7f40d13813515942cc14e9fae1
[ "MIT", "Unlicense" ]
null
null
null
/* * slave/kprop.c * * Copyright 1990,1991 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, 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 M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * * */ #include <errno.h> #include <stdio.h> #include <ctype.h> #include <sys/file.h> #include <signal.h> #include <string.h> #include <sys/types.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/param.h> #include <netdb.h> #include <fcntl.h> #include "k5-int.h" #include "com_err.h" #include "kprop.h" static char *kprop_version = KPROP_PROT_VERSION; char *progname = 0; int debug = 0; char *srvtab = 0; char *slave_host; char *realm = 0; char *file = KPROP_DEFAULT_FILE; short port = 0; krb5_principal my_principal; /* The Kerberos principal we'll be */ /* running under, initialized in */ /* get_tickets() */ krb5_ccache ccache; /* Credentials cache which we'll be using */ /* krb5_creds my_creds; /* My credentials */ krb5_creds creds; krb5_address sender_addr; krb5_address receiver_addr; void PRS PROTOTYPE((int, char **)); void get_tickets PROTOTYPE((krb5_context)); static void usage PROTOTYPE((void)); krb5_error_code open_connection PROTOTYPE((char *, int *, char *, int)); void kerberos_authenticate PROTOTYPE((krb5_context, krb5_auth_context *, int, krb5_principal, krb5_creds **)); int open_database PROTOTYPE((krb5_context, char *, int *)); void close_database PROTOTYPE((krb5_context, int)); void xmit_database PROTOTYPE((krb5_context, krb5_auth_context, krb5_creds *, int, int, int)); void send_error PROTOTYPE((krb5_context, krb5_creds *, int, char *, krb5_error_code)); void update_last_prop_file PROTOTYPE((char *, char *)); static void usage() { fprintf(stderr, "\nUsage: %s [-r realm] [-f file] [-d] [-P port] [-s srvtab] slave_host\n\n", progname); exit(1); } int main(argc, argv) int argc; char **argv; { int fd, database_fd, database_size; krb5_error_code retval; krb5_context context; krb5_creds *my_creds; krb5_auth_context auth_context; char Errmsg[256]; retval = krb5_init_context(&context); if (retval) { com_err(argv[0], retval, "while initializing krb5"); exit(1); } PRS(argc, argv); get_tickets(context); database_fd = open_database(context, file, &database_size); if (retval = open_connection(slave_host, &fd, Errmsg, sizeof(Errmsg))) { com_err(progname, retval, "%s while opening connection to %s", Errmsg, slave_host); exit(1); } if (fd < 0) { fprintf(stderr, "%s: %s while opening connection to %s\n", progname, Errmsg, slave_host); exit(1); } kerberos_authenticate(context, &auth_context, fd, my_principal, &my_creds); xmit_database(context, auth_context, my_creds, fd, database_fd, database_size); update_last_prop_file(slave_host, file); printf("Database propagation to %s: SUCCEEDED\n", slave_host); krb5_free_cred_contents(context, my_creds); close_database(context, database_fd); exit(0); } void PRS(argc, argv) int argc; char **argv; { register char *word, ch; progname = *argv++; while (--argc && (word = *argv++)) { if (*word == '-') { word++; while (word && (ch = *word++)) { switch(ch){ case 'r': if (*word) realm = word; else realm = *argv++; if (!realm) usage(); word = 0; break; case 'f': if (*word) file = word; else file = *argv++; if (!file) usage(); word = 0; break; case 'd': debug++; break; case 'P': if (*word) port = htons(atoi(word)); else port = htons(atoi(*argv++)); if (!port) usage(); word = 0; break; case 's': if (*word) srvtab = word; else srvtab = *argv++; if (!srvtab) usage(); word = 0; break; default: usage(); } } } else { if (slave_host) usage(); else slave_host = word; } } if (!slave_host) usage(); } void get_tickets(context) krb5_context context; { char my_host_name[MAXHOSTNAMELEN]; char buf[BUFSIZ]; char *cp; struct hostent *hp; krb5_error_code retval; static char tkstring[] = "/tmp/kproptktXXXXXX"; krb5_keytab keytab = NULL; /* * Figure out what tickets we'll be using to send stuff */ retval = krb5_sname_to_principal(context, NULL, NULL, KRB5_NT_SRV_HST, &my_principal); if (retval) { com_err(progname, errno, "while setting client principal name"); exit(1); } if (realm) { (void) krb5_xfree(krb5_princ_realm(context, my_principal)->data); krb5_princ_set_realm_length(context, my_principal, strlen(realm)); krb5_princ_set_realm_data(context, my_principal, strdup(realm)); } #if 0 krb5_princ_type(context, my_principal) = KRB5_NT_PRINCIPAL; #endif /* * Initialize cache file which we're going to be using */ (void) mktemp(tkstring); sprintf(buf, "FILE:%s", tkstring); if (retval = krb5_cc_resolve(context, buf, &ccache)) { com_err(progname, retval, "while opening credential cache %s", buf); exit(1); } if (retval = krb5_cc_initialize(context, ccache, my_principal)) { com_err (progname, retval, "when initializing cache %s", buf); exit(1); } /* * Get the tickets we'll need. * * Construct the principal name for the slave host. */ memset((char *)&creds, 0, sizeof(creds)); retval = krb5_sname_to_principal(context, slave_host, KPROP_SERVICE_NAME, KRB5_NT_SRV_HST, &creds.server); if (retval) { com_err(progname, errno, "while setting server principal name"); (void) krb5_cc_destroy(context, ccache); exit(1); } if (realm) { (void) krb5_xfree(krb5_princ_realm(context, creds.server)->data); krb5_princ_set_realm_length(context, creds.server, strlen(realm)); krb5_princ_set_realm_data(context, creds.server, strdup(realm)); } /* * Now fill in the client.... */ if (retval = krb5_copy_principal(context, my_principal, &creds.client)) { com_err(progname, retval, "While copying client principal"); (void) krb5_cc_destroy(context, ccache); exit(1); } if (srvtab) { if (retval = krb5_kt_resolve(context, srvtab, &keytab)) { com_err(progname, retval, "while resolving keytab"); (void) krb5_cc_destroy(context, ccache); exit(1); } } retval = krb5_get_in_tkt_with_keytab(context, 0, 0, NULL, NULL, keytab, ccache, &creds, 0); if (retval) { com_err(progname, retval, "while getting initial ticket\n"); (void) krb5_cc_destroy(context, ccache); exit(1); } if (keytab) (void) krb5_kt_close(context, keytab); /* * Now destroy the cache right away --- the credentials we * need will be in my_creds. */ if (retval = krb5_cc_destroy(context, ccache)) { com_err(progname, retval, "while destroying ticket cache"); exit(1); } } krb5_error_code open_connection(host, fd, Errmsg, ErrmsgSz) char *host; int *fd; char *Errmsg; int ErrmsgSz; { int s; krb5_error_code retval; struct hostent *hp; register struct servent *sp; struct sockaddr_in sin; int socket_length; hp = gethostbyname(host); if (hp == NULL) { (void) sprintf(Errmsg, "%s: unknown host", host); *fd = -1; return(0); } sin.sin_family = hp->h_addrtype; memcpy((char *)&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr)); if(!port) { sp = getservbyname(KPROP_SERVICE, "tcp"); if (sp == 0) { (void) strncpy(Errmsg, KPROP_SERVICE, ErrmsgSz - 1); Errmsg[ErrmsgSz - 1] = '\0'; (void) strncat(Errmsg, "/tcp: unknown service", ErrmsgSz - 1 - strlen(Errmsg)); *fd = -1; return(0); } sin.sin_port = sp->s_port; } else sin.sin_port = port; s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { (void) sprintf(Errmsg, "in call to socket"); return(errno); } if (connect(s, (struct sockaddr *)&sin, sizeof sin) < 0) { retval = errno; close(s); (void) sprintf(Errmsg, "in call to connect"); return(retval); } *fd = s; /* * Set receiver_addr and sender_addr. */ receiver_addr.addrtype = ADDRTYPE_INET; receiver_addr.length = sizeof(sin.sin_addr); receiver_addr.contents = (krb5_octet *) malloc(sizeof(sin.sin_addr)); memcpy((char *) receiver_addr.contents, (char *) &sin.sin_addr, sizeof(sin.sin_addr)); socket_length = sizeof(sin); if (getsockname(s, (struct sockaddr *)&sin, &socket_length) < 0) { retval = errno; close(s); (void) sprintf(Errmsg, "in call to getsockname"); return(retval); } sender_addr.addrtype = ADDRTYPE_INET; sender_addr.length = sizeof(sin.sin_addr); sender_addr.contents = (krb5_octet *) malloc(sizeof(sin.sin_addr)); memcpy((char *) sender_addr.contents, (char *) &sin.sin_addr, sizeof(sin.sin_addr)); return(0); } void kerberos_authenticate(context, auth_context, fd, me, new_creds) krb5_context context; krb5_auth_context *auth_context; int fd; krb5_principal me; krb5_creds ** new_creds; { krb5_error_code retval; krb5_error *error = NULL; krb5_ap_rep_enc_part *rep_result; if (retval = krb5_auth_con_init(context, auth_context)) exit(1); krb5_auth_con_setflags(context, *auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE); if (retval = krb5_auth_con_setaddrs(context, *auth_context, &sender_addr, &receiver_addr)) { com_err(progname, retval, "in krb5_auth_con_setaddrs"); exit(1); } if (retval = krb5_sendauth(context, auth_context, (void *)&fd, kprop_version, me, creds.server, AP_OPTS_MUTUAL_REQUIRED, NULL, &creds, NULL, &error, &rep_result, new_creds)) { com_err(progname, retval, "while authenticating to server"); if (error) { if (error->error == KRB_ERR_GENERIC) { if (error->text.data) fprintf(stderr, "Generic remote error: %s\n", error->text.data); } else if (error->error) { com_err(progname, error->error + ERROR_TABLE_BASE_krb5, "signalled from server"); if (error->text.data) fprintf(stderr, "Error text from server: %s\n", error->text.data); } krb5_free_error(context, error); } exit(1); } krb5_free_ap_rep_enc_part(context, rep_result); } char * dbpathname; /* * Open the Kerberos database dump file. Takes care of locking it * and making sure that the .ok file is more recent that the database * dump file itself. * * Returns the file descriptor of the database dump file. Also fills * in the size of the database file. */ int open_database(context, data_fn, size) krb5_context context; char *data_fn; int *size; { int fd; int err; struct stat stbuf, stbuf_ok; char *data_ok_fn; static char ok[] = ".dump_ok"; dbpathname = strdup(data_fn); if (!dbpathname) { com_err(progname, ENOMEM, "allocating database file name '%s'", data_fn); exit(1); } if ((fd = open(dbpathname, O_RDONLY)) < 0) { com_err(progname, errno, "while trying to open %s", dbpathname); exit(1); } err = krb5_lock_file(context, fd, KRB5_LOCKMODE_SHARED|KRB5_LOCKMODE_DONTBLOCK); if (err == EAGAIN || err == EWOULDBLOCK || errno == EACCES) { com_err(progname, 0, "database locked"); exit(1); } else if (err) { com_err(progname, err, "while trying to lock '%s'", dbpathname); exit(1); } if (fstat(fd, &stbuf)) { com_err(progname, errno, "while trying to stat %s", data_fn); exit(1); } if ((data_ok_fn = (char *) malloc(strlen(data_fn)+strlen(ok)+1)) == NULL) { com_err(progname, ENOMEM, "while trying to malloc data_ok_fn"); exit(1); } strcpy(data_ok_fn, data_fn); strcat(data_ok_fn, ok); if (stat(data_ok_fn, &stbuf_ok)) { com_err(progname, errno, "while trying to stat %s", data_ok_fn); free(data_ok_fn); exit(1); } free(data_ok_fn); if (stbuf.st_mtime > stbuf_ok.st_mtime) { com_err(progname, 0, "'%s' more recent than '%s'.", data_fn, data_ok_fn); exit(1); } *size = stbuf.st_size; return(fd); } void close_database(context, fd) krb5_context context; int fd; { int err; if (err = krb5_lock_file(context, fd, KRB5_LOCKMODE_UNLOCK)) com_err(progname, err, "while unlocking database '%s'", dbpathname); free(dbpathname); (void)close(fd); return; } /* * Now we send over the database. We use the following protocol: * Send over a KRB_SAFE message with the size. Then we send over the * database in blocks of KPROP_BLKSIZE, encrypted using KRB_PRIV. * Then we expect to see a KRB_SAFE message with the size sent back. * * At any point in the protocol, we may send a KRB_ERROR message; this * will abort the entire operation. */ void xmit_database(context, auth_context, my_creds, fd, database_fd, database_size) krb5_context context; krb5_auth_context auth_context; krb5_creds *my_creds; int fd; int database_fd; int database_size; { krb5_int32 send_size, sent_size, n; krb5_data inbuf, outbuf; char buf[KPROP_BUFSIZ]; krb5_error_code retval; krb5_error *error; /* * Send over the size */ send_size = htonl(database_size); inbuf.data = (char *) &send_size; inbuf.length = sizeof(send_size); /* must be 4, really */ /* KPROP_CKSUMTYPE */ if (retval = krb5_mk_safe(context, auth_context, &inbuf, &outbuf, NULL)) { com_err(progname, retval, "while encoding database size"); send_error(context, my_creds, fd, "while encoding database size", retval); exit(1); } if (retval = krb5_write_message(context, (void *) &fd, &outbuf)) { krb5_free_data_contents(context, &outbuf); com_err(progname, retval, "while sending database size"); exit(1); } krb5_free_data_contents(context, &outbuf); /* * Initialize the initial vector. */ if (retval = krb5_auth_con_initivector(context, auth_context)) { send_error(context, my_creds, fd, "failed while initializing i_vector", retval); com_err(progname, retval, "while allocating i_vector"); exit(1); } /* * Send over the file, block by block.... */ inbuf.data = buf; sent_size = 0; while (n = read(database_fd, buf, sizeof(buf))) { inbuf.length = n; if (retval = krb5_mk_priv(context, auth_context, &inbuf, &outbuf, NULL)) { sprintf(buf, "while encoding database block starting at %d", sent_size); com_err(progname, retval, buf); send_error(context, my_creds, fd, buf, retval); exit(1); } if (retval = krb5_write_message(context, (void *)&fd,&outbuf)) { krb5_free_data_contents(context, &outbuf); com_err(progname, retval, "while sending database block starting at %d", sent_size); exit(1); } krb5_free_data_contents(context, &outbuf); sent_size += n; if (debug) printf("%d bytes sent.\n", sent_size); } if (sent_size != database_size) { com_err(progname, 0, "Premature EOF found for database file!"); send_error(context, my_creds, fd,"Premature EOF found for database file!", KRB5KRB_ERR_GENERIC); exit(1); } /* * OK, we've sent the database; now let's wait for a success * indication from the remote end. */ if (retval = krb5_read_message(context, (void *) &fd, &inbuf)) { com_err(progname, retval, "while reading response from server"); exit(1); } /* * If we got an error response back from the server, display * the error message */ if (krb5_is_krb_error(&inbuf)) { if (retval = krb5_rd_error(context, &inbuf, &error)) { com_err(progname, retval, "while decoding error response from server"); exit(1); } if (error->error == KRB_ERR_GENERIC) { if (error->text.data) fprintf(stderr, "Generic remote error: %s\n", error->text.data); } else if (error->error) { com_err(progname, error->error + ERROR_TABLE_BASE_krb5, "signalled from server"); if (error->text.data) fprintf(stderr, "Error text from server: %s\n", error->text.data); } krb5_free_error(context, error); exit(1); } if (retval = krb5_rd_safe(context,auth_context,&inbuf,&outbuf,NULL)) { com_err(progname, retval, "while decoding final size packet from server"); exit(1); } memcpy((char *)&send_size, outbuf.data, sizeof(send_size)); send_size = ntohl(send_size); if (send_size != database_size) { com_err(progname, 0, "Kpropd sent database size %d, expecting %d", send_size, database_size); exit(1); } free(outbuf.data); free(inbuf.data); } void send_error(context, my_creds, fd, err_text, err_code) krb5_context context; krb5_creds *my_creds; int fd; char *err_text; krb5_error_code err_code; { krb5_error error; const char *text; krb5_data outbuf; memset((char *)&error, 0, sizeof(error)); krb5_us_timeofday(context, &error.ctime, &error.cusec); error.server = my_creds->server; error.client = my_principal; error.error = err_code - ERROR_TABLE_BASE_krb5; if (error.error > 127) error.error = KRB_ERR_GENERIC; if (err_text) text = err_text; else text = error_message(err_code); error.text.length = strlen(text) + 1; if (error.text.data = malloc(error.text.length)) { strcpy(error.text.data, text); if (!krb5_mk_error(context, &error, &outbuf)) { (void) krb5_write_message(context, (void *)&fd,&outbuf); krb5_free_data_contents(context, &outbuf); } free(error.text.data); } } void update_last_prop_file(hostname, file_name) char *hostname; char *file_name; { /* handle slave locking/failure stuff */ char *file_last_prop; int fd; static char last_prop[]=".last_prop"; if ((file_last_prop = (char *)malloc(strlen(file_name) + strlen(hostname) + 1 + strlen(last_prop) + 1)) == NULL) { com_err(progname, ENOMEM, "while allocating filename for update_last_prop_file"); return; } strcpy(file_last_prop, file_name); strcat(file_last_prop, "."); strcat(file_last_prop, hostname); strcat(file_last_prop, last_prop); if ((fd = THREEPARAMOPEN(file_last_prop, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) { com_err(progname, errno, "while creating 'last_prop' file, '%s'", file_last_prop); free(file_last_prop); return; } write(fd, "", 1); free(file_last_prop); close(fd); return; }
26.436893
94
0.673522
[ "vector" ]
fa331bcb6f96e4ebf0aea658f6eff79f59116d42
3,494
h
C
Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.h
lassoan/ITK
4634cb0490934f055065230e3db64df8f546b72a
[ "Apache-2.0" ]
2
2019-09-15T10:17:06.000Z
2019-09-15T10:19:06.000Z
Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.h
lassoan/ITK
4634cb0490934f055065230e3db64df8f546b72a
[ "Apache-2.0" ]
null
null
null
Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.h
lassoan/ITK
4634cb0490934f055065230e3db64df8f546b72a
[ "Apache-2.0" ]
1
2021-09-23T08:33:37.000Z
2021-09-23T08:33:37.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkBinaryThresholdSpatialFunction_h #define itkBinaryThresholdSpatialFunction_h #include "itkSpatialFunction.h" #include "itkImageBase.h" namespace itk { /** \class BinaryThresholdSpatialFunction * \brief A spatial functions that returns if the internal spatial function * is within user specified thresholds. * * BinaryThresholdSpatialFunction is a wrapper class for an internal * spatial function and returns true if it is within user specified * thresholds and false otherwise. * * This class is templated over the internal spatial function type. * * \sa SpatialFunction * * * \ingroup ITKCommon */ template <typename TFunction> class ITK_TEMPLATE_EXPORT BinaryThresholdSpatialFunction : public SpatialFunction<bool, TFunction::ImageDimension, typename TFunction::InputType> { public: ITK_DISALLOW_COPY_AND_ASSIGN(BinaryThresholdSpatialFunction); /** Standard class type aliases. */ using Self = BinaryThresholdSpatialFunction; using Superclass = SpatialFunction<bool, TFunction::ImageDimension, typename TFunction::InputType>; using Pointer = SmartPointer<Self>; using ConstPointer = SmartPointer<const Self>; /** Run-time type information (and related methods). */ itkTypeMacro(BinaryThresholdSpatialFunction, SpatialFunction); /** New macro for creation of through the object factory. */ itkNewMacro(Self); /** OutputType type alias support. */ using OutputType = typename Superclass::OutputType; /** InputType type alias support. */ using InputType = typename TFunction::InputType; /** Underlying function type. */ using FunctionType = TFunction; /** Underlying function output type. */ using FunctionOutputType = typename TFunction::OutputType; /** Set/Get the lower threshold. */ itkSetMacro(LowerThreshold, FunctionOutputType); itkGetConstReferenceMacro(LowerThreshold, FunctionOutputType); /** Set/Get the upper threshold. */ itkSetMacro(UpperThreshold, FunctionOutputType); itkGetConstReferenceMacro(UpperThreshold, FunctionOutputType); /** Set/Get the underlying function. */ itkSetObjectMacro(Function, FunctionType); itkGetModifiableObjectMacro(Function, FunctionType); /** Evaluate the function at a given position. */ OutputType Evaluate(const InputType & point) const override; protected: BinaryThresholdSpatialFunction(); ~BinaryThresholdSpatialFunction() override = default; void PrintSelf(std::ostream & os, Indent indent) const override; FunctionOutputType m_LowerThreshold; FunctionOutputType m_UpperThreshold; typename FunctionType::Pointer m_Function; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION # include "itkBinaryThresholdSpatialFunction.hxx" #endif #endif
32.654206
101
0.73526
[ "object" ]
fa33b76dacdb483992e9cdd0f8271b3ae1e50980
4,931
h
C
argparse/argparse/argparse.h
rolzwy7/argparse
69405aac7f19da34e3c272a280702a306733e8db
[ "MIT" ]
null
null
null
argparse/argparse/argparse.h
rolzwy7/argparse
69405aac7f19da34e3c272a280702a306733e8db
[ "MIT" ]
null
null
null
argparse/argparse/argparse.h
rolzwy7/argparse
69405aac7f19da34e3c272a280702a306733e8db
[ "MIT" ]
null
null
null
// MIT License // // Copyright(c) 2018 Bartosz Nowakowski (https://github.com/rolzwy7) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <string> #include <vector> #include <map> #include <sstream> #include <regex> namespace argparse { enum ArgErrorCode { NO_ERROR, POSITIONAL_ERROR, DUPLICATE_ARGUMENT_ERROR, INVALID_OS_SEP, RAW_VECTOR_OUT_OF_RANGE, OPTIONAL_PROVIDED_WITH_NO_VALUE, CONVERT_ARG_ERROR }; struct Error: public std::exception { ArgErrorCode code; const char * msg; Error(ArgErrorCode code, const char * msg); Error(); }; enum class ArgSpecialBehavior { None, DROP_POSITIONAL_CHECK }; enum class ArgType { tStoreFalse, tStoreTrue, tString, tFloat, tDouble, tInt }; enum class ArgImportance { iPositional, iOptional }; struct ArgConfig { std::string arg_name; std::string arg_help; ArgType arg_type; ArgImportance arg_imp; ArgSpecialBehavior arg_sb; bool arg_set; std::string arg_str_value; int pos; ArgConfig(std::string arg_name, std::string arg_help, ArgType arg_type, ArgImportance arg_imp, ArgSpecialBehavior arg_sb, int pos); ArgConfig(); }; class ArgumentParser { public: inline bool get_arg(std::string name, std::string & target) { target = (_arg_map_string.count(name)) ? _arg_map_string[name] : ""; return (target != "") ? true : false; } inline bool get_arg(std::string name, int & target) { target = (_arg_map_int.count(name)) ? _arg_map_int[name] : 0; return (target != 0) ? true : false; } inline bool get_arg(std::string name, float & target) { target = (_arg_map_float.count(name)) ? _arg_map_float[name] : 0; return (target != 0) ? true : false; } inline bool get_arg(std::string name, double & target) { target = (_arg_map_double.count(name)) ? _arg_map_double[name] : 0; return (target != 0) ? true : false; } inline bool get_arg(std::string name, bool & target) { if (_arg_map_bool.count(name)) { target = _arg_map_bool[name]; return true; } return false; } private: // maps std::map<std::string, std::string> _arg_map_string; std::map<std::string, int> _arg_map_int; std::map<std::string, double> _arg_map_double; std::map<std::string, float> _arg_map_float; std::map<std::string, bool> _arg_map_bool; unsigned short arguments_count; unsigned short positional_count; unsigned short optional_count; size_t _max_arg_name_len; int _argc; std::string exec_name; std::string description; std::string author; char os_sep; std::vector<std::string> raw_arguments; std::vector<std::string> sanitized_arguments; std::map<std::string, ArgConfig> _arguments; bool _drop_positional; std::regex re_optional_argument; std::regex re_float; std::regex re_int; void _init(); void _parse_exec_name(); void _parse_positional(); void _parse_optional(); void _sanitize_arguments_vector(); void _convert_arguments(); public: ArgumentParser(const std::string & description, const std::string & app_name, const std::string & author); ArgumentParser(); ~ArgumentParser(); bool parse_check_help(int argc, char * argv[]); Error parse_args(int argc, char * argv[]); inline unsigned short get_arguments_count() const { return this->arguments_count; } bool is_optional(std::string str); inline bool is_drop_positional_check() { return this->_drop_positional; } inline std::string get_description() const { return this->description; } inline void set_description(std::string description) { this->description = description; } void add_argument( std::string arg_name, std::string arg_help, ArgType arg_type = ArgType::tString, ArgImportance arg_imp = ArgImportance::iPositional, ArgSpecialBehavior arg_sb = ArgSpecialBehavior::None ); std::ostringstream ret_help(); }; } // argparse
27.093407
108
0.718313
[ "vector" ]
fa386ce4ab976c0831bea96530beced50eb94f18
9,075
h
C
rtl/pdp8.h
Rki009/PDP-8
530b30de330588b638e0672787b8a55289610ee6
[ "Unlicense" ]
null
null
null
rtl/pdp8.h
Rki009/PDP-8
530b30de330588b638e0672787b8a55289610ee6
[ "Unlicense" ]
null
null
null
rtl/pdp8.h
Rki009/PDP-8
530b30de330588b638e0672787b8a55289610ee6
[ "Unlicense" ]
null
null
null
// PDP-8/E - PDP-8/E, 12 bit processor, (C) Ron K. Irvine // // Notes: // Variant: PDP-8/E, 1970, Cost: PDP-8/E - $6,500 // // // Skips: // SMA SZA = GE - Great than or Equal to Zero // SPA SNA = LT - Less than Zero // SZA = EQ - Equal to Zero // // MNEMONIC CODE OPERATION // SZA SNl 7460 Skip if AC = 0 or L = 1 or both. // SNA SZl 7470 Skip if AC != O and L = 0 // SMA SNl 7520 Skip if AC < 0 or L = 1 or both. // SPA SZl 7530 Skip if AC >= and L = 0 // SMA SZA 7540 Skip if AC <= 0 // SPA SNA 7550 Skip if AC > 0 // SMA SZA SNl 7560 Skip if AC~O or L = 1 or both. // SPA SNA SZl 7570 Skip if AC >0 and L = O. // Comparison: // CLA CLL / AC = 0 // TAD B / AC = B // CML CMA IAC / NEG - AC = -B // TAD A / AC = (A-B) // Sxx CLA / Test AC, Clear AC // JMP FAIL // // SKIP IF UNSIGNED SIGNED // A NE B SNA SNA // A LT B SNL SMA // A LE B SNL SZA SMA SZA // A EQ B SZA SZA // A GE B SZL SPA // A GT B SZL SNA SPA SNA // Combination Instructions: // CIA 7041 Complement and Increment the AC, = Negate the AC // STL 7120 Set the LINK, LINK <= 1 // STA 7240 Set the AC, AC <= 7777 // GLK 7204 Get the LINK, {11{0}, AC} <= LINK // LAS Load AC with the Switch Register // CLA IAC Set the AC to 1, AC <= 1 // IOTs For Sample Interface // 6520 Not used. // 6521 Transfer contents of the AC to the output buffer. // 6522 Clear the AC. // 6523 Transfer the contents of the AC to the output buffer and clear the AC. // 6524 Transfer the contents of the AC to the output buffer (OR transfer). // 6525 Clear the flag. // 6526 Transfer the contents of the AC to the output buffer (jam transfer). // 6527 Skip if flag set (1). // CPU // SKON 6000 Skip if interrupt ON, and turn OFF // ION 6001 Turn interrupt ON. The interrupt system is enabled after the // CPU executes the next sequential instruction. // IOF 6002 Turn interrupt OFF // SRQ 6003 Skip interrupt request // GTF 6004 Get interrupt flags // bit 0 - Link // bit 1 - Greater than flag // bit 2 - INT request bus // bit 3 - Interrupt Inhibit FF // bit 4 - Interrupt Enable FF // bit 5 - User flag // bit 6 - 11 - Save Field Register // RTF 6005 Restore interrupt flags. The interrupt system is enabled after the // CPU executes the next sequential instruction. // SGT 6006 Skip on Greater Than flag, ignored // CAF 6007 Clear All Flags - AC and Link are cleared. Interrupt system is disabled. // Keyboard/Reader // KSF 6031 Skip the next instruction when the keyboard buffer register is loaded // with an ASCII symbol (causing the keyboard flag to be raised). // KCC 6032 Clear AC, clear keyboard flag. // KRS 6034 Transfer the contents of the keyboard buffer into the AC. // KRB 6036 Transfer the contents of the keyboard buffer into the AC, clear the // keyboard flag. // Printer/Punch // TSF 6041 Skip the next instruction if the printer flag is set to 1. // TCF 6043 Clear the printer flag. // TPC 6044 Load the printer buffer register with the contents of the AC, select and // print the character. (The flag is raised when the action is completed.) // TLS 6046 Clear the printer flag, transfer the contents of the ACinto the printer buffer, // select and print the character. (The flag is raised when the action is completed.) // Summary of IOT Instructions, Harris HD-6102 // MEDIC - Memory Extension/DMA/Interval Time/Controller // GTF 6004 1 0 0 1 (1) Get Flags // IOF 6002 1 1 0 0 (2) I interrupts Off // RTF 6005 1 1 1 1 (3) Restore Flags // CAF 6007 1 1 1 1 (4) Clear All Flags // CDF 62N1 1 1 1 1 Change Data Field // CIF 62N2 1 1 1 1 Change I instruction Field // CDF CIF 62N3 1 1 1 1 Combination of CDF & CIF // RDF 6214 1 1 0 1 Read Data Field // RIF 6224 1 1 0 1 Read Instruction Field // RIB 6234 1 1 0 1 Read I interrupt Buffer // RMF 6244 1 1 1 1 Restore Memory Field // LlF 6254 1 1 1 1 Load I instruction Field // CLZE 6130 1 1 1 1 Clear Clock Enable Register per AC // CLSK 6131 0 1 1 1 Skip on Clock Overflow Interrupt // CLOE 6132 1 1 1 1 Set Clock Enable Register per AC // CLAB 6133 1 1 1 1 AC to Clock Buffer // CLEN 6134 1 0 0 1 Load Clock Enable Register into AC // CLSA 6135 1 0 0 1 Clock Status to AC // CLBA 6136 1 0 0 1 Clock Buffer to AC // CLCA 6137 1 0 0 1 Clock Counter to AC // LCAR 6205 1 0 1 1 Load Current Address Register // RCAR 6215 1 0 0 1 Read Current Address Register // LWCR 6225 1 0 1 1 Load Word Count Register // LEAR 62N6 1 1 1 1 Load Extended Current Address Register // REAR 6235 1 1 0 1 Read Extended Current Address Register // LFSR 6245 1 0 1 1 Load DMA Flags and Status Register // RFSR 6255 1 1 0 1 Read DMA Flags and Status Register // SKOF 6265 0 1 1 1 Skip on Word Count Overflow // WRVR 6275 1 0 1 1 Write Vector Register // IOT Device Allocation PDP-8E // DEVICE SELECTION // PDP-8/E DEVICE TYPE // 00 Internal lOT's // 01 DEC High Speed Reader // 02 DEC High Speed Punch // 03 DEC Teletype Keyboard/Reader // 04 DEC Teletype Printer/Punch // 05 User Definable // 06,07 User Definable // 10,11 User Definable // 12 User Definable // 13 MEDIC Real Time Clock // 14,15 User Definable // 16,17 User Definable // 20,21 MED IC Extended Memory Control and DMA // 22,23 MED IC Extended Memory Control and DMA // 24,25 MEDIC Extended Memory Control and DMA // 26,27 MED IC Extended Memory Control and DMA // 30,31 HD-6103 Pia No. One // 32,33 HD-6103 Pia No. Two // 34,35 HD-6103 Pia No. Three // 36,37 HD-6103 Pia No. Four // 40,41 User Definable // 42,43 User Definable // 44,45 User Definable // 46,47 User Definable // 50,51 User Definable // 52,53 User Definable // 54,55 User Definable // 56,57 User Definable // 60,61 User Definable // 62,63 User Definable // 64,65 User Definable // 66,67 DEC Line Printer ~ 66 // 70,71 User Definable // 72,73 User Definable // 74,75 DEC Floppy Disk Drive ~ 75 // 76,77 User Definable // New PDP-8/E Instructions // OCTAL NEW INSTRUCTION // CODE (MNEMONIC) PREVIOUS FUNCTION // 6000 SKON NOP // 6003 SRQ ION // 6004 GIF ADC or NOP // 6005 RTF ION (ORed with ADC) // 6006 SGT IOF (ORed with ADC) // 6007 CAF ION (ORed with ADC) // 7002 BSW NOP // 7014 Reserved RAR RAL // 7016 Reserved RTR RTL // 74X1 MQ Instructions Only available with EAE. // 7521 SWP MQL MQA // Octal codes 7014 and 7016 produced predictable but undocumented // results in the PDP-8/1 and PDP-8/L. In the PDP-8/E these codes are // specifically reserved for future expansion. // Options: `define CORE_4K 1 // `define CORE_32K 1 // `define START_ADDR 12'o7777 `ifndef START_ADDR `define START_ADDR 12'o0200 `endif // DE10 Led Output // 6776 Write the AC[9:0] to LEDR (10 DE10 Status Leds) `define DEV_CPU 6'o00 // CPU Interrupt Control `define DEV_TTY_RX 6'o03 // teletype Keyboard `define DEV_TTY_TX 6'o04 // teletype Printer `define DEV_GPS_RX 6'o43 // GPS UART Receiver `define DEV_GPS_TX 6'o44 // GPS UART Transmitter `define DEV_DE10 6'o47 // DE10 Interface // Major Opcodes `define OP_AND 3'b000 // AND memory with AC `define OP_TAD 3'b001 // Transfer and Add to AC `define OP_ISZ 3'b010 // INC and Skip on Zero `define OP_DCA 3'b011 // Deposit and Clear AC `define OP_JMS 3'b100 // JuMp to Subroutine `define OP_JMP 3'b101 // JuMP `define OP_IOT 3'b110 // Input/Output Transfer `define OP_OPR 3'b111 // micro coded OPeRations // CPU Cycle State - use one-shot logic `define STATE_IDLE 10'h001 `define STATE_FETCH 10'h002 `define STATE_EXECUTE 10'h004 `define STATE_INDIRECT 10'h008 `define STATE_WRITEBACK 10'h010 `define STATE_JMS 10'h020 `define STATE_EXECUTE2 10'h040 `define STATE_INTERRUPT 10'h080 `define STATE_AUTOINC 10'h100 `define STATE_HALT 10'h200 `define OP_NOP 12'o7000 // NOP - No Operation `define OP_JMS0 12'o4000 // JMS 0 - Interrupt // various baud rate factors for 50MHz clk // Baud Factor iFactor Error // 300 10416.667 10417 -0.003% // 9600 325.521 326 -0.147% // 19200 162.760 163 -0.147% // 115200 27.127 27 0.467% // 256000 12.207 12 1.696% // 1000000 3.125 3 4.000% `define BAUD_300 16'd10417 // 300 = 10417, `define BAUD_9600 16'd326 // 9600 = 325.52, -0.15% `define BAUD_19200 16'd163 // 19200 = 162.76, `define BAUD_115200 16'd27 // 115,200 = 27.13, `define BAUD_256000 16'd12 // 256,000 = 12.21 `define BAUD_1M 16'd3 // 1000000 = 3.125 `ifdef iverilog `define BAUD_FACTOR `BAUD_1M // very fast for simulation `endif `ifndef BAUD_FACTOR `define BAUD_FACTOR `BAUD_300 // Teletype = 300 baud `endif // `define OLD_WAY `ifdef OLD_WAY // CORE Memory - xK by 12 bits wide `ifdef EXTENDED_MEM `define CORE_32K_12BITS 1 `else `define CORE_4K_12BITS 1 `endif `else `define MEM_12BITS `endif `ifndef MEM_SIZE_K `define MEM_SIZE_K 8 // 8K // Extended Memory Interface `define EXTENDED_MEM `endif `define MEM_AWIDTH ($clog2(`MEM_SIZE_K*1024)) // add a second UART for GPS interface `define ADD_GPS
32.761733
92
0.677906
[ "vector" ]
fa3cd8c14ff380b024156b2f0455c2b0a84ccf97
3,031
h
C
src/objects/maybe-object-inl.h
mtk-watch/android_external_v8
29eb30806a59123b1f9faf9083a12d26fa418fad
[ "BSD-3-Clause" ]
null
null
null
src/objects/maybe-object-inl.h
mtk-watch/android_external_v8
29eb30806a59123b1f9faf9083a12d26fa418fad
[ "BSD-3-Clause" ]
null
null
null
src/objects/maybe-object-inl.h
mtk-watch/android_external_v8
29eb30806a59123b1f9faf9083a12d26fa418fad
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_OBJECTS_MAYBE_OBJECT_INL_H_ #define V8_OBJECTS_MAYBE_OBJECT_INL_H_ #include "src/objects/maybe-object.h" #include "src/objects-inl.h" namespace v8 { namespace internal { bool MaybeObject::ToSmi(Smi** value) { if (HAS_SMI_TAG(this)) { *value = Smi::cast(reinterpret_cast<Object*>(this)); return true; } return false; } Smi* MaybeObject::ToSmi() { DCHECK(HAS_SMI_TAG(this)); return Smi::cast(reinterpret_cast<Object*>(this)); } bool MaybeObject::IsStrongOrWeakHeapObject() const { if (IsSmi() || IsClearedWeakHeapObject()) { return false; } return true; } bool MaybeObject::ToStrongOrWeakHeapObject(HeapObject** result) { if (IsSmi() || IsClearedWeakHeapObject()) { return false; } *result = GetHeapObject(); return true; } bool MaybeObject::ToStrongOrWeakHeapObject( HeapObject** result, HeapObjectReferenceType* reference_type) { if (IsSmi() || IsClearedWeakHeapObject()) { return false; } *reference_type = HasWeakHeapObjectTag(this) ? HeapObjectReferenceType::WEAK : HeapObjectReferenceType::STRONG; *result = GetHeapObject(); return true; } bool MaybeObject::IsStrongHeapObject() const { return !HasWeakHeapObjectTag(this) && !IsSmi(); } bool MaybeObject::ToStrongHeapObject(HeapObject** result) { if (!HasWeakHeapObjectTag(this) && !IsSmi()) { *result = reinterpret_cast<HeapObject*>(this); return true; } return false; } HeapObject* MaybeObject::ToStrongHeapObject() { DCHECK(IsStrongHeapObject()); return reinterpret_cast<HeapObject*>(this); } bool MaybeObject::IsWeakHeapObject() const { return HasWeakHeapObjectTag(this) && !IsClearedWeakHeapObject(); } bool MaybeObject::IsWeakOrClearedHeapObject() const { return HasWeakHeapObjectTag(this); } bool MaybeObject::ToWeakHeapObject(HeapObject** result) { if (HasWeakHeapObjectTag(this) && !IsClearedWeakHeapObject()) { *result = GetHeapObject(); return true; } return false; } HeapObject* MaybeObject::ToWeakHeapObject() { DCHECK(IsWeakHeapObject()); return GetHeapObject(); } HeapObject* MaybeObject::GetHeapObject() { DCHECK(!IsSmi()); DCHECK(!IsClearedWeakHeapObject()); return RemoveWeakHeapObjectMask(reinterpret_cast<HeapObjectReference*>(this)); } Object* MaybeObject::GetHeapObjectOrSmi() { if (IsSmi()) { return reinterpret_cast<Object*>(this); } return GetHeapObject(); } bool MaybeObject::IsObject() const { return IsSmi() || IsStrongHeapObject(); } Object* MaybeObject::ToObject() { DCHECK(!HasWeakHeapObjectTag(this)); return reinterpret_cast<Object*>(this); } MaybeObject* MaybeObject::MakeWeak(MaybeObject* object) { DCHECK(object->IsStrongOrWeakHeapObject()); return AddWeakHeapObjectMask(object); } } // namespace internal } // namespace v8 #endif // V8_OBJECTS_MAYBE_OBJECT_INL_H_
24.844262
80
0.719565
[ "object" ]
fa3ef62383d7225375c1fd7c02023f69eeea7936
4,587
c
C
tests/roseTests/astOutliningTests/complexStruct.c
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
tests/roseTests/astOutliningTests/complexStruct.c
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
tests/roseTests/astOutliningTests/complexStruct.c
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
// A test case from a changed version of smg2000 kernel // for recursive copy dependent declarations and typedef used in an outlining target // to a new file. // Liao, 5/8/2009 enum MyEnumType { ALPHA, BETA, GAMMA }; typedef int MYINT; typedef MYINT hypre_MPI_Comm; // test chain of typedef here typedef int hypre_MPI_Datatype; typedef int hypre_Index[3]; // test a defining typedef with embedded struct definition typedef struct hypre_Box_struct { hypre_Index imin; hypre_Index imax; } hypre_Box; typedef struct hypre_BoxArray_struct //5 { hypre_Box *boxes; int size; int alloc_size; } hypre_BoxArray; typedef struct hypre_RankLink_struct { int rank; struct hypre_RankLink_struct *next; } hypre_RankLink; // test base type of typedef: pointer to a typedef, then a struct typedef hypre_RankLink *hypre_RankLinkArray[3][3][3]; typedef struct hypre_BoxNeighbors_struct { hypre_BoxArray *boxes; int *procs; int *ids; int first_local; int num_local; int num_periodic; hypre_RankLinkArray *rank_links; } hypre_BoxNeighbors; typedef struct hypre_StructGrid_struct { hypre_MPI_Comm comm; int dim; hypre_BoxArray *boxes; int *ids; hypre_BoxNeighbors *neighbors; int max_distance; hypre_Box *bounding_box; int local_size; int global_size; hypre_Index periodic; int ref_count; } hypre_StructGrid; typedef struct hypre_StructStencil_struct //10 { hypre_Index *shape; int size; int max_offset; int dim; int ref_count; } hypre_StructStencil; typedef struct hypre_CommTypeEntry_struct { hypre_Index imin; hypre_Index imax; int offset; int dim; int length_array[4]; int stride_array[4]; } hypre_CommTypeEntry; typedef struct hypre_CommType_struct { hypre_CommTypeEntry **comm_entries; int num_entries; } hypre_CommType; typedef struct hypre_CommPkg_struct { int num_values; hypre_MPI_Comm comm; int num_sends; int num_recvs; int *send_procs; int *recv_procs; hypre_CommType **send_types; hypre_CommType **recv_types; hypre_MPI_Datatype *send_mpi_types; hypre_MPI_Datatype *recv_mpi_types; hypre_CommType *copy_from_type; hypre_CommType *copy_to_type; } hypre_CommPkg; typedef struct hypre_StructMatrix_struct //14 { hypre_MPI_Comm comm; hypre_StructGrid *grid; hypre_StructStencil *user_stencil; hypre_StructStencil *stencil; int num_values; hypre_BoxArray *data_space; double *data; int data_alloced; int data_size; int **data_indices; int symmetric; int *symm_elements; int num_ghost[6]; int global_size; hypre_CommPkg *comm_pkg; int ref_count; } hypre_StructMatrix; enum special_function_modifier_enum { e_unknown = 0, e_default = 1, e_none = e_default, e_constructor = 2, e_destructor = 3, e_conversion = 4, e_operator = 5, e_last_modifier }; union item { int m; float p; char c; } code; void OUT__1__6119__(void **__out_argv) { hypre_StructMatrix *A = *((hypre_StructMatrix **)(__out_argv[20])); int ri = *((int *)(__out_argv[19])); double *rp = *((double **)(__out_argv[18])); int stencil_size = *((int *)(__out_argv[17])); int i = *((int *)(__out_argv[16])); int (*dxp_s)[15UL] = (int (*)[15UL])(__out_argv[15]); int hypre__sy1 = *((int *)(__out_argv[14])); int hypre__sz1 = *((int *)(__out_argv[13])); int hypre__sy2 = *((int *)(__out_argv[12])); int hypre__sz2 = *((int *)(__out_argv[11])); int hypre__sy3 = *((int *)(__out_argv[10])); int hypre__sz3 = *((int *)(__out_argv[9])); int hypre__mx = *((int *)(__out_argv[8])); int hypre__my = *((int *)(__out_argv[7])); int hypre__mz = *((int *)(__out_argv[6])); int si = *((int *)(__out_argv[5])); int ii = *((int *)(__out_argv[4])); int jj = *((int *)(__out_argv[3])); int kk = *((int *)(__out_argv[2])); const double *Ap_0 = *((const double **)(__out_argv[1])); const double *xp_0 = *((const double **)(__out_argv[0])); // real kernel which should be outlined for (si = 0; si < stencil_size; si++) for (kk = 0; kk < hypre__mz; kk++) for (jj = 0; jj < hypre__my; jj++) for (ii = 0; ii < hypre__mx; ii++) { rp[(ri + ii) + (jj * hypre__sy3) + (kk * hypre__sz3)] -= Ap_0[ii + (jj * hypre__sy1) + (kk * hypre__sz1) + A -> data_indices[i][si]] * xp_0[ii + (jj * hypre__sy2) + (kk * hypre__sz2) + ( *dxp_s)[si]]; // add more interesting stuff just for testing enum special_function_modifier_enum e1; if (ii== ALPHA) ; code.m =1; } }
21.434579
210
0.669937
[ "shape" ]
fa43395d06c4301c37dad92709fe97f561bfff43
1,615
h
C
Chess/Game.h
NanoBreeze/Tcp-Chess
2cf51a8b6991dbeced7714b18429640394b04641
[ "Apache-2.0" ]
1
2017-08-01T17:28:39.000Z
2017-08-01T17:28:39.000Z
Chess/Game.h
NanoBreeze/TCP-Chess
2cf51a8b6991dbeced7714b18429640394b04641
[ "Apache-2.0" ]
null
null
null
Chess/Game.h
NanoBreeze/TCP-Chess
2cf51a8b6991dbeced7714b18429640394b04641
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Square.h" #include "StateManager.h" #include <iostream> #include <assert.h> #include "WhitePlayer.h" #include "BlackPlayer.h" #include "Board.h" #include <vector> #include <algorithm> #include "Coordinate.h" #include "MovesDisplay.h" #include <SFML/Network.hpp> //will remove #include <SFML\Graphics.hpp> //contains 64 Squares to represent a chessboard class Game { public: //sets up the board, and players Game(); //removes all pointers ~Game(); //contains pieces and info related to the white player Player* whitePlayer = nullptr; //contains pieces and info related to the black player Player* blackPlayer = nullptr; //contains the Squares. This is where the visual action goes on and the 2D array of Squares reside Board board = Board::getInstance(); //contains info relevant to the state of the game. StateManager stateManager = StateManager::getInstance(); //manages selecting a Square or Piece, (thus moving, etc), works with stateManager getCoordinateFromCursor(), socket and bool indicate if //we're playing with remove player void delegateClick(const int& x, const int& y, sf::TcpSocket& socket, const bool); //this is used with the TCP socket, we have just received the coordinate of a from and to. Thus, find the piece that was at the from //and move it to the to coordinate void delegateReceivedMove(const char[], const int); private: //Returns the coordinate associated with the pixel that the cursor clicked. Coordinate getCoordinateFromCursor(const int&, const int&) const; };
26.916667
140
0.720124
[ "vector" ]
fa459e25dbb6f090b1eb9ee9caf19b8c71f69d51
5,890
c
C
amethyst/src/menuDebugRenderEffects.c
RenaKunisaki/StarFoxAdventures
02f7efad391e78fb1ba0139e6e4cb6d8c6d1cfbd
[ "MIT" ]
22
2019-11-29T21:20:59.000Z
2022-01-25T06:39:02.000Z
amethyst/src/menuDebugRenderEffects.c
RenaKunisaki/StarFoxAdventures
02f7efad391e78fb1ba0139e6e4cb6d8c6d1cfbd
[ "MIT" ]
7
2021-01-26T11:57:25.000Z
2022-02-07T11:00:06.000Z
amethyst/src/menuDebugRenderEffects.c
RenaKunisaki/StarFoxAdventures
02f7efad391e78fb1ba0139e6e4cb6d8c6d1cfbd
[ "MIT" ]
3
2021-01-03T23:47:37.000Z
2021-08-06T09:02:11.000Z
#include "main.h" void menuDebugRenderEffectsBlur_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; sprintf(str, self->fmt, T(self->name), bEnableBlurFilter ? T("On") : T("Off")); menuDrawText(str, x, y, selected); } void menuDebugRenderEffectsBlur_select(const MenuItem *self, int amount) { bEnableBlurFilter = !bEnableBlurFilter; audioPlaySound(NULL, MENU_ADJUST_SOUND); } void menuDebugRenderEffectsMotBlur_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; sprintf(str, self->fmt, T(self->name), (int)motionBlurIntensity); menuDrawText(str, x, y, selected); } void menuDebugRenderEffectsMotBlur_select(const MenuItem *self, int amount) { int val = motionBlurIntensity + amount; if(val < 0) val = 255; if(val > 255) val = 0; motionBlurIntensity = val; bEnableMotionBlur = (val > 0); audioPlaySound(NULL, MENU_ADJUST_SOUND); } void menuDebugRenderEffectsHeatFx_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; sprintf(str, self->fmt, T(self->name), heatEffectIntensity); menuDrawText(str, x, y, selected); } void menuDebugRenderEffectsHeatFx_select(const MenuItem *self, int amount) { int val = heatEffectIntensity + amount; if(val < 0) val = 255; if(val > 255) val = 0; heatEffectIntensity = val; audioPlaySound(NULL, MENU_ADJUST_SOUND); } void menuDebugRenderEffectsMono_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; sprintf(str, self->fmt, T(self->name), bEnableMonochromeFilter ? T("On") : T("Off")); menuDrawText(str, x, y, selected); } void menuDebugRenderEffectsMono_select(const MenuItem *self, int amount) { bEnableMonochromeFilter = !bEnableMonochromeFilter; audioPlaySound(NULL, MENU_ADJUST_SOUND); } void menuDebugRenderEffectsSpirit_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; sprintf(str, self->fmt, T(self->name), bEnableSpiritVision ? T("On") : T("Off")); menuDrawText(str, x, y, selected); } void menuDebugRenderEffectsSpirit_select(const MenuItem *self, int amount) { bEnableSpiritVision = !bEnableSpiritVision; audioPlaySound(NULL, MENU_ADJUST_SOUND); } void menuDebugRenderColFiltOn_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; sprintf(str, self->fmt, T(self->name), bEnableColorFilter ? T("On") : T("Off")); menuDrawText(str, x, y, selected); } void menuDebugRenderColFiltOn_select(const MenuItem *self, int amount) { bEnableColorFilter = !bEnableColorFilter; audioPlaySound(NULL, MENU_ADJUST_SOUND); } void menuDebugRenderColFiltR_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; sprintf(str, self->fmt, T(self->name), colorFilterColor.r); menuDrawText(str, x, y, selected); } void menuDebugRenderColFiltR_select(const MenuItem *self, int amount) { int val = colorFilterColor.r + amount; if(val < 0) val = 255; if(val > 255) val = 0; colorFilterColor.r = val; audioPlaySound(NULL, MENU_ADJUST_SOUND); } void menuDebugRenderColFiltG_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; sprintf(str, self->fmt, T(self->name), colorFilterColor.g); menuDrawText(str, x, y, selected); } void menuDebugRenderColFiltG_select(const MenuItem *self, int amount) { int val = colorFilterColor.g + amount; if(val < 0) val = 255; if(val > 255) val = 0; colorFilterColor.g = val; audioPlaySound(NULL, MENU_ADJUST_SOUND); } void menuDebugRenderColFiltB_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; sprintf(str, self->fmt, T(self->name), colorFilterColor.b); menuDrawText(str, x, y, selected); } void menuDebugRenderColFiltB_select(const MenuItem *self, int amount) { int val = colorFilterColor.b + amount; if(val < 0) val = 255; if(val > 255) val = 0; colorFilterColor.b = val; audioPlaySound(NULL, MENU_ADJUST_SOUND); } void menuDebugRenderColScale_draw(const MenuItem *self, int x, int y, bool selected) { char str[256]; if(overrideColorScale >= 0){ sprintf(str, "%s:\eX0280\eF%3d%%", T("Color Scale"), (int)((overrideColorScale / 255.0) * 100.0)); } else sprintf(str, "%s:\eX0280%s", T("Color Scale"), T("Normal")); menuDrawText(str, x, y, selected); } void menuDebugRenderColScale_select(const MenuItem *self, int amount) { int val = overrideColorScale + amount; if(val < -1) val = 255; if(val > 255) val = -1; overrideColorScale = val; audioPlaySound(NULL, MENU_ADJUST_SOUND); } #define _FMT "%s:\eX0280" Menu menuDebugRenderEffects = { "Effects", 0, genericMenu_run, genericMenu_draw, debugRenderSubMenu_close, "Blur Filter", _FMT "%s", menuDebugRenderEffectsBlur_draw, menuDebugRenderEffectsBlur_select, "Motion Blur", _FMT "\eF%3d", menuDebugRenderEffectsMotBlur_draw, menuDebugRenderEffectsMotBlur_select, "Heat Effect", _FMT "\eF%3d", menuDebugRenderEffectsHeatFx_draw, menuDebugRenderEffectsHeatFx_select, "Monochrome", _FMT "%s", menuDebugRenderEffectsMono_draw, menuDebugRenderEffectsMono_select, "Spirit Vision", _FMT "%s", menuDebugRenderEffectsSpirit_draw, menuDebugRenderEffectsSpirit_select, "Color Filter", _FMT "%s", menuDebugRenderColFiltOn_draw, menuDebugRenderColFiltOn_select, "Filter R", _FMT "\eF%3d", menuDebugRenderColFiltR_draw, menuDebugRenderColFiltR_select, "Filter G", _FMT "\eF%3d", menuDebugRenderColFiltG_draw, menuDebugRenderColFiltG_select, "Filter B", _FMT "\eF%3d", menuDebugRenderColFiltB_draw, menuDebugRenderColFiltB_select, "", _FMT "%s", menuDebugRenderColScale_draw, menuDebugRenderColScale_select, NULL, }; #undef _FMT
39.006623
110
0.699151
[ "3d" ]
fa486c76d24c2a4a37e27a152333bf57057df1c8
549
h
C
src/xrGame/ai/monsters/states/monster_state_eat_eat.h
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
src/xrGame/ai/monsters/states/monster_state_eat_eat.h
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
src/xrGame/ai/monsters/states/monster_state_eat_eat.h
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
#pragma once #include "ai/monsters/state.h" template <typename _Object> class CStateMonsterEating : public CState<_Object> { protected: typedef CState<_Object> inherited; CEntityAlive* corpse; u32 time_last_eat; public: CStateMonsterEating(_Object* obj); virtual ~CStateMonsterEating(); virtual void initialize(); virtual void execute(); virtual void remove_links(IGameObject* object); virtual bool check_start_conditions(); virtual bool check_completion(); }; #include "monster_state_eat_eat_inline.h"
21.115385
51
0.741348
[ "object" ]
fa4e3d9f6ebefecab7d0efef678b9d24a5df73bb
14,051
c
C
.vim/sourceCode/glibc-2.16.0/sysdeps/mach/hurd/i386/init-first.c
lakehui/Vim_config
6cab80dc1209b34bf6379f42b1a92790bd0c146b
[ "MIT" ]
null
null
null
.vim/sourceCode/glibc-2.16.0/sysdeps/mach/hurd/i386/init-first.c
lakehui/Vim_config
6cab80dc1209b34bf6379f42b1a92790bd0c146b
[ "MIT" ]
null
null
null
.vim/sourceCode/glibc-2.16.0/sysdeps/mach/hurd/i386/init-first.c
lakehui/Vim_config
6cab80dc1209b34bf6379f42b1a92790bd0c146b
[ "MIT" ]
null
null
null
/* Initialization code run first thing by the ELF startup code. For i386/Hurd. Copyright (C) 1995-2012 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <ctype.h> #include <hurd.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sysdep.h> #include <set-hooks.h> #include "hurdstartup.h" #include "hurdmalloc.h" /* XXX */ #include "../locale/localeinfo.h" #include <ldsodefs.h> #include <fpu_control.h> extern void __mach_init (void); extern void __init_misc (int, char **, char **); #ifdef USE_NONOPTION_FLAGS extern void __getopt_clean_environment (char **); #endif #ifndef SHARED extern void _dl_non_dynamic_init (void) internal_function; #endif extern void __libc_global_ctors (void); unsigned int __hurd_threadvar_max; unsigned long int __hurd_threadvar_stack_offset; unsigned long int __hurd_threadvar_stack_mask; #ifndef SHARED int __libc_enable_secure; #endif int __libc_multiple_libcs attribute_hidden = 1; extern int __libc_argc attribute_hidden; extern char **__libc_argv attribute_hidden; extern char **_dl_argv; extern void *(*_cthread_init_routine) (void) __attribute__ ((weak)); void (*_cthread_exit_routine) (int status) __attribute__ ((__noreturn__)); /* Things that want to be run before _hurd_init or much anything else. Importantly, these are called before anything tries to use malloc. */ DEFINE_HOOK (_hurd_preinit_hook, (void)); /* We call this once the Hurd magic is all set up and we are ready to be a Posixoid program. This does the same things the generic version does. */ static void posixland_init (int argc, char **argv, char **envp) { __libc_multiple_libcs = &_dl_starting_up && !_dl_starting_up; /* Make sure we don't initialize twice. */ if (!__libc_multiple_libcs) { /* Set the FPU control word to the proper default value. */ __setfpucw (__fpu_control); } /* Save the command-line arguments. */ __libc_argc = argc; __libc_argv = argv; __environ = envp; #ifndef SHARED _dl_non_dynamic_init (); #endif __init_misc (argc, argv, envp); #ifdef USE_NONOPTION_FLAGS /* This is a hack to make the special getopt in GNU libc working. */ __getopt_clean_environment (envp); #endif /* Initialize ctype data. */ __ctype_init (); #if defined SHARED && !defined NO_CTORS_DTORS_SECTIONS __libc_global_ctors (); #endif } static void init1 (int argc, char *arg0, ...) { char **argv = &arg0; char **envp = &argv[argc + 1]; struct hurd_startup_data *d; #ifndef SHARED extern ElfW(Phdr) *_dl_phdr; extern size_t _dl_phnum; #endif while (*envp) ++envp; d = (void *) ++envp; /* If we are the bootstrap task started by the kernel, then after the environment pointers there is no Hurd data block; the argument strings start there. */ if ((void *) d == argv[0]) { #ifndef SHARED /* We may need to see our own phdrs, e.g. for TLS setup. Try the usual kludge to find the headers without help from the exec server. */ extern const void _start; const ElfW(Ehdr) *const ehdr = &_start; _dl_phdr = (ElfW(Phdr) *) ((const void *) ehdr + ehdr->e_phoff); _dl_phnum = ehdr->e_phnum; assert (ehdr->e_phentsize == sizeof (ElfW(Phdr))); #endif return; } #ifndef SHARED __libc_enable_secure = d->flags & EXEC_SECURE; _dl_phdr = (ElfW(Phdr) *) d->phdr; _dl_phnum = d->phdrsz / sizeof (ElfW(Phdr)); assert (d->phdrsz % sizeof (ElfW(Phdr)) == 0); #endif _hurd_init_dtable = d->dtable; _hurd_init_dtablesize = d->dtablesize; { /* Check if the stack we are now on is different from the one described by _hurd_stack_{base,size}. */ char dummy; const vm_address_t newsp = (vm_address_t) &dummy; if (d->stack_size != 0 && (newsp < d->stack_base || newsp - d->stack_base > d->stack_size)) /* The new stack pointer does not intersect with the stack the exec server set up for us, so free that stack. */ __vm_deallocate (__mach_task_self (), d->stack_base, d->stack_size); } if (d->portarray || d->intarray) /* Initialize library data structures, start signal processing, etc. */ _hurd_init (d->flags, argv, d->portarray, d->portarraysize, d->intarray, d->intarraysize); } static inline void init (int *data) { int argc = *data; char **argv = (void *) (data + 1); char **envp = &argv[argc + 1]; struct hurd_startup_data *d; unsigned long int threadvars[_HURD_THREADVAR_MAX]; /* Provide temporary storage for thread-specific variables on the startup stack so the cthreads initialization code can use them for malloc et al, or so we can use malloc below for the real threadvars array. */ memset (threadvars, 0, sizeof threadvars); threadvars[_HURD_THREADVAR_LOCALE] = (unsigned long int) &_nl_global_locale; __hurd_threadvar_stack_offset = (unsigned long int) threadvars; /* Since the cthreads initialization code uses malloc, and the malloc initialization code needs to get at the environment, make sure we can find it. We'll need to do this again later on since switching stacks changes the location where the environment is stored. */ __environ = envp; while (*envp) ++envp; d = (void *) ++envp; /* The user might have defined a value for this, to get more variables. Otherwise it will be zero on startup. We must make sure it is set properly before before cthreads initialization, so cthreads can know how much space to leave for thread variables. */ if (__hurd_threadvar_max < _HURD_THREADVAR_MAX) __hurd_threadvar_max = _HURD_THREADVAR_MAX; /* After possibly switching stacks, call `init1' (above) with the user code as the return address, and the argument data immediately above that on the stack. */ if (&_cthread_init_routine && _cthread_init_routine) { /* Initialize cthreads, which will allocate us a new stack to run on. */ int *newsp = (*_cthread_init_routine) (); struct hurd_startup_data *od; void switch_stacks (void); __libc_stack_end = newsp; /* Copy per-thread variables from that temporary area onto the new cthread stack. */ memcpy (__hurd_threadvar_location_from_sp (0, newsp), threadvars, sizeof threadvars); /* Copy the argdata from the old stack to the new one. */ newsp = memcpy (newsp - ((char *) &d[1] - (char *) data), data, (char *) d - (char *) data); #ifdef SHARED /* And readjust the dynamic linker's idea of where the argument vector lives. */ assert (_dl_argv == argv); _dl_argv = (void *) (newsp + 1); #endif /* Set up the Hurd startup data block immediately following the argument and environment pointers on the new stack. */ od = ((void *) newsp + ((char *) d - (char *) data)); if ((void *) argv[0] == d) /* We were started up by the kernel with arguments on the stack. There is no Hurd startup data, so zero the block. */ memset (od, 0, sizeof *od); else /* Copy the Hurd startup data block to the new stack. */ *od = *d; /* Push the user code address on the top of the new stack. It will be the return address for `init1'; we will jump there with NEWSP as the stack pointer. */ /* The following expression would typically be written as ``__builtin_return_address (0)''. But, for example, GCC 4.4.6 doesn't recognize that this read operation may alias the following write operation, and thus is free to reorder the two, clobbering the original return address. */ *--newsp = *((int *) __builtin_frame_address (0) + 1); /* GCC 4.4.6 also wants us to force loading *NEWSP already here. */ asm volatile ("# %0" : : "X" (*newsp)); *((void **) __builtin_frame_address (0) + 1) = &switch_stacks; /* Force NEWSP into %eax and &init1 into %ecx, which are not restored by function return. */ asm volatile ("# a %0 c %1" : : "a" (newsp), "c" (&init1)); } else { /* We are not using cthreads, so we will have just a single allocated area for the per-thread variables of the main user thread. */ unsigned long int *array; unsigned int i; int usercode; void call_init1 (void); array = malloc (__hurd_threadvar_max * sizeof (unsigned long int)); if (array == NULL) __libc_fatal ("Can't allocate single-threaded thread variables."); /* Copy per-thread variables from the temporary array into the newly malloc'd space. */ memcpy (array, threadvars, sizeof threadvars); __hurd_threadvar_stack_offset = (unsigned long int) array; for (i = _HURD_THREADVAR_MAX; i < __hurd_threadvar_max; ++i) array[i] = 0; /* The argument data is just above the stack frame we will unwind by returning. Mutate our own return address to run the code below. */ /* The following expression would typically be written as ``__builtin_return_address (0)''. But, for example, GCC 4.4.6 doesn't recognize that this read operation may alias the following write operation, and thus is free to reorder the two, clobbering the original return address. */ usercode = *((int *) __builtin_frame_address (0) + 1); /* GCC 4.4.6 also wants us to force loading USERCODE already here. */ asm volatile ("# %0" : : "X" (usercode)); *((void **) __builtin_frame_address (0) + 1) = &call_init1; /* Force USERCODE into %eax and &init1 into %ecx, which are not restored by function return. */ asm volatile ("# a %0 c %1" : : "a" (usercode), "c" (&init1)); } } /* These bits of inline assembler used to be located inside `init'. However they were optimized away by gcc 2.95. */ /* The return address of `init' above, was redirected to here, so at this point our stack is unwound and callers' registers restored. Only %ecx and %eax are call-clobbered and thus still have the values we set just above. Fetch from there the new stack pointer we will run on, and jmp to the run-time address of `init1'; when it returns, it will run the user code with the argument data at the top of the stack. */ asm ("switch_stacks:\n" " movl %eax, %esp\n" " jmp *%ecx"); /* As in the stack-switching case, at this point our stack is unwound and callers' registers restored, and only %ecx and %eax communicate values from the lines above. In this case we have stashed in %eax the user code return address. Push it on the top of the stack so it acts as init1's return address, and then jump there. */ asm ("call_init1:\n" " push %eax\n" " jmp *%ecx\n"); /* Do the first essential initializations that must precede all else. */ static inline void first_init (void) { /* Initialize data structures so we can do RPCs. */ __mach_init (); RUN_HOOK (_hurd_preinit_hook, ()); } #ifdef SHARED /* This function is called specially by the dynamic linker to do early initialization of the shared C library before normal initializers expecting a Posixoid environment can run. It gets called with the stack set up just as the user will see it, so it can switch stacks. */ void _dl_init_first (int argc, ...) { first_init (); /* If we use ``__builtin_frame_address (0) + 2'' here, GCC gets confused. */ init (&argc); } #endif #ifdef SHARED /* The regular posixland initialization is what goes into libc's normal initializer. */ /* NOTE! The linker notices the magical name `_init' and sets the DT_INIT pointer in the dynamic section based solely on that. It is convention for this function to be in the `.init' section, but the symbol name is the only thing that really matters!! */ strong_alias (posixland_init, _init); void __libc_init_first (int argc, char **argv, char **envp) { /* Everything was done in the shared library initializer, _init. */ } #else strong_alias (posixland_init, __libc_init_first); /* XXX This is all a crock and I am not happy with it. This poorly-named function is called by static-start.S, which should not exist at all. */ void _hurd_stack_setup (void) { intptr_t caller = (intptr_t) __builtin_return_address (0); void doinit (intptr_t *data) { /* This function gets called with the argument data at TOS. */ void doinit1 (int argc, ...) { /* If we use ``__builtin_frame_address (0) + 2'' here, GCC gets confused. */ init ((int *) &argc); } /* Push the user return address after the argument data, and then jump to `doinit1' (above), so it is as if __libc_init_first's caller had called `doinit1' with the argument data already on the stack. */ *--data = caller; asm volatile ("movl %0, %%esp\n" /* Switch to new outermost stack. */ "movl $0, %%ebp\n" /* Clear outermost frame pointer. */ "jmp *%1" : : "r" (data), "r" (&doinit1) : "sp"); /* NOTREACHED */ } first_init (); _hurd_startup ((void **) __builtin_frame_address (0) + 2, &doinit); } #endif /* This function is defined here so that if this file ever gets into ld.so we will get a link error. Having this file silently included in ld.so causes disaster, because the _init definition above will cause ld.so to gain an init function, which is not a cool thing. */ void _dl_start (void) { abort (); }
33.857831
79
0.683724
[ "vector" ]
fa4f6ef7f38429401e0ec8e2a16d4d170deb41c8
6,827
h
C
MK4duo/src/lcd/ultralcd/ultralcd.h
DapDeveloper/MK4duo
385fdcd3cda94e73396dd12f23ff570c86d2eab5
[ "RSA-MD" ]
null
null
null
MK4duo/src/lcd/ultralcd/ultralcd.h
DapDeveloper/MK4duo
385fdcd3cda94e73396dd12f23ff570c86d2eab5
[ "RSA-MD" ]
null
null
null
MK4duo/src/lcd/ultralcd/ultralcd.h
DapDeveloper/MK4duo
385fdcd3cda94e73396dd12f23ff570c86d2eab5
[ "RSA-MD" ]
null
null
null
/** * MK4duo Firmware for 3D Printer, Laser and CNC * * Based on Marlin, Sprinter and grbl * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * Copyright (C) 2019 Alberto Cotronei @MagoKimbra * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once #if HAS_SPI_LCD #if HAS_ADC_BUTTONS uint8_t get_ADC_keyValue(); #endif #if HAS_GRAPHICAL_LCD #define SETCURSOR(col, row) lcd_moveto(col * (MENU_FONT_WIDTH), (row + 1) * (MENU_FONT_HEIGHT)) #define SETCURSOR_RJ(len, row) lcd_moveto(LCD_PIXEL_WIDTH - len * (MENU_FONT_WIDTH), (row + 1) * (MENU_FONT_HEIGHT)) #define LCDPRINT(p) u8g.print(p) #define LCDWRITE(c) u8g.print(c) #else #define SETCURSOR(col, row) lcd_moveto(col, row) #define SETCURSOR_RJ(len, row) lcd_moveto(LCD_WIDTH - len, row) #define LCDPRINT(p) lcd_put_u8str(p) #define LCDWRITE(c) lcd_put_wchar(c) #endif #define LCD_UPDATE_INTERVAL 100 #if HAS_LCD_MENU // Manual Movement constexpr float manual_feedrate_mm_m[XYZE] = MANUAL_FEEDRATE; extern float move_menu_scale; #if ENABLED(ADVANCED_PAUSE_FEATURE) void lcd_pause_show_message(const PauseMessageEnum message, const PauseModeEnum mode=PAUSE_MODE_SAME, const uint8_t hotend=TARGET_HOTEND); #endif #if ENABLED(AUTO_BED_LEVELING_UBL) void lcd_mesh_edit_setup(const float &initial); float lcd_mesh_edit(); #endif #if ENABLED(PROBE_MANUALLY) || MECH(DELTA) void _man_probe_pt(const float &rx, const float &ry); #endif #if ENABLED(PROBE_MANUALLY) float lcd_probe_pt(const float &rx, const float &ry); #endif #endif // HAS_LCD_MENU #endif // HAS_SPI_LCD // REPRAPWORLD_KEYPAD (and ADC_KEYPAD) #if ENABLED(REPRAPWORLD_KEYPAD) #define BTN_OFFSET 0 // Bit offset into buttons for shift register values #define BLEN_KEYPAD_F3 0 #define BLEN_KEYPAD_F2 1 #define BLEN_KEYPAD_F1 2 #define BLEN_KEYPAD_DOWN 3 #define BLEN_KEYPAD_RIGHT 4 #define BLEN_KEYPAD_MIDDLE 5 #define BLEN_KEYPAD_UP 6 #define BLEN_KEYPAD_LEFT 7 #define EN_KEYPAD_F1 _BV(BTN_OFFSET + BLEN_KEYPAD_F1) #define EN_KEYPAD_F2 _BV(BTN_OFFSET + BLEN_KEYPAD_F2) #define EN_KEYPAD_F3 _BV(BTN_OFFSET + BLEN_KEYPAD_F3) #define EN_KEYPAD_DOWN _BV(BTN_OFFSET + BLEN_KEYPAD_DOWN) #define EN_KEYPAD_RIGHT _BV(BTN_OFFSET + BLEN_KEYPAD_RIGHT) #define EN_KEYPAD_MIDDLE _BV(BTN_OFFSET + BLEN_KEYPAD_MIDDLE) #define EN_KEYPAD_UP _BV(BTN_OFFSET + BLEN_KEYPAD_UP) #define EN_KEYPAD_LEFT _BV(BTN_OFFSET + BLEN_KEYPAD_LEFT) #define RRK(B) (keypad_buttons & (B)) #ifdef EN_C #define BUTTON_CLICK() ((buttons & EN_C) || RRK(EN_KEYPAD_MIDDLE)) #else #define BUTTON_CLICK() RRK(EN_KEYPAD_MIDDLE) #endif #endif #if HAS_DIGITAL_BUTTONS // Wheel spin pins where BA is 00, 10, 11, 01 (1 bit always changes) #define BLEN_A 0 #define BLEN_B 1 #define EN_A _BV(BLEN_A) #define EN_B _BV(BLEN_B) #define BUTTON_PRESSED(BN) !READ(BTN_## BN) #if BUTTON_EXISTS(ENC) #define BLEN_C 2 #define EN_C _BV(BLEN_C) #endif #if ENABLED(LCD_I2C_VIKI) #define B_I2C_BTN_OFFSET 3 // (the first three bit positions reserved for EN_A, EN_B, EN_C) // button and encoder bit positions within 'buttons' #define B_LE (BUTTON_LEFT << B_I2C_BTN_OFFSET) // The remaining normalized buttons are all read via I2C #define B_UP (BUTTON_UP << B_I2C_BTN_OFFSET) #define B_MI (BUTTON_SELECT << B_I2C_BTN_OFFSET) #define B_DW (BUTTON_DOWN << B_I2C_BTN_OFFSET) #define B_RI (BUTTON_RIGHT << B_I2C_BTN_OFFSET) #if BUTTON_EXISTS(ENC) // The pause/stop/restart button is connected to BTN_ENC when used #define B_ST (EN_C) // Map the pause/stop/resume button into its normalized functional name #if ENABLED(INVERT_CLICK_BUTTON) #define BUTTON_CLICK() !(buttons & (B_MI|B_RI|B_ST)) // pause/stop button also acts as click until we implement proper pause/stop. #else #define BUTTON_CLICK() (buttons & (B_MI|B_RI|B_ST)) // pause/stop button also acts as click until we implement proper pause/stop. #endif #else #if ENABLED(INVERT_CLICK_BUTTON) #define BUTTON_CLICK() !(buttons & (B_MI|B_RI)) #else #define BUTTON_CLICK() (buttons & (B_MI|B_RI)) #endif #endif // I2C buttons take too long to read inside an interrupt context and so we read them during lcd_update #elif ENABLED(LCD_I2C_PANELOLU2) #if !BUTTON_EXISTS(ENC) // Use I2C if not directly connected to a pin #define B_I2C_BTN_OFFSET 3 // (the first three bit positions reserved for EN_A, EN_B, EN_C) #define B_MI (PANELOLU2_ENCODER_C << B_I2C_BTN_OFFSET) // requires LiquidTWI2 library v1.2.3 or later #if ENABLED(INVERT_CLICK_BUTTON) #define BUTTON_CLICK() !(buttons & B_MI) #else #define BUTTON_CLICK() (buttons & B_MI) #endif #endif #endif #else #define BUTTON_EXISTS(BN) false // Shift register bits correspond to buttons: #define BL_LE 7 // Left #define BL_UP 6 // Up #define BL_MI 5 // Middle #define BL_DW 4 // Down #define BL_RI 3 // Right #define BL_ST 2 // Red Button #define B_LE (_BV(BL_LE)) #define B_UP (_BV(BL_UP)) #define B_MI (_BV(BL_MI)) #define B_DW (_BV(BL_DW)) #define B_RI (_BV(BL_RI)) #define B_ST (_BV(BL_ST)) #ifndef BUTTON_CLICK #define BUTTON_CLICK() (buttons & (B_MI|B_ST)) #endif #endif #if BUTTON_EXISTS(BACK) #define BLEN_D 3 #define EN_D _BV(BLEN_D) #if ENABLED(INVERT_BACK_BUTTON) #define LCD_BACK_CLICKED() !(buttons & EN_D) #else #define LCD_BACK_CLICKED() (buttons & EN_D) #endif #else #define LCD_BACK_CLICKED() false #endif #ifndef BUTTON_CLICK #ifdef EN_C #if ENABLED(INVERT_CLICK_BUTTON) #define BUTTON_CLICK() !(buttons & EN_C) #else #define BUTTON_CLICK() (buttons & EN_C) #endif #else #define BUTTON_CLICK() false #endif #endif
31.901869
138
0.67775
[ "3d" ]
fa50007e2782fc2bf75815701dc4dad71385e3ff
12,279
c
C
src/shapes/handle.c
Mu-L/brlcad
4fdb63530d60ad4a7980241306b65f640aad0974
[ "BSD-4-Clause", "BSD-3-Clause" ]
83
2021-03-10T05:54:52.000Z
2022-03-31T16:33:46.000Z
src/shapes/handle.c
Mu-L/brlcad
4fdb63530d60ad4a7980241306b65f640aad0974
[ "BSD-4-Clause", "BSD-3-Clause" ]
13
2021-06-24T17:07:48.000Z
2022-03-31T15:31:33.000Z
src/shapes/handle.c
Mu-L/brlcad
4fdb63530d60ad4a7980241306b65f640aad0974
[ "BSD-4-Clause", "BSD-3-Clause" ]
54
2021-03-10T07:57:06.000Z
2022-03-28T23:20:37.000Z
/* H A N D L E . C * BRL-CAD * * Copyright (c) 2004-2021 United States Government as represented by * the U.S. Army Research Laboratory. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. */ /** @file shapes/handle.c * * Program to make a handle using libwdb. The objects will be in * millimeters. This handle will be constructed using three * cylinders, two tori, and two arb8s. The base of the handle will be * centered at (0, 0, 0) and the height of the handle will extend in * the positive z-direction. * * Introduced in BRL-CAD release 4.4. */ #include "common.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "rt/db4.h" #include "vmath.h" #include "bu/app.h" #include "raytrace.h" #include "wdb.h" void printusage() { printf("Usage: handle <-- (if no arguments, go into interactive mode)\n"); printf("or\n"); printf("Usage: handle -f name.g -n number_of_handles -l handle_length -H handle_height\n"); printf(" -r1 torus_radius -r2 cylinder_radius\n"); printf(" (units mm)\n"); printf("\nThis program constructs a handle with the base centered\n"); printf("at (0, 0, 0) and the height extending in the positive z-\n"); printf("direction. The handle is to be composed of 3 cylinders, \n"); printf("2 tori, and 2 arb8s.\n\n"); /* List of options. */ /* -fname - name = name of .g file. */ /* -n# - # = number of handles. */ /* -l# - # = length of handle in mm. */ /* -H# - # = height of handle in mm. */ /* -r1# - # = r1 radius of torus. */ /* -r2# - # = r2 radius of cylinder. */ } int main(int argc, char **argv) { /* START # 1 */ struct rt_wdb *fpw; /* File to be written to. */ #define NAME_LEN 256 char filemged[NAME_LEN+1] = {0}; /* Mged file create. */ double hgt = 0.0; /* Height of handle. */ double len = 0.0; /* Length of handle. */ double r1 = 0.0; /* Radius of tori & radius of cylinders. */ double r2 = 0.0; point_t pts[8]; /* Eight points of arb8. */ point_t bs; /* Base of rcc. */ vect_t ht; /* Height of rcc. */ fastf_t rad; /* Radius of rcc. */ point_t cent; /* Center of torus. */ vect_t norm; /* Normal of torus. */ double rad1, rad2; /* r1 and r2 of torus. */ char *temp; /* Temporary character string. */ char temp1[NAME_LEN]; /* Temporary character string. */ char solnam[8]; /* Solid name. */ char regnam[8]; /* Region name. */ char grpnam[5]; /* Group name. */ int numhan = 0; /* Number of handles to be created. */ struct wmember comb; /* Used to make regions. */ struct wmember comb1; /* Used to make groups. */ int i, j, k; /* Loop counters. */ int ret; bu_setprogname(argv[0]); /* Set up solid, region, and group names. */ solnam[0] = 's'; solnam[1] = '.'; solnam[2] = 'h'; solnam[3] = 'a'; solnam[4] = 'n'; solnam[5] = ' '; solnam[6] = '#'; solnam[7] = '\0'; regnam[0] = 'r'; regnam[1] = '.'; regnam[2] = 'h'; regnam[3] = 'a'; regnam[4] = 'n'; regnam[5] = ' '; regnam[6] = '#'; regnam[7] = '\0'; grpnam[0] = 'h'; grpnam[1] = 'a'; grpnam[2] = 'n'; grpnam[3] = ' '; grpnam[4] = '\0'; /* If there are no arguments ask questions. */ if (argc == 1) { /* START # 3 */ /* Explain makings of handle. */ printusage(); (void)fflush(stdout); /* Find name of mged file to create. */ printf("\nEnter the name of the mged file to be created "); printf("(%d char max).\n\t", NAME_LEN); (void)fflush(stdout); ret = scanf(CPP_SCAN(NAME_LEN), filemged); if (ret == 0) perror("scanf"); if (BU_STR_EQUAL(filemged, "")) bu_strlcpy(filemged, "handle.g", sizeof(filemged)); /* Find number of handles to create. */ printf("Enter number of handles to create (%d max).\n\t", NAME_LEN); (void)fflush(stdout); ret = scanf("%d", &numhan); if (ret == 0) { perror("scanf"); numhan = 1; } /* Find dimensions of handle. */ printf("Enter the length and height of handle in mm.\n\t"); (void)fflush(stdout); ret = scanf("%lf %lf", &len, &hgt); if (ret == 0) { perror("scanf"); len = 100.0; hgt = 10.0; } else { if (len < SMALL_FASTF) len = SMALL_FASTF; if (hgt < SMALL_FASTF) hgt = SMALL_FASTF; } printf("Enter the radius of the tori in mm.\n\t"); (void)fflush(stdout); ret = scanf("%lf", &r1); if (ret == 0) { perror("scanf"); r1 = 5.0; } else { if (r1 < SMALL_FASTF) r1 = SMALL_FASTF; } printf("Enter the radius of the cylinders in mm.\n\t"); (void)fflush(stdout); ret = scanf("%lf", &r2); if (ret == 0) { perror("scanf"); r2 = 5.0; } else { if (r2 < SMALL_FASTF) r2 = SMALL_FASTF; } } /* END # 3 */ /* if there are arguments get the answers from the arguments. */ else { /* START # 4 */ for (i=1; i<argc; i++) { /* START # 5 */ /* Put argument into temporary character string. */ temp = argv[i]; if (temp[1] == 'h' || temp[1] == '?') { printusage(); bu_exit(1, NULL); } /* -f - mged file name. */ if (temp[1] == 'f') { /* START # 6 */ j = 2; k = 0; while ((temp[j] != '\0') && (k < NAME_LEN - 1)) { /* START # 7 */ filemged[k] = temp[j]; j++; k++; } /* END # 7 */ filemged[k] = '\0'; } /* END # 6 */ /* -n - # of handles to be created. */ else if (temp[1] == 'n') { /* START # 8 */ /* Set up temporary character string. */ j = 2; k = 0; while ((temp[j] != '\0') && (k < NAME_LEN - 1)) { /* START # 9 */ temp1[k] = temp[j]; j++; k++; } /* END # 9 */ temp1[k] = '\0'; sscanf(temp1, "%d", &numhan); } /* END # 8 */ /* -l or -h - length and height of handle in mm. */ else if ((temp[1] == 'l') || (temp[1] == 'H')) { /* START # 10 */ /* Set up temporary character string. */ j = 2; k = 0; while ((temp[j] != '\0') && (k < NAME_LEN - 1)) { /* START # 11 */ temp1[k] = temp[j]; j++; k++; } /* END # 11 */ temp1[k] = '\0'; if (temp[1] == 'l') sscanf(temp1, "%lf", &len); else if (temp[1] == 'H') sscanf(temp1, "%lf", &hgt); } /* END # 10 */ /* -r1 or -r2 - radii for torus. */ else if (temp[1] == 'r') { /* START # 12 */ /* Set up temporary character string. */ j = 3; k = 0; while ((temp[j] != '\0') && (k < NAME_LEN - 1)) { /* START # 13 */ temp1[k] = temp[j]; j++; k++; } /* END # 13 */ temp1[k] = '\0'; if (temp[2] == '1') sscanf(temp1, "%lf", &r1); else if (temp[2] == '2') sscanf(temp1, "%lf", &r2); } /* END # 12 */ } /* END # 5 */ } /* END # 4 */ if (numhan < 1) numhan = 1; else if (numhan > NAME_LEN) numhan = NAME_LEN; /* Print out dimensions of the handle. */ printf("\nmged file name: %s\n", filemged); printf("length: %f mm\n", len); printf("height: %f mm\n", hgt); printf("radius of tori: %f mm\n", r1); printf("radius of cylinders: %f mm\n", r2); printf("number of handles: %d\n\n", numhan); (void)fflush(stdout); /* Open mged file for writing to. */ fpw = wdb_fopen(filemged); if (!fpw) bu_exit(1, "file-open failed"); /* Write ident record. */ mk_id(fpw, "handles"); for (i=0; i<numhan; i++) { /* START # 2 */ /* Create solids for handle. */ /* Create top cylinder. */ bs[0] = (fastf_t)0.0; bs[1] = (fastf_t) (len / 2.0 - r1 - r2); bs[2] = (fastf_t) (hgt - r2); ht[0] = (fastf_t)0.0; ht[1] = (fastf_t) (r1 + r1 + r2 + r2 - len); ht[2] = (fastf_t)0.0; rad = (fastf_t)r2; solnam[5] = 97 + i; solnam[6] = '1'; mk_rcc(fpw, solnam, bs, ht, rad); /* Create right cylinder. */ bs[0] = (fastf_t)0.0; bs[1] = (fastf_t) (len / 2.0 - r2); bs[2] = (fastf_t)0.0; ht[0] = (fastf_t)0.0; ht[1] = (fastf_t)0.0; ht[2] = (fastf_t) (hgt - r1 - r2); rad = (fastf_t)r2; solnam[6] = '2'; mk_rcc(fpw, solnam, bs, ht, rad); /* Create left cylinder. */ bs[1] = (-bs[1]); solnam[6] = '3'; mk_rcc(fpw, solnam, bs, ht, rad); /* Create right torus. */ cent[0] = (fastf_t)0.0; cent[1] = (fastf_t) (len / 2.0 -r1 - r2); cent[2] = (fastf_t) (hgt - r1 -r2); norm[0] = (fastf_t)1.0; norm[1] = (fastf_t)0.0; norm[2] = (fastf_t)0.0; rad1 = r1; rad2 = r2; solnam[6] = '4'; mk_tor(fpw, solnam, cent, norm, rad1, rad2); /* Create left torus. */ cent[1] = (-cent[1]); solnam[6] = '5'; mk_tor(fpw, solnam, cent, norm, rad1, rad2); /* Create right arb8. */ pts[0][0] = (fastf_t)r2; pts[0][1] = (fastf_t) (len / 2.0 - r1 - r2); pts[0][2] = (fastf_t)hgt; pts[1][0] = (fastf_t)r2; pts[1][1] = (fastf_t) (len / 2.0); pts[1][2] = (fastf_t)hgt; pts[2][0] = (fastf_t)r2; pts[2][1] = (fastf_t) (len / 2.0); pts[2][2] = (fastf_t) (hgt -r1 - r2); pts[3][0] = (fastf_t)r2; pts[3][1] = (fastf_t) (len / 2.0 - r1 - r2); pts[3][2] = (fastf_t) (hgt -r1 - r2); pts[4][0] = (fastf_t)(-r2); pts[4][1] = (fastf_t) (len / 2.0 - r1 - r2); pts[4][2] = (fastf_t)hgt; pts[5][0] = (fastf_t)(-r2); pts[5][1] = (fastf_t) (len / 2.0); pts[5][2] = (fastf_t)hgt; pts[6][0] = (fastf_t)(-r2); pts[6][1] = (fastf_t) (len / 2.0); pts[6][2] = (fastf_t) (hgt -r1 - r2); pts[7][0] = (fastf_t)(-r2); pts[7][1] = (fastf_t) (len / 2.0 - r1 - r2); pts[7][2] = (fastf_t) (hgt -r1 - r2); solnam[6] ='6'; mk_arb8(fpw, solnam, &pts[0][X]); /* Create left arb8. */ pts[0][1] = (-pts[0][1]); pts[1][1] = (-pts[1][1]); pts[2][1] = (-pts[2][1]); pts[3][1] = (-pts[3][1]); pts[4][1] = (-pts[4][1]); pts[5][1] = (-pts[5][1]); pts[6][1] = (-pts[6][1]); pts[7][1] = (-pts[7][1]); solnam[6] = '7'; mk_arb8(fpw, solnam, &pts[0][X]); /* Create all regions. */ /* Initialize list. */ BU_LIST_INIT(&comb.l); solnam[6] = '1'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_INTERSECT); regnam[5] = 97 + i; regnam[6] = '1'; mk_lfcomb(fpw, regnam, &comb, 1); solnam[6] = '2'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_INTERSECT); regnam[6] = '2'; mk_lfcomb(fpw, regnam, &comb, 1); solnam[6] = '3'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_INTERSECT); regnam[6] = '3'; mk_lfcomb(fpw, regnam, &comb, 1); solnam[6] = '4'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_INTERSECT); solnam[6] = '6'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_INTERSECT); solnam[6] = '1'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_SUBTRACT); solnam[6] = '2'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_SUBTRACT); regnam[6] = '4'; mk_lfcomb(fpw, regnam, &comb, 1); solnam[6] = '5'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_INTERSECT); solnam[6] = '7'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_INTERSECT); solnam[6] = '1'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_SUBTRACT); solnam[6] = '3'; (void)mk_addmember(solnam, &comb.l, NULL, WMOP_SUBTRACT); regnam[6] = '5'; mk_lfcomb(fpw, regnam, &comb, 1); /* Create a group. */ /* Initialize list. */ BU_LIST_INIT(&comb1.l); regnam[6] = '1'; (void)mk_addmember(regnam, &comb1.l, NULL, WMOP_UNION); regnam[6] = '2'; (void)mk_addmember(regnam, &comb1.l, NULL, WMOP_UNION); regnam[6] = '3'; (void)mk_addmember(regnam, &comb1.l, NULL, WMOP_UNION); regnam[6] = '4'; (void)mk_addmember(regnam, &comb1.l, NULL, WMOP_UNION); regnam[6] = '5'; (void)mk_addmember(regnam, &comb1.l, NULL, WMOP_UNION); grpnam[3] = 97 + i; mk_lfcomb(fpw, grpnam, &comb1, 0); } /* END # 2 */ /* Close mged file. */ wdb_close(fpw); return 0; } /* END # 1 */ /* * Local Variables: * mode: C * tab-width: 8 * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
26.927632
95
0.54866
[ "cad", "solid" ]
fa50d0e7b7c5aa63df663c39dab90c7bf01f83c5
346
h
C
src/tutorial06/Headers.h
ksoderbl/thinmatrix-opengl-3d-game-tutorial-cpp-sdl2
c6d8e79c11a09284ee262fb44439e58cc9d7d906
[ "MIT" ]
9
2018-07-15T23:09:10.000Z
2021-05-14T16:45:03.000Z
src/tutorial06/Headers.h
ksoderbl/thinmatrix-opengl-3d-game-tutorial-cpp-sdl2
c6d8e79c11a09284ee262fb44439e58cc9d7d906
[ "MIT" ]
null
null
null
src/tutorial06/Headers.h
ksoderbl/thinmatrix-opengl-3d-game-tutorial-cpp-sdl2
c6d8e79c11a09284ee262fb44439e58cc9d7d906
[ "MIT" ]
5
2019-11-24T02:44:42.000Z
2022-01-07T14:49:33.000Z
#ifndef HEADERS_H #define HEADERS_H #include <GL/glew.h> #include <GL/gl.h> #include <GL/glu.h> #include <SDL2/SDL.h> #include <iostream> #include <fstream> #include <string> #include <vector> using std::cout; using std::cin; using std::ios; using std::cerr; using std::endl; using std::string; using std::ifstream; using std::vector; #endif
14.416667
21
0.710983
[ "vector" ]
fa547164d6cc8a5688277003baa4aa653ac4d4e4
453
h
C
include/keras/model.h
choiip/kerasify
9add953ad2333486de66e985213c6e57ea4c17b4
[ "MIT" ]
7
2018-04-02T07:31:30.000Z
2019-02-02T15:48:26.000Z
include/keras/model.h
choiip/kerasify
9add953ad2333486de66e985213c6e57ea4c17b4
[ "MIT" ]
null
null
null
include/keras/model.h
choiip/kerasify
9add953ad2333486de66e985213c6e57ea4c17b4
[ "MIT" ]
2
2019-04-18T05:43:45.000Z
2019-07-09T03:58:45.000Z
/* * Copyright (c) 2016 Robert W. Rose * Copyright (c) 2018 Paul Maevskikh * * MIT License, see LICENSE file. */ #pragma once #include "keras/io.h" #include "keras/layer.h" #include <memory> #include <vector> namespace keras { class Model final : public Layer<Model> { std::vector<std::unique_ptr<LayerBase>> layers_; public: Model(Stream& file); Tensor forward(const Tensor& in) const noexcept override; }; } // namespace keras
17.423077
61
0.684327
[ "vector", "model" ]
3658f85b9c0d03c2481fe7f452897b26c00f0a3a
11,896
c
C
uwb-beacon-firmware/src/usbconf.c
greck2908/robot-software
2e1e8177148a089e8883967375dde7f8ed3d878b
[ "MIT" ]
40
2016-10-04T19:59:22.000Z
2020-12-25T18:11:35.000Z
uwb-beacon-firmware/src/usbconf.c
greck2908/robot-software
2e1e8177148a089e8883967375dde7f8ed3d878b
[ "MIT" ]
209
2016-09-21T21:54:28.000Z
2022-01-26T07:42:37.000Z
uwb-beacon-firmware/src/usbconf.c
greck2908/robot-software
2e1e8177148a089e8883967375dde7f8ed3d878b
[ "MIT" ]
21
2016-11-07T14:40:16.000Z
2021-11-02T09:53:37.000Z
/* clang-format off */ #include "usbconf.h" /*Endpoints to be used for USBD1. */ #define USBD1_DATA_REQUEST_EP 1 #define USBD1_DATA_AVAILABLE_EP 1 #define USBD1_INTERRUPT_REQUEST_EP 2 extern const USBConfig usbcfg; extern const SerialUSBConfig serusbcfg; /* USB Device Descriptor. */ static const uint8_t vcom_device_descriptor_data[18] = { USB_DESC_DEVICE(0x0110, /* bcdUSB (1.1). */ 0x02, /* bDeviceClass (CDC). */ 0x00, /* bDeviceSubClass. */ 0x00, /* bDeviceProtocol. */ 0x40, /* bMaxPacketSize. */ 0x0483, /* idVendor (ST). */ 0x5740, /* idProduct. */ 0x0200, /* bcdDevice. */ 1, /* iManufacturer. */ 2, /* iProduct. */ 3, /* iSerialNumber. */ 1) /* bNumConfigurations. */ }; /* Device Descriptor wrapper. */ static const USBDescriptor vcom_device_descriptor = { sizeof vcom_device_descriptor_data, vcom_device_descriptor_data }; /* Configuration Descriptor tree for a CDC.*/ static const uint8_t vcom_configuration_descriptor_data[67] = { /* Configuration Descriptor.*/ USB_DESC_CONFIGURATION(67, /* wTotalLength. */ 0x02, /* bNumInterfaces. */ 0x01, /* bConfigurationValue. */ 0, /* iConfiguration. */ 0xC0, /* bmAttributes (self powered). */ 50), /* bMaxPower (100mA). */ /* Interface Descriptor.*/ USB_DESC_INTERFACE(0x00, /* bInterfaceNumber. */ 0x00, /* bAlternateSetting. */ 0x01, /* bNumEndpoints. */ 0x02, /* bInterfaceClass (Communications Interface Class, CDC section 4.2). */ 0x02, /* bInterfaceSubClass (Abstract Control Model, CDC section 4.3). */ 0x01, /* bInterfaceProtocol (AT commands, CDC section 4.4). */ 0), /* iInterface. */ /* Header Functional Descriptor (CDC section 5.2.3).*/ USB_DESC_BYTE(5), /* bLength. */ USB_DESC_BYTE(0x24), /* bDescriptorType (CS_INTERFACE). */ USB_DESC_BYTE(0x00), /* bDescriptorSubtype (Header Functional Descriptor. */ USB_DESC_BCD(0x0110), /* bcdCDC. */ /* Call Management Functional Descriptor. */ USB_DESC_BYTE(5), /* bFunctionLength. */ USB_DESC_BYTE(0x24), /* bDescriptorType (CS_INTERFACE). */ USB_DESC_BYTE(0x01), /* bDescriptorSubtype (Call Management Functional Descriptor). */ USB_DESC_BYTE(0x00), /* bmCapabilities (D0+D1). */ USB_DESC_BYTE(0x01), /* bDataInterface. */ /* ACM Functional Descriptor.*/ USB_DESC_BYTE(4), /* bFunctionLength. */ USB_DESC_BYTE(0x24), /* bDescriptorType (CS_INTERFACE). */ USB_DESC_BYTE(0x02), /* bDescriptorSubtype (Abstract Control Management Descriptor). */ USB_DESC_BYTE(0x02), /* bmCapabilities. */ /* Union Functional Descriptor.*/ USB_DESC_BYTE(5), /* bFunctionLength. */ USB_DESC_BYTE(0x24), /* bDescriptorType (CS_INTERFACE). */ USB_DESC_BYTE(0x06), /* bDescriptorSubtype (Union Functional Descriptor). */ USB_DESC_BYTE(0x00), /* bMasterInterface (Communication Class Interface). */ USB_DESC_BYTE(0x01), /* bSlaveInterface0 (Data Class Interface). */ /* Endpoint 2 Descriptor.*/ USB_DESC_ENDPOINT(USBD1_INTERRUPT_REQUEST_EP | 0x80, 0x03, /* bmAttributes (Interrupt). */ 0x0008, /* wMaxPacketSize. */ 0xFF), /* bInterval. */ /* Interface Descriptor.*/ USB_DESC_INTERFACE(0x01, /* bInterfaceNumber. */ 0x00, /* bAlternateSetting. */ 0x02, /* bNumEndpoints. */ 0x0A, /* bInterfaceClass (Data Class Interface, CDC section 4.5). */ 0x00, /* bInterfaceSubClass (CDC section 4.6). */ 0x00, /* bInterfaceProtocol (CDC section 4.7). */ 0x00), /* iInterface. */ /* Endpoint 3 Descriptor.*/ USB_DESC_ENDPOINT(USBD1_DATA_AVAILABLE_EP, /* bEndpointAddress.*/ 0x02, /* bmAttributes (Bulk). */ 0x0040, /* wMaxPacketSize. */ 0x00), /* bInterval. */ /* Endpoint 1 Descriptor.*/ USB_DESC_ENDPOINT(USBD1_DATA_REQUEST_EP | 0x80, /* bEndpointAddress.*/ 0x02, /* bmAttributes (Bulk). */ 0x0040, /* wMaxPacketSize. */ 0x00) /* bInterval. */ }; /* Configuration Descriptor wrapper. */ static const USBDescriptor vcom_configuration_descriptor = { sizeof vcom_configuration_descriptor_data, vcom_configuration_descriptor_data }; /* U.S. English language identifier. */ static const uint8_t vcom_string0[] = { USB_DESC_BYTE(4), /* bLength. */ USB_DESC_BYTE(USB_DESCRIPTOR_STRING), /* bDescriptorType. */ USB_DESC_WORD(0x0409) /* wLANGID (U.S. English). */ }; /* Vendor string. */ static const uint8_t vcom_string1[] = { USB_DESC_BYTE(10), /* bLength. */ USB_DESC_BYTE(USB_DESCRIPTOR_STRING), /* bDescriptorType. */ 'C', 0, 'V', 0, 'R', 0, 'A', 0, }; /* Device Description string. */ static const uint8_t vcom_string2[] = { USB_DESC_BYTE(22), /* bLength. */ USB_DESC_BYTE(USB_DESCRIPTOR_STRING), /* bDescriptorType. */ 'U', 0, 'W', 0, 'B', 0, ' ', 0, 'B', 0, 'e', 0, 'a', 0, 'c', 0, 'o', 0, 'n', 0, }; /* Serial Number string. */ static uint8_t vcom_string3[] = { USB_DESC_BYTE(10), /* bLength. */ USB_DESC_BYTE(USB_DESCRIPTOR_STRING), /* bDescriptorType. */ '0', 0, '0', 0, '0', 0, '0', 0 }; /* Strings wrappers array. */ static const USBDescriptor vcom_strings[] = { {sizeof vcom_string0, vcom_string0}, {sizeof vcom_string1, vcom_string1}, {sizeof vcom_string2, vcom_string2}, {sizeof vcom_string3, vcom_string3} }; static void update_serial_vcom(uint8_t *vcom, int serial) { vcom[2] = '0' + serial / 100; serial = serial % 100; vcom[4] = '0' + serial / 10; serial = serial % 10; vcom[6] = '0' + serial; } /* Handles the GET_DESCRIPTOR callback. All required descriptors must be * handled here. */ static const USBDescriptor *get_descriptor(USBDriver *usbp, uint8_t dtype, uint8_t dindex, uint16_t lang) { (void)usbp; (void)lang; switch (dtype) { case USB_DESCRIPTOR_DEVICE: return &vcom_device_descriptor; case USB_DESCRIPTOR_CONFIGURATION: return &vcom_configuration_descriptor; case USB_DESCRIPTOR_STRING: if (dindex < 4) { return &vcom_strings[dindex]; } } return NULL; } static USBInEndpointState ep1instate; static USBOutEndpointState ep1outstate; /** @brief EP1 initialization structure (both IN and OUT). */ static const USBEndpointConfig ep1config = { USB_EP_MODE_TYPE_BULK, NULL, sduDataTransmitted, sduDataReceived, 0x0040, 0x0040, &ep1instate, &ep1outstate, 2, NULL }; static USBInEndpointState ep2instate; static const USBEndpointConfig ep2config = { USB_EP_MODE_TYPE_INTR, NULL, sduInterruptTransmitted, NULL, 0x0010, 0x0000, &ep2instate, NULL, 1, NULL }; /** Handles the USB driver global events. */ static void usb_event(USBDriver *usbp, usbevent_t event) { switch (event) { case USB_EVENT_ADDRESS: return; case USB_EVENT_CONFIGURED: chSysLockFromISR(); /* Enables the endpoints specified into the configuration. Note, this callback is invoked from an ISR so I-Class functions must be used.*/ usbInitEndpointI(usbp, USBD1_DATA_REQUEST_EP, &ep1config); usbInitEndpointI(usbp, USBD1_INTERRUPT_REQUEST_EP, &ep2config); /* Resetting the state of the CDC subsystem.*/ sduConfigureHookI(&SDU1); chSysUnlockFromISR(); return; case USB_EVENT_RESET: /* Falls into.*/ case USB_EVENT_UNCONFIGURED: /* Falls into.*/ case USB_EVENT_SUSPEND: chSysLockFromISR(); /* Disconnection event on suspend.*/ sduSuspendHookI(&SDU1); chSysUnlockFromISR(); return; case USB_EVENT_WAKEUP: return; case USB_EVENT_STALLED: return; } return; } /* * Handles the USB driver global events. */ static void sof_handler(USBDriver *usbp) { (void)usbp; osalSysLockFromISR(); sduSOFHookI(&SDU1); osalSysUnlockFromISR(); } /* * USB driver configuration. */ const USBConfig usbcfg = { usb_event, get_descriptor, sduRequestsHook, sof_handler }; /* * Serial over USB driver configuration. */ const SerialUSBConfig serusbcfg = { &USBD1, USBD1_DATA_REQUEST_EP, USBD1_DATA_AVAILABLE_EP, USBD1_INTERRUPT_REQUEST_EP }; /* Serial over USB Driver structure. */ SerialUSBDriver SDU1; void usb_start(unsigned int serial) { /* First genereate the serial number string from the serial number. */ update_serial_vcom(vcom_string3, serial); /* * Activates the USB driver and then the USB bus pull-up on D+. * Note, a delay is inserted in order to not have to disconnect the cable * after a reset. */ usbDisconnectBus(serusbcfg.usbp); chThdSleepMilliseconds(1500); usbStart(serusbcfg.usbp, &usbcfg); usbConnectBus(serusbcfg.usbp); sduObjectInit(&SDU1); sduStart(&SDU1, &serusbcfg); } /* clang-format on */
36.944099
81
0.492939
[ "model" ]
3659586709ff4004411b762d2c7f99f3b9cca39e
3,618
c
C
backup/serialElliptic/src/ellipticScaledAdd.c
noelchalmers/benchparanumal
96c22154a13348c3f34df7483c6977abb5aaa718
[ "MIT" ]
null
null
null
backup/serialElliptic/src/ellipticScaledAdd.c
noelchalmers/benchparanumal
96c22154a13348c3f34df7483c6977abb5aaa718
[ "MIT" ]
null
null
null
backup/serialElliptic/src/ellipticScaledAdd.c
noelchalmers/benchparanumal
96c22154a13348c3f34df7483c6977abb5aaa718
[ "MIT" ]
null
null
null
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "elliptic.h" template < int p_Nq > void ellipticSerialScaledAddKernel(const hlong Nelements, const dfloat alpha, const dfloat * __restrict__ cpu_a, const dfloat beta, dfloat * __restrict__ cpu_b){ cpu_a = (dfloat*)__builtin_assume_aligned(cpu_a, USE_OCCA_MEM_BYTE_ALIGN) ; cpu_b = (dfloat*)__builtin_assume_aligned(cpu_b, USE_OCCA_MEM_BYTE_ALIGN) ; #define p_Np (p_Nq*p_Nq*p_Nq) for(hlong e=0;e<Nelements;++e){ for(int i=0;i<p_Np;++i){ const dfloat ai = cpu_a[e*p_Np+i]; const dfloat bi = cpu_b[e*p_Np+i]; cpu_b[e*p_Np+i] = alpha*ai + beta*bi; } } #undef p_Np } void ellipticSerialScaledAdd(const int Nq, const hlong Nelements, const dfloat alpha, occa::memory &o_a, const dfloat beta, occa::memory &o_b){ const dfloat * __restrict__ cpu_a = (dfloat*)__builtin_assume_aligned(o_a.ptr(), USE_OCCA_MEM_BYTE_ALIGN) ; dfloat * __restrict__ cpu_b = (dfloat*)__builtin_assume_aligned(o_b.ptr(), USE_OCCA_MEM_BYTE_ALIGN) ; switch(Nq){ case 2: ellipticSerialScaledAddKernel < 2 > (Nelements, alpha, cpu_a, beta, cpu_b); break; case 3: ellipticSerialScaledAddKernel < 3 > (Nelements, alpha, cpu_a, beta, cpu_b); break; case 4: ellipticSerialScaledAddKernel < 4 > (Nelements, alpha, cpu_a, beta, cpu_b); break; case 5: ellipticSerialScaledAddKernel < 5 > (Nelements, alpha, cpu_a, beta, cpu_b); break; case 6: ellipticSerialScaledAddKernel < 6 > (Nelements, alpha, cpu_a, beta, cpu_b); break; case 7: ellipticSerialScaledAddKernel < 7 > (Nelements, alpha, cpu_a, beta, cpu_b); break; case 8: ellipticSerialScaledAddKernel < 8 > (Nelements, alpha, cpu_a, beta, cpu_b); break; case 9: ellipticSerialScaledAddKernel < 9 > (Nelements, alpha, cpu_a, beta, cpu_b); break; case 10: ellipticSerialScaledAddKernel < 10 > (Nelements, alpha, cpu_a, beta, cpu_b); break; } } void ellipticScaledAdd(elliptic_t *elliptic, dfloat alpha, occa::memory &o_a, dfloat beta, occa::memory &o_b){ mesh_t *mesh = elliptic->mesh; setupAide &options = elliptic->options; int continuous = options.compareArgs("DISCRETIZATION", "CONTINUOUS"); int serial = options.compareArgs("THREAD MODEL", "Serial"); dlong Ntotal = mesh->Nelements*mesh->Np; // b[n] = alpha*a[n] + beta*b[n] n\in [0,Ntotal) if(serial == 1 && continuous==1){ ellipticSerialScaledAdd(mesh->Nq, mesh->Nelements, alpha, o_a, beta, o_b); return; } // if not Serial elliptic->scaledAddKernel(Ntotal, alpha, o_a, beta, o_b); }
42.069767
161
0.736042
[ "mesh", "model" ]
365b87f3597859dc903fe5ea984975db9c878d57
6,995
h
C
Example/Pods/LayerKit.framework/Headers/LYRMessagePart.h
maybeiamme/PGAtlas
58daac18f2032cdfd5865d3c5129b83c5c188adc
[ "MIT" ]
null
null
null
Example/Pods/LayerKit.framework/Headers/LYRMessagePart.h
maybeiamme/PGAtlas
58daac18f2032cdfd5865d3c5129b83c5c188adc
[ "MIT" ]
null
null
null
Example/Pods/LayerKit.framework/Headers/LYRMessagePart.h
maybeiamme/PGAtlas
58daac18f2032cdfd5865d3c5129b83c5c188adc
[ "MIT" ]
null
null
null
// // LYRMessagePart.h // LayerKit // // Created by Blake Watters on 5/8/14. // Copyright (c) 2014 Layer Inc. All rights reserved. // #import <Foundation/Foundation.h> #import "LYRQuery.h" #import "LYRConstants.h" #import "LYRProgress.h" @class LYRMessage; /** @abstract The `LYRContentTransferStatus` enumeration describes the transfer status of the message part's content. */ typedef NS_ENUM(NSUInteger, LYRContentTransferStatus) { /** @abstract Content is available locally and is yet to be uploaded. @discussion This state is expected before the message is sent. */ LYRContentTransferAwaitingUpload, /** @abstract Content is available locally and is in a state of uploading. @discussion This state is expected when message is in the sending process. */ LYRContentTransferUploading, /** @abstract Content is not available locally but it is ready for download. @discussion This state is expected when message part didn't met the criteria to be auto-downloaded. Use `downloadContent` to initiate a manual download process. @see `[(LYRClient *)client setConfiguration:forConnection:]` on how to use auto-downlod features. */ LYRContentTransferReadyForDownload, /** @abstract Content is not yet avaiable locally and is in a state of downloading. @discussion This state is expected when message part downloaded was started manually or by using the auto-download feature. */ LYRContentTransferDownloading, /** @abstract Content is available locally. @abstract This state is expected when the transfer completes. */ LYRContentTransferComplete, }; /** @abstract The `LYRMessagePart` class represents a piece of content embedded within a containing message. Each part has a specific MIME Type identifying the type of content it contains. Messages may contain an arbitrary number of parts with any MIME Type that the application wishes to support. */ @interface LYRMessagePart : NSObject <LYRQueryable> ///----------------------------- /// @name Creating Message Parts ///----------------------------- /** @abstract Creates a message part with the given MIME Type and data. @param MIMEType A MIME Type identifying the type of data contained in the given data object. @param data The data to be embedded in the mesage part. @return A new message part with the given MIME Type and data. @raises NSInvalidArgumentException Raised if MIME Type or data is nil. */ + (nonnull instancetype)messagePartWithMIMEType:(nonnull NSString *)MIMEType data:(nonnull NSData *)data; /** @abstract Creates a message part with the given MIME Type and stream of data. @param MIMEType A MIME Type identifying the type of data contained in the given data object. @param stream A stream from which to read the data for the message part. @return A new message part with the given MIME Type and stream of data. @raises NSInvalidArgumentException Raised if MIME Type or stream is nil. */ + (nonnull instancetype)messagePartWithMIMEType:(nonnull NSString *)MIMEType stream:(nonnull NSInputStream *)stream; /** @abstract Create a message part with a string of text. @discussion This is a convience accessor encapsulating the common operation of creating a message part with a plain text data attachment in UTF-8 encoding. It is functionally equivalent to the following example code: [LYRMessagePart messagePartWithMIMEType:@"text/plain" data:[text dataUsingEncoding:NSUTF8StringEncoding]]; @param text The plain text body of the new message part. @return A new message part with the MIME Type text/plain and a UTF-8 encoded representation of the given input text. @raises NSInvalidArgumentException Raised if text is nil. */ + (nonnull instancetype)messagePartWithText:(nonnull NSString *)text; ///--------------- /// @name Identity ///--------------- /** @abstract A unique identifier for the message part. */ @property (nonatomic, readonly, nonnull) NSURL *identifier LYR_QUERYABLE_PROPERTY; /** @abstract Object index dictating message part order in a collection of LYRMessage. */ @property (nonatomic, readonly) NSUInteger index LYR_QUERYABLE_PROPERTY; /** @abstract The message that the receiver is a part of. */ @property (nonatomic, readonly, nullable) LYRMessage *message LYR_QUERYABLE_PROPERTY; ///------------------------ /// @name Accessing Content ///------------------------ /** @abstract The MIME Type of the content represented by the receiver. */ @property (nonatomic, readonly, nonnull) NSString *MIMEType LYR_QUERYABLE_PROPERTY LYR_QUERYABLE_FROM(LYRMessage); /** @abstract The content of the receiver as a data object. @discussion Property will be `nil` if content is not availble. Note that this operation might be expensive if trying to read large data. */ @property (nonatomic, readonly, nullable) NSData *data; /** @abstract Returns a `NSURL` object to the filesystem location of the receiver’s content or `nil` if the content is not available locally or was transmitted inline. @discussion Property will be `nil` if content is not availble. */ @property (nonatomic, readonly, nullable) NSURL *fileURL; /** @abstract The size of the content in bytes. */ @property (nonatomic, readonly) LYRSize size LYR_QUERYABLE_PROPERTY LYR_QUERYABLE_FROM(LYRMessage); /** @abstract The current transfer status of the message part. */ @property (nonatomic, readonly) LYRContentTransferStatus transferStatus LYR_QUERYABLE_PROPERTY LYR_QUERYABLE_FROM(LYRMessage); /** @abstract Progress of the current transfer state. @discussion Property will return a new instance, if previous one has been released from the memory. */ @property (nonatomic, readonly, nonnull) LYRProgress *progress; /** @abstract Returns a new input stream object for reading the content of the receiver as a stream. @return A new, unopened input stream object configured for reading the content of the part represented by the receiver, if the content is available, otherwise `nil`. */ - (nullable NSInputStream *)inputStream; /** @abstract Tells the receiver to schedule a download of the content, optionally reporting progress. @param error A pointer to an error object that upon failure will be set to an object that indicates why the download could not be started. @return An `LYRProgress` object that reports the progress of the download operation or `nil` if the content cannot be downloaded. */ - (nullable LYRProgress *)downloadContent:(NSError * _Nullable * _Nullable)error; /** @abstract Tells the receiver to schedule a purge of the content, optionally reporting progress. @param error A pointer to an error object that upon failure will be set to an object that indicates why the content could not be purged. @return An `LYRProgress` object that reports the progress of the content purging operation or `nil` if the content cannot be purged. */ - (nullable LYRProgress *)purgeContent:(NSError * _Nullable * _Nullable)error; @end
41.390533
166
0.74782
[ "object" ]
36621a0b9ef212956a16c64ae74e6d8b2bc7c88f
3,997
h
C
Modules/Filtering/Path/include/itkChainCodeToFourierSeriesPathFilter.h
GEHC-Surgery/ITK
f5df62749e56c9036e5888cfed904032ba5fdfb7
[ "Apache-2.0" ]
1
2015-12-11T14:35:23.000Z
2015-12-11T14:35:23.000Z
Modules/Filtering/Path/include/itkChainCodeToFourierSeriesPathFilter.h
GEHC-Surgery/ITK
f5df62749e56c9036e5888cfed904032ba5fdfb7
[ "Apache-2.0" ]
null
null
null
Modules/Filtering/Path/include/itkChainCodeToFourierSeriesPathFilter.h
GEHC-Surgery/ITK
f5df62749e56c9036e5888cfed904032ba5fdfb7
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkChainCodeToFourierSeriesPathFilter_h #define __itkChainCodeToFourierSeriesPathFilter_h #include "itkPathToPathFilter.h" #include "itkOffset.h" //Templates require interfaces conforming to itkPath.h and itkChainCodePath.h namespace itk { /** \class ChainCodeToFourierSeriesPathFilter * \brief Filter that produces a Fourier series version of a chain code path * * ChainCodeToFourierSeriesPathFilter produces a Fourier series representation * of a chain code path. By default, the first 8 harmonics (frequency * coefficients, which include the "DC" term) are computed. * SetNumberOfHarmonics() can be used to override this value. * Because the requested number of harmonics may not be able to be computed, * it is advisable to check the number of harmonics in the actual output. * * \ingroup PathFilters * \ingroup ITKPath */ template< class TInputChainCodePath, class TOutputFourierSeriesPath > class ChainCodeToFourierSeriesPathFilter:public PathToPathFilter< TInputChainCodePath, TOutputFourierSeriesPath > { public: /** Standard class typedefs. */ typedef ChainCodeToFourierSeriesPathFilter Self; typedef PathToPathFilter< TInputChainCodePath, TOutputFourierSeriesPath > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(ChainCodeToFourierSeriesPathFilter, PathToPathFilter); /** Some convenient typedefs. */ typedef TInputChainCodePath InputPathType; typedef typename InputPathType::Pointer InputPathPointer; typedef typename InputPathType::InputType InputPathInputType; typedef TOutputFourierSeriesPath OutputPathType; typedef typename OutputPathType::Pointer OutputPathPointer; typedef typename OutputPathType::InputType OutputPathInputType; typedef typename InputPathType::IndexType IndexType; typedef typename InputPathType::OffsetType OffsetType; typedef typename OutputPathType::VectorType VectorType; /** Set the number of harmonics to try to compute. By default, the first 8 * harmonics (frequency coefficients, which include the "DC" term) are * computed. SetNumberOfHarmonics() can be used to override this value. If * the chain code has too few steps to calculate the desired number of * harmonics (due to the Nyquist criterion), then as many harmonics as are * possible (input->NumberOfSteps()/2) will be calculated, but at least 2 * harmonics will always be calculated.*/ itkSetMacro(NumberOfHarmonics, unsigned int) protected: ChainCodeToFourierSeriesPathFilter(); virtual ~ChainCodeToFourierSeriesPathFilter() {} void PrintSelf(std::ostream & os, Indent indent) const; void GenerateData(void); private: ChainCodeToFourierSeriesPathFilter(const Self &); //purposely not implemented void operator=(const Self &); //purposely not implemented unsigned int m_NumberOfHarmonics; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkChainCodeToFourierSeriesPathFilter.hxx" #endif #endif
40.373737
79
0.7338
[ "object" ]
366443791a2efe44fc8b2eaaa0c2c2909e3c8f8e
1,777
h
C
Reflection/Controls/Aspects/IndexedPropertyAspect.h
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
Reflection/Controls/Aspects/IndexedPropertyAspect.h
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
Reflection/Controls/Aspects/IndexedPropertyAspect.h
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
#pragma once // Copyright (c) 2021 DNV AS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #include "IControlAspect.h" #include "Reflection/Objects/Object.h" #include <map> #include "TypeUtilities/CompareCaseLess.h" namespace DNVS {namespace MoFa {namespace Reflection {namespace Controls { //This aspect represents constant values stored on the node. This is used when parsing the RecordAttribute to store the row and column information for a given node. class REFLECTION_IMPORT_EXPORT IndexedPropertyAspect : public IControlAspectT<IndexedPropertyAspect> { public: using IndexMap = std::map<std::string, Objects::Object, TypeUtilities::CompareCaseLess>; IndexedPropertyAspect(const Members::MemberPointer& setFunction, const Members::MemberPointer& getFunction, const IndexMap& indices); ~IndexedPropertyAspect(); const Attributes::AttributeCollection& GetAttributeCollection() const override; bool operator==(const IndexedPropertyAspect& other) const override; std::string ToString() const override; const IndexMap& GetIndices() const; const Members::MemberPointer& GetGetFunction() const; const Members::MemberPointer& GetSetFunction() const; Contents::Content TryGetPropertyContent(const Contents::Content& parent, bool trySimplify = true) override; Contents::Content TrySetPropertyContent(const Contents::Content& parent, const Contents::Content& value) override; bool SupportAssign() const override; private: Members::MemberPointer m_setFunction; Members::MemberPointer m_getFunction; IndexMap m_indices; }; }}}}
50.771429
168
0.741699
[ "object" ]
366869fc3d5a5ce3f106cb4a4a1b5d7314eaa456
558
h
C
Include/Serialize/BaseTypeSerializeMethods.h
MrFrenik/Enjon
405733f1b8d05c65bc6b4f4c779d3c6845a8c12b
[ "BSD-3-Clause" ]
121
2019-05-02T01:22:17.000Z
2022-03-19T00:16:14.000Z
Include/Serialize/BaseTypeSerializeMethods.h
MrFrenik/Enjon
405733f1b8d05c65bc6b4f4c779d3c6845a8c12b
[ "BSD-3-Clause" ]
42
2019-08-17T20:33:43.000Z
2019-09-25T14:28:50.000Z
Include/Serialize/BaseTypeSerializeMethods.h
MrFrenik/Enjon
405733f1b8d05c65bc6b4f4c779d3c6845a8c12b
[ "BSD-3-Clause" ]
20
2019-05-02T01:22:20.000Z
2022-01-30T04:04:57.000Z
// Copyright 2016-2017 John Jackson. All Rights Reserved. // File: BaseTypeSerializeMethods.h #pragma once #ifndef ENJON_PROPERTY_SERIALIZER_ARCHIVER_H #define ENJON_PROPERTY_SERIALIZER_ARCHIVER_H #include "Base/Object.h" #include "Serialize/ByteBuffer.h" namespace Enjon { class PropertyArchiver { public: /** * @brief */ static void Serialize( const Object* object, const MetaProperty* property, ByteBuffer* buffer ); /** * @brief */ static void Deserialize( const Object* object, ByteBuffer* buffer ); }; } #endif
18
100
0.716846
[ "object" ]
3669c92a571867eb135a7277b55709a5ab937983
3,787
h
C
QueryEngine/Descriptors/ColSlotContext.h
gitboti/omniscidb
70db1e5ef56cbaf6ee1773f2b11afd523da83e5d
[ "Apache-2.0" ]
null
null
null
QueryEngine/Descriptors/ColSlotContext.h
gitboti/omniscidb
70db1e5ef56cbaf6ee1773f2b11afd523da83e5d
[ "Apache-2.0" ]
1
2021-02-24T03:22:29.000Z
2021-02-24T03:22:29.000Z
QueryEngine/Descriptors/ColSlotContext.h
isabella232/omniscidb
bf83d84833710679debdf7a0484b6fbfc421cc96
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 OmniSci, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file ColSlotContext.h * @author Alex Baden <alex.baden@omnisci.com> * @brief Provides column info and slot info for the output buffer and some metadata * helpers * */ #pragma once #include "Logger/Logger.h" #include <algorithm> #include <string> #include <vector> struct SlotSize { int8_t padded_size; // size of the slot int8_t logical_size; // size of the element in the slot }; inline bool operator==(const SlotSize& lhs, const SlotSize& rhs) { return lhs.padded_size == rhs.padded_size && lhs.logical_size == rhs.logical_size; } namespace Analyzer { class Expr; } class ColSlotContext { public: ColSlotContext() {} ColSlotContext(const std::vector<Analyzer::Expr*>& col_expr_list, const std::vector<int64_t>& col_exprs_to_not_project); void setAllSlotsSize(const int8_t slot_width_size); void setAllSlotsPaddedSize(const int8_t padded_size); void setAllUnsetSlotsPaddedSize(const int8_t padded_size); void setAllSlotsPaddedSizeToLogicalSize(); void validate() const; size_t getColCount() const; size_t getSlotCount() const; const SlotSize& getSlotInfo(const size_t slot_idx) const { CHECK_LT(slot_idx, slot_sizes_.size()); return slot_sizes_[slot_idx]; } const std::vector<size_t>& getSlotsForCol(const size_t col_idx) const { CHECK_LT(col_idx, col_to_slot_map_.size()); return col_to_slot_map_[col_idx]; } size_t getAllSlotsPaddedSize() const; size_t getAllSlotsAlignedPaddedSize() const; size_t getAlignedPaddedSizeForRange(const size_t end) const; size_t getTotalBytesOfColumnarBuffers(const size_t entry_count) const; int8_t getMinPaddedByteSize(const int8_t actual_min_byte_width) const; size_t getCompactByteWidth() const; size_t getColOnlyOffInBytes(const size_t slot_idx) const; bool empty(); void clear(); void addColumn(const std::vector<std::tuple<int8_t, int8_t>>& slots_for_col); bool operator==(const ColSlotContext& that) const { return std::equal( slot_sizes_.cbegin(), slot_sizes_.cend(), that.slot_sizes_.cbegin()) && std::equal(col_to_slot_map_.cbegin(), col_to_slot_map_.cend(), that.col_to_slot_map_.cbegin()); } bool operator!=(const ColSlotContext& that) const { return !(*this == that); } void alignPaddedSlots(const bool sort_on_gpu); std::string toString() const { std::string str{"Col Slot Context State\n"}; if (slot_sizes_.empty()) { str += "\tEmpty"; return str; } str += "\tN | P , L\n"; for (size_t i = 0; i < slot_sizes_.size(); i++) { const auto& slot_size = slot_sizes_[i]; str += "\t" + std::to_string(i) + " | " + std::to_string(slot_size.padded_size) + " , " + std::to_string(slot_size.logical_size) + "\n"; } return str; } private: void addSlotForColumn(const int8_t logical_size, const size_t column_idx); void addSlotForColumn(const int8_t padded_size, const int8_t logical_size, const size_t column_idx); std::vector<SlotSize> slot_sizes_; std::vector<std::vector<size_t>> col_to_slot_map_; };
28.473684
87
0.694217
[ "vector" ]
366c05e4f1f0d284ca2cc5055252e1b428db3f42
4,883
h
C
utils/ChUtilsInputOutput.h
Chen-Tang/chrono-vehicle
ecef212010a01832cdecac8dacd2bae7b1d237de
[ "BSD-3-Clause" ]
2
2018-05-16T04:00:30.000Z
2021-03-12T11:24:54.000Z
utils/ChUtilsInputOutput.h
Chen-Tang/chrono-vehicle
ecef212010a01832cdecac8dacd2bae7b1d237de
[ "BSD-3-Clause" ]
null
null
null
utils/ChUtilsInputOutput.h
Chen-Tang/chrono-vehicle
ecef212010a01832cdecac8dacd2bae7b1d237de
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // A set of utility classes and functions for I/O. // // ============================================================================= #ifndef CH_UTILS_INOUT_H #define CH_UTILS_INOUT_H #include <string> #include <iostream> #include <sstream> #include <fstream> #include "physics/ChSystem.h" #include "assets/ChColor.h" #include "utils/ChApiUtils.h" #include "utils/ChUtilsCreators.h" namespace chrono { namespace utils { // ----------------------------------------------------------------------------- // CSV_writer // // Simple class to output to a Comma-Separated Values file. // ----------------------------------------------------------------------------- class CH_UTILS_API CSV_writer { public: explicit CSV_writer(const std::string& delim = ",") : m_delim(delim) {} CSV_writer(const CSV_writer& source) : m_delim(source.m_delim) { // Note that we do not copy the stream buffer (as then it would be shared!) m_ss.copyfmt(source.m_ss); // copy all data m_ss.clear(source.m_ss.rdstate()); // copy the error state } ~CSV_writer() {} void write_to_file(const std::string& filename, const std::string& header = "") { std::ofstream ofile(filename.c_str()); ofile << header; ofile << m_ss.str(); ofile.close(); } const std::string& delim() const { return m_delim; } std::ostringstream& stream() { return m_ss; } template <typename T> CSV_writer& operator<< (const T& t) { m_ss << t << m_delim; return *this; } CSV_writer& operator<<(std::ostream& (*t)(std::ostream&)) { m_ss << t; return *this; } CSV_writer& operator<<(std::ios& (*t)(std::ios&)) { m_ss << t; return *this; } CSV_writer& operator<<(std::ios_base& (*t)(std::ios_base&)) { m_ss << t; return *this; } private: std::string m_delim; std::ostringstream m_ss; }; inline CSV_writer& operator<< (CSV_writer& out, const ChVector<>& v) { out << v.x << v.y << v.z; return out; } inline CSV_writer& operator<< (CSV_writer& out, const ChQuaternion<>& q) { out << q.e0 << q.e1 << q.e2 << q.e3; return out; } inline CSV_writer& operator<< (CSV_writer& out, const ChColor& c) { out << c.R << c.G << c.B; return out; } // ----------------------------------------------------------------------------- // Free function declarations // ----------------------------------------------------------------------------- // Write to a CSV file pody position, orientation, and (optionally) linear and // angular velocity. Optionally, only active bodies are processed. CH_UTILS_API void WriteBodies(ChSystem* system, const std::string& filename, bool active_only = false, bool dump_vel = false, const std::string& delim = ","); // Create a CSV file with a checkpoint... CH_UTILS_API bool WriteCheckpoint(ChSystem* system, const std::string& filename); // Read a CSV file with a checkpoint... CH_UTILS_API void ReadCheckpoint(ChSystem* system, const std::string& filename); // Write CSV output file for PovRay. // Each line contains information about one visualization asset shape, as // follows: // index, x, y, z, e0, e1, e2, e3, type, geometry // where 'geometry' depends on 'type' (an enum). CH_UTILS_API void WriteShapesPovray(ChSystem* system, const std::string& filename, bool body_info = true, const std::string& delim = ","); // Write the triangular mesh from the specified OBJ file as a macro in a PovRay // include file. The output file will be "[out_dir]/[mesh_name].inc". The mesh // vertices will be tramsformed to the frame with specified offset and // orientation. CH_UTILS_API void WriteMeshPovray(const std::string& obj_filename, const std::string& mesh_name, const std::string& out_dir, const ChColor& color = ChColor(0.4f, 0.4f, 0.4f), const ChVector<>& pos = ChVector<>(0, 0, 0), const ChQuaternion<>& rot = ChQuaternion<>(1, 0, 0, 0)); } // namespace utils } // namespace chrono #endif
32.337748
102
0.537375
[ "mesh", "geometry", "shape" ]
366f4f1deed185115df56f7b790453694fc64a0c
17,056
h
C
include/tvm/runtime/profiling.h
Xuyuanjia2014/tvm
892f8305e77ad506660b851f9ce4c81be0f95d9d
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
2,084
2020-11-25T02:31:53.000Z
2022-03-31T11:33:47.000Z
include/tvm/runtime/profiling.h
Xuyuanjia2014/tvm
892f8305e77ad506660b851f9ce4c81be0f95d9d
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
3,022
2020-11-24T14:02:31.000Z
2022-03-31T23:55:31.000Z
include/tvm/runtime/profiling.h
Xuyuanjia2014/tvm
892f8305e77ad506660b851f9ce4c81be0f95d9d
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
977
2020-11-25T00:54:52.000Z
2022-03-31T12:47:08.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file include/tvm/runtime/profiling.h * \brief Runtime profiling including timers. */ #ifndef TVM_RUNTIME_PROFILING_H_ #define TVM_RUNTIME_PROFILING_H_ #include <tvm/runtime/c_runtime_api.h> #include <tvm/runtime/device_api.h> #include <tvm/runtime/object.h> #include <tvm/runtime/packed_func.h> #include <tvm/runtime/registry.h> #include <stack> #include <string> #include <unordered_map> #include <utility> #include <vector> namespace tvm { namespace runtime { /*! \brief Base class for all implementations. * * New implementations of this interface should make sure that `Start` and `Stop` * are as lightweight as possible. Expensive state synchronization should be * done in `SyncAndGetElapsedNanos`. */ class TimerNode : public Object { public: /*! \brief Start the timer. * * Note: this function should only be called once per object. */ virtual void Start() = 0; /*! \brief Stop the timer. * * Note: this function should only be called once per object. */ virtual void Stop() = 0; /*! \brief Synchronize timer state and return elapsed time between `Start` and `Stop`. * \return The time in nanoseconds between `Start` and `Stop`. * * This function is necessary because we want to avoid timing the overhead of * doing timing. When using multiple timers, it is recommended to stop all of * them before calling `SyncAndGetElapsedNanos` on any of them. * * Note: this function should be only called once per object. It may incur * a large synchronization overhead (for example, with GPUs). */ virtual int64_t SyncAndGetElapsedNanos() = 0; virtual ~TimerNode() {} static constexpr const char* _type_key = "TimerNode"; TVM_DECLARE_BASE_OBJECT_INFO(TimerNode, Object); }; /*! \brief Timer for a specific device. * * This is a managed reference to a TimerNode. * * \sa TimerNode */ class Timer : public ObjectRef { public: /*! * \brief Get a device specific timer. * \param dev The device to time. * \return A `Timer` that has already been started. * * Use this function to time runtime of arbitrary regions of code on a specific * device. The code that you want to time should be running on the device * otherwise the timer will not return correct results. This is a lower level * interface than TimeEvaluator and only runs the timed code once * (TimeEvaluator runs the code multiple times). * * A default timer is used if a device specific one does not exist. This * timer performs synchronization between the device and CPU, which can lead * to overhead in the reported results. * * Example usage: * \code{.cpp} * Timer t = Timer::Start(Device::cpu()); * my_long_running_function(); * t->Stop(); * ... // some more computation * int64_t nanosecs = t->SyncAndGetElapsedNanos() // elapsed time in nanoseconds * \endcode * * To add a new device-specific timer, register a new function * "profiler.timer.my_device" (where `my_device` is the `DeviceName` of your * device). This function should accept a `Device` and return a new `Timer` * that has already been started. * * For example, this is how the CPU timer is implemented: * \code{.cpp} * class CPUTimerNode : public TimerNode { * public: * virtual void Start() { start_ = std::chrono::high_resolution_clock::now(); } * virtual void Stop() { duration_ = std::chrono::high_resolution_clock::now() - start_; } * virtual int64_t SyncAndGetElapsedNanos() { return duration_.count(); } * virtual ~CPUTimerNode() {} * * static constexpr const char* _type_key = "CPUTimerNode"; * TVM_DECLARE_FINAL_OBJECT_INFO(CPUTimerNode, TimerNode); * * private: * std::chrono::high_resolution_clock::time_point start_; * std::chrono::duration<int64_t, std::nano> duration_; * }; * TVM_REGISTER_OBJECT_TYPE(CPUTimerNode); * * TVM_REGISTER_GLOBAL("profiling.timer.cpu").set_body_typed([](Device dev) { * return Timer(make_object<CPUTimerNode>()); * }); * \endcode */ static TVM_DLL Timer Start(Device dev); TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(Timer, ObjectRef, TimerNode); }; /*! * \brief Default timer if one does not exist for the device. * \param dev The device to time on. * * Note that this timer performs synchronization between the device and CPU, * which can lead to overhead in the reported results. */ Timer DefaultTimer(Device dev); namespace profiling { /*! \brief Wrapper for `Device` because `Device` is not passable across the * PackedFunc interface. */ struct DeviceWrapperNode : public Object { /*! The device */ Device device; /*! Constructor */ explicit DeviceWrapperNode(Device device) : device(device) {} static constexpr const char* _type_key = "runtime.profiling.DeviceWrapper"; TVM_DECLARE_BASE_OBJECT_INFO(DeviceWrapperNode, Object); }; /*! \brief Wrapper for `Device`. */ class DeviceWrapper : public ObjectRef { public: explicit DeviceWrapper(Device dev) { data_ = make_object<DeviceWrapperNode>(dev); } TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(DeviceWrapper, ObjectRef, DeviceWrapperNode); }; /*! \brief Data collected from a profiling run. Includes per-call metrics and per-device metrics. */ class ReportNode : public Object { public: /*! \brief A list of function calls and the metrics recorded for that call. * * Each element is a mapping from metric name to value. Some metrics that * appear in every call are "Name" (the function name), "Argument Shapes", * and "Duration (us)". Values are one of `String`, `PercentNode`, * `DurationNode`, or `CountNode`. */ Array<Map<String, ObjectRef>> calls; /*! \brief Metrics collected for the entire run of the model on a per-device basis. * * `device_metrics` is indexed by device name then metric. * * These metrics may be larger than the sum of the same metric in `calls` * because these metrics include the overhead of the executor. */ Map<String, Map<String, ObjectRef>> device_metrics; /*! \brief Output `calls` in CSV format. * * Note that this does not include `device_metrics`, it only includes per-call metrics. */ String AsCSV() const; /*! \brief Create a human readable table of profiling metrics. * * \param aggregate Whether or not to join multiple calls to the * same op into a single line. * * \param sort Whether or not to sort call frames by descending * duration. If false and if `aggregate` is false, frames will * be sorted by order of appearance in the program. Order is * undefined if `sort` is false and `aggregate` is true. * * \param compute_col_sums Whether or not to include sum totals for * the Count, Duation, and Percent columns. * */ String AsTable(bool sort = true, bool aggregate = true, bool compute_col_sums = true) const; /*! \brief Convert this report to JSON. * * Output JSON will be of this format: * \code * { * "calls": [ * { * "Duration (us)": { * "microseconds": 12.3 * }, * "Name": "fused_dense", * "Count": { * "count": 1 * }, * "Percent": { * "percent": 10.3 * } * } * ], * "device_metrics": { * "cpu": { * "Duration (us)": { * "microseconds": 334.2 * }, * "Percent": { * "percent": 100 * } * } * } * } * \endcode */ String AsJSON() const; static constexpr const char* _type_key = "runtime.profiling.Report"; TVM_DECLARE_FINAL_OBJECT_INFO(ReportNode, Object); }; class Report : public ObjectRef { public: /*! Construct a Report from a set of calls (with associated metrics) and per-device metrics. * \param calls Function calls and associated metrics. * \param device_metrics Per-device metrics for overall execution. */ explicit Report(Array<Map<String, ObjectRef>> calls, Map<String, Map<String, ObjectRef>> device_metrics); /*! Deserialize a Report from a JSON object. Needed for sending the report over RPC. * \param json Serialized json report from `ReportNode::AsJSON`. * \returns A Report. */ static Report FromJSON(String json); TVM_DEFINE_NOTNULLABLE_OBJECT_REF_METHODS(Report, ObjectRef, ReportNode); }; /*! \brief Interface for user defined profiling metric collection. * * Users can register their own collector by registering a packed function with * the name "runtime.profiling.metrics.my_collector_name" where * "my_collector_name" is the name of their collector. This function should * take an Array of Device as input which contains the devices the collector * will be run on. * * `MetricCollectorNode`s will be called in the following fashion. * \code * MetricCollector mc; * for (auto op : model) { * auto o = mc.Start(); * op(); * auto metrics = mc.Stop(o); // metrics are added the profiling report * } * \endcode */ class MetricCollectorNode : public Object { public: /*! \brief Initialization call. Called before profiling has started. Any * expensive precomputation should happen here. * \param devs The list of devices this collector will be run on. */ virtual void Init(Array<DeviceWrapper> devs) = 0; /*! \brief Start colling metrics for a function call. * \param dev The device the call will be run on. * \returns An object used to maintain state of the metric collection. This * object will be passed to the corresponding `Stop` call. If the device is * not supported, this function will return a nullptr ObjectRef. */ virtual ObjectRef Start(Device dev) = 0; /*! \brief Stop collecting metrics. * \param obj The object created by the corresponding `Start` call. * \returns A set of metric names and the associated values. Values must be * one of DurationNode, PercentNode, CountNode, or StringObj. */ virtual Map<String, ObjectRef> Stop(ObjectRef obj) = 0; virtual ~MetricCollectorNode() {} static constexpr const char* _type_key = "runtime.profiling.MetricCollector"; TVM_DECLARE_BASE_OBJECT_INFO(MetricCollectorNode, Object); }; /*! \brief Wrapper for `MetricCollectorNode`. */ class MetricCollector : public ObjectRef { public: TVM_DEFINE_MUTABLE_OBJECT_REF_METHODS(MetricCollector, ObjectRef, MetricCollectorNode); }; /*! Information about a single function or operator call. */ struct CallFrame { /*! Device on which the call was made */ Device dev; /*! Name of the function or op */ String name; /*! Runtime of the function or op */ Timer timer; /*! Extra performance metrics */ std::unordered_map<std::string, ObjectRef> extra_metrics; /*! User defined metric collectors. Each pair is the MetricCollector and its * associated data (returned from MetricCollector.Start). */ std::vector<std::pair<MetricCollector, ObjectRef>> extra_collectors; }; /*! Runtime profiler for function and/or operator calls. Used in the graph * runtime and VM to provide profiling information for all operators. * * Example usage: * \code{.cpp} * Device cpu, gpu; * Profiler prof({cpu, gpu}); * my_gpu_kernel(); // do a warmup iteration * prof.Start(); * prof.StartCall("my_gpu_kernel", gpu); * my_gpu_kernel(); * prof.StopCall(); * prof.StartCall("my_cpu_function", cpu); * my_cpu_function(); * prof.StopCall(); * prof.Stop(); * std::cout << prof.Report << std::endl; // print profiling report * \endcode */ class Profiler { public: /*! Constructor. * * The profiler should be constructed before you do any warmup iterations. * * \note * Calling this constructor will reset the TVM threadpool. It is necessary in * order to install thread handlers required by certain collectors. * * \param devs The list of devices the profiler will be running on. Should * include all devices used by profiled operators. * \param metric_collectors Additional `MetricCollector`s to use with this profiler. */ explicit Profiler(std::vector<Device> devs, std::vector<MetricCollector> metric_collectors); /*! \brief Start the profiler. * * This function should only be called once per object. */ void Start(); /*! \brief Stop the profiler. * * This function should only be called once per object after start has been called. */ void Stop(); /*! \brief Start a function call. * \param name The name of the function being called. * \param dev The device on which the function is running. * \param extra_metrics Optional additional profiling information to add to * the frame (input sizes, allocations). * * `StartCall` may be nested, but each `StartCall` needs a matching * `StopCall`. Function calls are stopped in LIFO order, so calls to * `StartCall` and `StopCall` must be nested properly. */ void StartCall(String name, Device dev, std::unordered_map<std::string, ObjectRef> extra_metrics = {}); /*! \brief Stop the last `StartCall`. * \param extra_metrics Optional additional profiling information to add to * the frame (input sizes, allocations). */ void StopCall(std::unordered_map<std::string, ObjectRef> extra_metrics = {}); /*! \brief A report of total runtime between `Start` and `Stop` as * well as individual statistics for each `StartCall`-`StopCall` pair. * \returns A `Report` that can either be formatted as CSV (with `.AsCSV`) * or as a human readable table (with `.AsTable`). */ profiling::Report Report(bool aggregate = true, bool sort = true); /*! \brief Check if the profiler is currently running. * \returns Whether or not the profiler is running. */ bool IsRunning() const { return is_running_; } private: std::vector<Device> devs_; bool is_running_{false}; std::vector<CallFrame> calls_; std::stack<CallFrame> in_flight_; std::vector<MetricCollector> collectors_; }; /* \brief A duration in time. */ class DurationNode : public Object { public: /* The duration as a floating point number of microseconds. */ double microseconds; /* \brief Construct a new duration. * \param a The duration in microseconds. */ explicit DurationNode(double a) : microseconds(a) {} static constexpr const char* _type_key = "runtime.profiling.Duration"; TVM_DECLARE_FINAL_OBJECT_INFO(DurationNode, Object); }; /* A percentage of something */ class PercentNode : public Object { public: /* The percent as a floating point value out of 100%. i.e. if `percent` is 10 then we have 10%. */ double percent; /* \brief Construct a new percentage. * \param a The percentage out of 100. */ explicit PercentNode(double a) : percent(a) {} static constexpr const char* _type_key = "runtime.profiling.Percent"; TVM_DECLARE_FINAL_OBJECT_INFO(PercentNode, Object); }; /* A count of something */ class CountNode : public Object { public: /* The actual count */ int64_t value; /* \brief Construct a new count. * \param a The count. */ explicit CountNode(int64_t a) : value(a) {} static constexpr const char* _type_key = "runtime.profiling.Count"; TVM_DECLARE_FINAL_OBJECT_INFO(CountNode, Object); }; /*! \brief String representation of an array of NDArray shapes * \param shapes Array of NDArrays to get the shapes of. * \return A textual representation of the shapes. For example: `float32[2], int64[1, 2]`. */ String ShapeString(const std::vector<NDArray>& shapes); /*! \brief String representation of shape encoded as an NDArray * \param shape NDArray containing the shape. * \param dtype The dtype of the shape. * \return A textual representation of the shape. For example: `float32[2]`. */ String ShapeString(NDArray shape, DLDataType dtype); /*! \brief String representation of a shape encoded as a vector * \param shape Shape as a vector of integers. * \param dtype The dtype of the shape. * \return A textual representation of the shape. For example: `float32[2]`. */ String ShapeString(const std::vector<int64_t>& shape, DLDataType dtype); } // namespace profiling } // namespace runtime } // namespace tvm #endif // TVM_RUNTIME_PROFILING_H_
35.16701
100
0.693304
[ "object", "shape", "vector", "model" ]
367092f069345ecce20dcca413329400a663b98d
259
h
C
test/pch_test.h
KUDB/MSDB
19e89d1d9c09c57b242737f0634ac30b4c8ecfd7
[ "MIT" ]
2
2021-08-31T12:43:16.000Z
2021-12-13T13:49:19.000Z
test/pch_test.h
KUDB/MSDB
19e89d1d9c09c57b242737f0634ac30b4c8ecfd7
[ "MIT" ]
3
2021-09-09T17:23:31.000Z
2021-09-09T19:14:50.000Z
test/pch_test.h
KUDB/MSDB
19e89d1d9c09c57b242737f0634ac30b4c8ecfd7
[ "MIT" ]
null
null
null
// // pch.h // Header for standard system include files. // #pragma once #include <iostream> #include <vector> #include <map> #include <list> #include <bitset> #include <memory> #include <tuple> #include <string> #include <cstdlib> #include "gtest/gtest.h"
14.388889
44
0.698842
[ "vector" ]
3671930966437bf4fc1b505530a0c94df0163473
17,611
c
C
src/pluginscript.c
himetori/godot-ruby
8072844a24b6c178e06248d613ab68e78a28b3da
[ "MIT" ]
15
2018-06-04T22:10:21.000Z
2020-02-14T07:44:33.000Z
src/pluginscript.c
himetori/godot-ruby
8072844a24b6c178e06248d613ab68e78a28b3da
[ "MIT" ]
3
2018-06-01T04:00:34.000Z
2019-12-01T16:46:12.000Z
src/pluginscript.c
onyxblade/godot-ruby
8072844a24b6c178e06248d613ab68e78a28b3da
[ "MIT" ]
3
2020-11-12T13:23:13.000Z
2022-02-02T14:34:01.000Z
#include <pthread.h> const godot_gdnative_core_api_struct *api = NULL; const godot_gdnative_ext_pluginscript_api_struct *pluginscript_api = NULL; static const char *RUBY_RECOGNIZED_EXTENSIONS[] = { "rb", 0 }; static const char *RUBY_RESERVED_WORDS[] = { "__ENCODING__", "__LINE__", "__FILE__", "BEGIN", "END", "alias", "and", "begin", "break", "case", "class", "def", "defined?", "do", "else", "elsif", "end", "ensure", "false", "for", "if", "in", "module", "next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield", 0 }; static const char *RUBY_COMMENT_DELIMITERS[] = { "#", 0 }; static const char *RUBY_STRING_DELIMITERS[] = { "\" \"", "' '", 0 }; static godot_pluginscript_language_desc desc; static VALUE rb_mGodot; static pthread_t ruby_thread_id; typedef struct { VALUE klass; } godot_ruby_pluginscript_script_data; typedef struct { VALUE object; godot_object *owner; } godot_ruby_pluginscript_instance_data; godot_string godot_ruby_get_template_source_code(godot_pluginscript_language_data *p_data, const godot_string *p_class_name, const godot_string *p_base_class_name) { // p_class_name is the filename VALUE template = rb_funcall(rb_mGodot, rb_intern("_template_source_code"), 1, rb_godot_string_pointer_from_godot(p_base_class_name)); godot_string ret; api->godot_string_new_copy(&ret, rb_godot_string_pointer_to_godot(template)); printf("get_template_source_code\n"); return ret; } void godot_ruby_add_global_constant(godot_pluginscript_language_data *p_data, const godot_string *p_variable, const godot_variant *p_value) { printf("add_global_constant\n"); } VALUE rb_godot_object_call(VALUE self, VALUE method_name, VALUE method_args) { godot_object *pointer = rb_godot_object_pointer_to_godot(self); godot_variant gv_args = rb_godot_variant_to_godot(method_args); godot_variant gv_name = rb_godot_variant_to_godot(method_name); godot_variant_call_error p_error; godot_method_bind *method_bind = api->godot_method_bind_get_method("Object", "callv"); const godot_variant *c_args[] = { &gv_name, &gv_args }; godot_variant ret = api->godot_method_bind_call(method_bind, pointer, c_args, 2, &p_error); // printf("call error %d", p_error.error); return rb_godot_variant_from_godot(ret); } VALUE rb_godot_get_global_singleton (VALUE self, VALUE name) { godot_object* klass = api->godot_global_get_singleton(StringValueCStr(name)); if (klass) { return rb_godot_object_pointer_from_godot(klass); } else { return Qnil; } } VALUE rb_godot_print (VALUE self, VALUE string) { api->godot_print(rb_godot_string_pointer_to_godot(string)); return Qtrue; } VALUE rb_godot_print_error (VALUE self, VALUE exception) { VALUE message = rb_funcall(exception, rb_intern("message"), 0); VALUE backtrace = rb_funcall(rb_funcall(exception, rb_intern("backtrace"), 0), rb_intern("to_s"), 0); api->godot_print_error(StringValueCStr(message), StringValueCStr(backtrace), "ruby", 0); return Qtrue; } godot_pluginscript_language_data *godot_ruby_init() { printf("godot_ruby_init\n"); ruby_init(); ruby_script("godot"); ruby_init_loadpath(); // VALUE load_path = rb_gv_get("$LOAD_PATH"); // rb_funcall(load_path, rb_intern("unshift"), 1, rb_str_new_cstr("/home/cichol/godot-ruby/lib")); rb_eval_string(RUBY_CODE); rb_mGodot = rb_const_get(rb_cModule, rb_intern("Godot")); VALUE object_module = rb_const_get(rb_mGodot, rb_intern("Object")); rb_define_method(object_module, "_call", &rb_godot_object_call, 2); rb_define_singleton_method(rb_mGodot, "_get_singleton", &rb_godot_get_global_singleton, 1); rb_define_singleton_method(rb_mGodot, "_print", &rb_godot_print, 1); rb_define_singleton_method(rb_mGodot, "_print_error", &rb_godot_print_error, 1); init(); godot_dictionary constant_dict = api->godot_get_global_constants(); rb_iv_set(rb_mGodot, "@_godot_constants", rb_godot_dictionary_from_godot(constant_dict)); rb_funcall(rb_mGodot, rb_intern("_initialize"), 0); ruby_thread_id = pthread_self(); return NULL; } void godot_ruby_finish(godot_pluginscript_language_data *p_data) { printf("ruby_finish\n"); ruby_cleanup(0); } godot_pluginscript_script_manifest godot_ruby_script_init(godot_pluginscript_language_data *p_data, const godot_string *p_path, const godot_string *p_source, godot_error *r_error) { godot_pluginscript_script_manifest manifest; if (ruby_thread_id != pthread_self()) { printf("script_init called from another thread\n"); *r_error = GODOT_ERR_LOCKED; return manifest; } VALUE r_path = rb_godot_string_pointer_from_godot(p_path); VALUE r_source = rb_godot_string_pointer_from_godot(p_source); VALUE klass = rb_funcall(rb_mGodot, rb_intern("_register_class"), 2, rb_funcall(r_path, rb_intern("to_s"), 0), rb_funcall(r_source, rb_intern("to_s"), 0)); godot_ruby_pluginscript_script_data *data; data = (godot_ruby_pluginscript_script_data*)api->godot_alloc(sizeof(godot_ruby_pluginscript_script_data)); data->klass = klass; VALUE script_manifest = rb_funcall(rb_mGodot, rb_intern("_script_manifest"), 1, klass); godot_string_name name; api->godot_string_name_new(&name, rb_godot_string_pointer_to_godot(RARRAY_AREF(script_manifest, 0))); godot_int is_tool = rb_godot_int_to_godot(RARRAY_AREF(script_manifest, 1)); godot_string_name base; api->godot_string_name_new(&base, rb_godot_string_pointer_to_godot(RARRAY_AREF(script_manifest, 2))); godot_dictionary member_lines; api->godot_dictionary_new_copy(&member_lines, rb_godot_dictionary_pointer_to_godot(RARRAY_AREF(script_manifest, 3))); godot_array methods; api->godot_array_new_copy(&methods, rb_godot_array_pointer_to_godot(RARRAY_AREF(script_manifest, 4))); godot_array signals; api->godot_array_new_copy(&signals, rb_godot_array_pointer_to_godot(RARRAY_AREF(script_manifest, 5))); godot_array properties; api->godot_array_new_copy(&properties, rb_godot_array_pointer_to_godot(RARRAY_AREF(script_manifest, 6))); manifest.data = (godot_pluginscript_script_data*) data; manifest.name = name; manifest.is_tool = is_tool; manifest.base = base; manifest.member_lines = member_lines; manifest.methods = methods; manifest.signals = signals; manifest.properties = properties; *r_error = GODOT_OK; printf("ruby_script_init\n"); return manifest; } void godot_ruby_script_finish(godot_pluginscript_script_data *p_data) { godot_ruby_pluginscript_script_data *data = (godot_ruby_pluginscript_script_data*) p_data; api->godot_free(p_data); if (ruby_thread_id != pthread_self()) { printf("script_init called from another thread\n"); return; } rb_funcall(rb_mGodot, rb_intern("_unregister_class"), 1, data->klass); printf("script_finish\n"); } godot_pluginscript_instance_data *godot_ruby_instance_init(godot_pluginscript_script_data *p_data, godot_object *p_owner) { godot_ruby_pluginscript_script_data *script_data = (godot_ruby_pluginscript_script_data*) p_data; godot_ruby_pluginscript_instance_data *data; data = (godot_ruby_pluginscript_instance_data*)api->godot_alloc(sizeof(godot_ruby_pluginscript_instance_data)); VALUE instance = rb_funcall(script_data->klass, rb_intern("new"), 0); data->object = instance; data->owner = p_owner; rb_iv_set(instance, "@_godot_address", LONG2NUM((long)p_owner)); printf("ruby_instance_init\n"); return (godot_pluginscript_instance_data*)data; } void godot_ruby_instance_finish(godot_pluginscript_instance_data *p_data) { godot_ruby_pluginscript_instance_data *data = (godot_ruby_pluginscript_instance_data *) p_data; rb_funcall(rb_mGodot, rb_intern("_unregister_object"), 1, data->object); api->godot_free(p_data); printf("instance_finish\n"); } godot_bool godot_ruby_instance_set_prop(godot_pluginscript_instance_data *p_data, const godot_string *p_name, const godot_variant *p_value) { godot_ruby_pluginscript_instance_data *data = (godot_ruby_pluginscript_instance_data*) p_data; printf("instance_set_prop\n"); VALUE method_name = rb_funcall(rb_funcall(rb_godot_string_pointer_from_godot(p_name), rb_intern("to_s"), 0), rb_intern("concat"), 1, rb_str_new_cstr("=")); if (RTEST(rb_funcall(data->object, rb_intern("respond_to?"), 1, method_name))) { rb_funcall(data->object, rb_intern_str(method_name), 1, rb_godot_variant_from_godot(*p_value)); return 1; } else { return 0; } } godot_bool godot_ruby_instance_get_prop(godot_pluginscript_instance_data *p_data, const godot_string *p_name, godot_variant *r_ret) { godot_ruby_pluginscript_instance_data *data = (godot_ruby_pluginscript_instance_data*) p_data; printf("instance_get_prop\n"); VALUE method_name = rb_funcall(rb_godot_string_pointer_from_godot(p_name), rb_intern("to_s"), 0); if (RTEST(rb_funcall(data->object, rb_intern("respond_to?"), 1, method_name))) { godot_variant var; VALUE ret = rb_funcall(data->object, rb_intern_str(method_name), 0); var = rb_godot_variant_to_godot(ret); memcpy(r_ret, &var, sizeof(godot_variant)); return 1; } else { return 0; } } godot_variant godot_ruby_instance_call_method(godot_pluginscript_instance_data *p_data, const godot_string_name *p_method, const godot_variant **p_args, int p_argcount, godot_variant_call_error *r_error) { printf("instance_call_method\n"); godot_ruby_pluginscript_instance_data *data = (godot_ruby_pluginscript_instance_data*) p_data; godot_string method_name = api->godot_string_name_get_name(p_method); VALUE method_name_str = rb_funcall(rb_godot_string_pointer_from_godot(&method_name), rb_intern("to_s"), 0); VALUE respond_to = rb_funcall(data->object, rb_intern("respond_to?"), 1, rb_funcall(method_name_str, rb_intern("to_s"), 0)); godot_variant var; if (RTEST(respond_to)) { VALUE arguments[p_argcount+2]; arguments[0] = data->object; arguments[1] = method_name_str; for (int i=0; i < p_argcount; ++i) { arguments[i + 2] = rb_godot_variant_from_godot(*p_args[i]); } VALUE ret = rb_funcallv(rb_mGodot, rb_intern("call_method"), p_argcount + 2, arguments); var = rb_godot_variant_to_godot(ret); } else { VALUE klass = rb_funcall(data->object, rb_intern("class"), 0); VALUE base_name = rb_iv_get(klass, "@_base_name"); godot_method_bind *method; wchar_t *wchars = api->godot_string_wide_str(&method_name); { int len = api->godot_string_length(&method_name); char chars[len+1]; wcstombs(chars, wchars, len + 1); method = api->godot_method_bind_get_method(StringValueCStr(base_name), chars); if (method) { var = api->godot_method_bind_call(method, data->owner, p_args, p_argcount, r_error); } else { api->godot_variant_new_nil(&var); r_error->error = GODOT_CALL_ERROR_CALL_ERROR_INVALID_METHOD; } } } api->godot_string_destroy(&method_name); return var; } void godot_ruby_instance_notification(godot_pluginscript_instance_data *p_data, int p_notification) { printf("instance_notification\n"); } godot_bool godot_ruby_validate(godot_pluginscript_language_data *p_data, const godot_string *p_script, int *r_line_error, int *r_col_error, godot_string *r_test_error, const godot_string *p_path, godot_pool_string_array *r_functions) { printf("validate\n"); } int godot_ruby_find_function(godot_pluginscript_language_data *p_data, const godot_string *p_function, const godot_string *p_code) { printf("find_function\n"); } godot_string godot_ruby_make_function(godot_pluginscript_language_data *p_data, const godot_string *p_class, const godot_string *p_name, const godot_pool_string_array *p_args) { printf("make_function\n"); } godot_error godot_ruby_complete_code(godot_pluginscript_language_data *p_data, const godot_string *p_code, const godot_string *p_base_path, godot_object *p_owner, godot_array *r_options, godot_bool *r_force, godot_string *r_call_hint) { printf("complete_code\n"); } void godot_ruby_auto_indent_code(godot_pluginscript_language_data *p_data, godot_string *p_code, int p_from_line, int p_to_line) { printf("auto_indent_code\n"); } godot_string godot_ruby_debug_get_error(godot_pluginscript_language_data *p_data) { printf("debug_get_error\n"); } int godot_ruby_debug_get_stack_level_count(godot_pluginscript_language_data *p_data) { printf("debug_get_stack_level_count\n"); } int godot_ruby_debug_get_stack_level_line(godot_pluginscript_language_data *p_data, int p_level) { printf("debug_get_stack_level_line\n"); } godot_string godot_ruby_debug_get_stack_level_function(godot_pluginscript_language_data *p_data, int p_level) { printf("debug_get_stack_level_function\n"); } godot_string godot_ruby_debug_get_stack_level_source(godot_pluginscript_language_data *p_data, int p_level) { printf("debug_get_stack_level_source\n"); } void godot_ruby_debug_get_stack_level_locals(godot_pluginscript_language_data *p_data, int p_level, godot_pool_string_array *p_locals, godot_array *p_values, int p_max_subitems, int p_max_depth) { printf("debug_get_stack_level_locals\n"); } void godot_ruby_debug_get_stack_level_members(godot_pluginscript_language_data *p_data, int p_level, godot_pool_string_array *p_members, godot_array *p_values, int p_max_subitems, int p_max_depth) { printf("debug_get_stack_level_members\n"); } void godot_ruby_debug_get_globals(godot_pluginscript_language_data *p_data, godot_pool_string_array *p_locals, godot_array *p_values, int p_max_subitems, int p_max_depth) { printf("debug_get_globals\n"); } godot_string godot_ruby_debug_parse_stack_level_expression(godot_pluginscript_language_data *p_data, int p_level, const godot_string *p_expression, int p_max_subitems, int p_max_depth) { printf("debug_parse_stack_level_expression\n"); } void godot_ruby_profiling_start(godot_pluginscript_language_data *p_data) { printf("profiling_start\n"); } void godot_ruby_profiling_stop(godot_pluginscript_language_data *p_data) { printf("profiling_stop\n"); } int godot_ruby_profiling_get_accumulated_data(godot_pluginscript_language_data *p_data, godot_pluginscript_profiling_data *r_info, int p_info_max) { printf("godot_ruby_profiling_get_accumulated_data\n"); } int godot_ruby_profiling_get_frame_data(godot_pluginscript_language_data *p_data, godot_pluginscript_profiling_data *r_info, int p_info_max) { printf("godot_ruby_profiling_get_frame_data\n"); } void godot_ruby_profiling_frame(godot_pluginscript_language_data *p_data) { printf("profiling_frame\n"); } void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *p_options) { printf("gdnative init\n"); api = p_options->api_struct; // now find our extensions for (int i = 0; i < api->num_extensions; i++) { switch (api->extensions[i]->type) { case GDNATIVE_EXT_PLUGINSCRIPT: pluginscript_api = (godot_gdnative_ext_pluginscript_api_struct *)api->extensions[i]; break; default: break; }; }; desc.name = "Ruby"; desc.type = "Ruby"; desc.extension = "rb"; desc.recognized_extensions = RUBY_RECOGNIZED_EXTENSIONS; desc.init = &godot_ruby_init; desc.finish = &godot_ruby_finish; desc.reserved_words = RUBY_RESERVED_WORDS; desc.comment_delimiters = RUBY_COMMENT_DELIMITERS; desc.string_delimiters = RUBY_STRING_DELIMITERS; desc.has_named_classes = false; desc.get_template_source_code = &godot_ruby_get_template_source_code; desc.add_global_constant = &godot_ruby_add_global_constant; desc.script_desc.init = &godot_ruby_script_init; desc.script_desc.finish = &godot_ruby_script_finish; desc.script_desc.instance_desc.init = &godot_ruby_instance_init; desc.script_desc.instance_desc.finish = &godot_ruby_instance_finish; desc.script_desc.instance_desc.set_prop = &godot_ruby_instance_set_prop; desc.script_desc.instance_desc.get_prop = &godot_ruby_instance_get_prop; desc.script_desc.instance_desc.call_method = &godot_ruby_instance_call_method; desc.script_desc.instance_desc.notification = &godot_ruby_instance_notification; desc.script_desc.instance_desc.refcount_incremented = NULL; desc.script_desc.instance_desc.refcount_decremented = NULL; if (p_options->in_editor) { desc.get_template_source_code = &godot_ruby_get_template_source_code; /* desc.validate = &godot_ruby_validate; desc.find_function = &godot_ruby_find_function; desc.make_function = &godot_ruby_make_function; desc.complete_code = &godot_ruby_complete_code; desc.auto_indent_code = &godot_ruby_auto_indent_code; desc.debug_get_error = &godot_ruby_debug_get_error; desc.debug_get_stack_level_count = &godot_ruby_debug_get_stack_level_count; desc.debug_get_stack_level_line = &godot_ruby_debug_get_stack_level_line; desc.debug_get_stack_level_function = &godot_ruby_debug_get_stack_level_function; desc.debug_get_stack_level_source = &godot_ruby_debug_get_stack_level_source; desc.debug_get_stack_level_locals = &godot_ruby_debug_get_stack_level_locals; desc.debug_get_stack_level_members = &godot_ruby_debug_get_stack_level_members; desc.debug_get_globals = &godot_ruby_debug_get_globals; desc.debug_parse_stack_level_expression = &godot_ruby_debug_parse_stack_level_expression; desc.profiling_start = &godot_ruby_profiling_start; desc.profiling_stop = &godot_ruby_profiling_stop; desc.profiling_get_accumulated_data = &godot_ruby_profiling_get_accumulated_data; desc.profiling_get_frame_data = &godot_ruby_profiling_get_frame_data; desc.profiling_frame = &godot_ruby_profiling_frame; */ } pluginscript_api->godot_pluginscript_register_language(&desc); printf("registered language\n"); } void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *p_options) { printf("gdnative_terminate\n"); api = NULL; pluginscript_api = NULL; } void GDN_EXPORT godot_gdnative_singleton() { }
38.536105
236
0.800011
[ "object" ]
36745c8178e09c96f4727a914a5975e592850978
13,434
c
C
third_party/sqlalchemy_0_7_1/sqlalchemy/cextension/processors.c
bopopescu/build
4e95fd33456e552bfaf7d94f7d04b19273d1c534
[ "BSD-3-Clause" ]
null
null
null
third_party/sqlalchemy_0_7_1/sqlalchemy/cextension/processors.c
bopopescu/build
4e95fd33456e552bfaf7d94f7d04b19273d1c534
[ "BSD-3-Clause" ]
null
null
null
third_party/sqlalchemy_0_7_1/sqlalchemy/cextension/processors.c
bopopescu/build
4e95fd33456e552bfaf7d94f7d04b19273d1c534
[ "BSD-3-Clause" ]
1
2020-07-23T11:05:06.000Z
2020-07-23T11:05:06.000Z
/* processors.c Copyright (C) 2010 Gaetan de Menten gdementen@gmail.com This module is part of SQLAlchemy and is released under the MIT License: http://www.opensource.org/licenses/mit-license.php */ #include <Python.h> #include <datetime.h> #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #endif static PyObject * int_to_boolean(PyObject *self, PyObject *arg) { long l = 0; PyObject *res; if (arg == Py_None) Py_RETURN_NONE; l = PyInt_AsLong(arg); if (l == 0) { res = Py_False; } else if (l == 1) { res = Py_True; } else if ((l == -1) && PyErr_Occurred()) { /* -1 can be either the actual value, or an error flag. */ return NULL; } else { PyErr_SetString(PyExc_ValueError, "int_to_boolean only accepts None, 0 or 1"); return NULL; } Py_INCREF(res); return res; } static PyObject * to_str(PyObject *self, PyObject *arg) { if (arg == Py_None) Py_RETURN_NONE; return PyObject_Str(arg); } static PyObject * to_float(PyObject *self, PyObject *arg) { if (arg == Py_None) Py_RETURN_NONE; return PyNumber_Float(arg); } static PyObject * str_to_datetime(PyObject *self, PyObject *arg) { const char *str; unsigned int year, month, day, hour, minute, second, microsecond = 0; if (arg == Py_None) Py_RETURN_NONE; str = PyString_AsString(arg); if (str == NULL) return NULL; /* microseconds are optional */ /* TODO: this is slightly less picky than the Python version which would not accept "2000-01-01 00:00:00.". I don't know which is better, but they should be coherent. */ if (sscanf(str, "%4u-%2u-%2u %2u:%2u:%2u.%6u", &year, &month, &day, &hour, &minute, &second, &microsecond) < 6) { PyErr_SetString(PyExc_ValueError, "Couldn't parse datetime string."); return NULL; } return PyDateTime_FromDateAndTime(year, month, day, hour, minute, second, microsecond); } static PyObject * str_to_time(PyObject *self, PyObject *arg) { const char *str; unsigned int hour, minute, second, microsecond = 0; if (arg == Py_None) Py_RETURN_NONE; str = PyString_AsString(arg); if (str == NULL) return NULL; /* microseconds are optional */ /* TODO: this is slightly less picky than the Python version which would not accept "00:00:00.". I don't know which is better, but they should be coherent. */ if (sscanf(str, "%2u:%2u:%2u.%6u", &hour, &minute, &second, &microsecond) < 3) { PyErr_SetString(PyExc_ValueError, "Couldn't parse time string."); return NULL; } return PyTime_FromTime(hour, minute, second, microsecond); } static PyObject * str_to_date(PyObject *self, PyObject *arg) { const char *str; unsigned int year, month, day; if (arg == Py_None) Py_RETURN_NONE; str = PyString_AsString(arg); if (str == NULL) return NULL; if (sscanf(str, "%4u-%2u-%2u", &year, &month, &day) != 3) { PyErr_SetString(PyExc_ValueError, "Couldn't parse date string."); return NULL; } return PyDate_FromDate(year, month, day); } /*********** * Structs * ***********/ typedef struct { PyObject_HEAD PyObject *encoding; PyObject *errors; } UnicodeResultProcessor; typedef struct { PyObject_HEAD PyObject *type; PyObject *format; } DecimalResultProcessor; /************************** * UnicodeResultProcessor * **************************/ static int UnicodeResultProcessor_init(UnicodeResultProcessor *self, PyObject *args, PyObject *kwds) { PyObject *encoding, *errors = NULL; static char *kwlist[] = {"encoding", "errors", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "S|S:__init__", kwlist, &encoding, &errors)) return -1; Py_INCREF(encoding); self->encoding = encoding; if (errors) { Py_INCREF(errors); } else { errors = PyString_FromString("strict"); if (errors == NULL) return -1; } self->errors = errors; return 0; } static PyObject * UnicodeResultProcessor_process(UnicodeResultProcessor *self, PyObject *value) { const char *encoding, *errors; char *str; Py_ssize_t len; if (value == Py_None) Py_RETURN_NONE; if (PyString_AsStringAndSize(value, &str, &len)) return NULL; encoding = PyString_AS_STRING(self->encoding); errors = PyString_AS_STRING(self->errors); return PyUnicode_Decode(str, len, encoding, errors); } static void UnicodeResultProcessor_dealloc(UnicodeResultProcessor *self) { Py_XDECREF(self->encoding); Py_XDECREF(self->errors); self->ob_type->tp_free((PyObject*)self); } static PyMethodDef UnicodeResultProcessor_methods[] = { {"process", (PyCFunction)UnicodeResultProcessor_process, METH_O, "The value processor itself."}, {NULL} /* Sentinel */ }; static PyTypeObject UnicodeResultProcessorType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "sqlalchemy.cprocessors.UnicodeResultProcessor", /* tp_name */ sizeof(UnicodeResultProcessor), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)UnicodeResultProcessor_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "UnicodeResultProcessor objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ UnicodeResultProcessor_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)UnicodeResultProcessor_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; /************************** * DecimalResultProcessor * **************************/ static int DecimalResultProcessor_init(DecimalResultProcessor *self, PyObject *args, PyObject *kwds) { PyObject *type, *format; if (!PyArg_ParseTuple(args, "OS", &type, &format)) return -1; Py_INCREF(type); self->type = type; Py_INCREF(format); self->format = format; return 0; } static PyObject * DecimalResultProcessor_process(DecimalResultProcessor *self, PyObject *value) { PyObject *str, *result, *args; if (value == Py_None) Py_RETURN_NONE; if (PyFloat_CheckExact(value)) { /* Decimal does not accept float values directly */ args = PyTuple_Pack(1, value); if (args == NULL) return NULL; str = PyString_Format(self->format, args); Py_DECREF(args); if (str == NULL) return NULL; result = PyObject_CallFunctionObjArgs(self->type, str, NULL); Py_DECREF(str); return result; } else { return PyObject_CallFunctionObjArgs(self->type, value, NULL); } } static void DecimalResultProcessor_dealloc(DecimalResultProcessor *self) { Py_XDECREF(self->type); Py_XDECREF(self->format); self->ob_type->tp_free((PyObject*)self); } static PyMethodDef DecimalResultProcessor_methods[] = { {"process", (PyCFunction)DecimalResultProcessor_process, METH_O, "The value processor itself."}, {NULL} /* Sentinel */ }; static PyTypeObject DecimalResultProcessorType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "sqlalchemy.DecimalResultProcessor", /* tp_name */ sizeof(DecimalResultProcessor), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)DecimalResultProcessor_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "DecimalResultProcessor objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ DecimalResultProcessor_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)DecimalResultProcessor_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif static PyMethodDef module_methods[] = { {"int_to_boolean", int_to_boolean, METH_O, "Convert an integer to a boolean."}, {"to_str", to_str, METH_O, "Convert any value to its string representation."}, {"to_float", to_float, METH_O, "Convert any value to its floating point representation."}, {"str_to_datetime", str_to_datetime, METH_O, "Convert an ISO string to a datetime.datetime object."}, {"str_to_time", str_to_time, METH_O, "Convert an ISO string to a datetime.time object."}, {"str_to_date", str_to_date, METH_O, "Convert an ISO string to a datetime.date object."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initcprocessors(void) { PyObject *m; UnicodeResultProcessorType.tp_new = PyType_GenericNew; if (PyType_Ready(&UnicodeResultProcessorType) < 0) return; DecimalResultProcessorType.tp_new = PyType_GenericNew; if (PyType_Ready(&DecimalResultProcessorType) < 0) return; m = Py_InitModule3("cprocessors", module_methods, "Module containing C versions of data processing functions."); if (m == NULL) return; PyDateTime_IMPORT; Py_INCREF(&UnicodeResultProcessorType); PyModule_AddObject(m, "UnicodeResultProcessor", (PyObject *)&UnicodeResultProcessorType); Py_INCREF(&DecimalResultProcessorType); PyModule_AddObject(m, "DecimalResultProcessor", (PyObject *)&DecimalResultProcessorType); }
32.138756
85
0.495013
[ "object" ]
3676e125f15c88bcf002aeb38069e944e38c26ed
3,256
h
C
aws-cpp-sdk-codepipeline/include/aws/codepipeline/model/ArtifactLocation.h
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-codepipeline/include/aws/codepipeline/model/ArtifactLocation.h
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-codepipeline/include/aws/codepipeline/model/ArtifactLocation.h
ambasta/aws-sdk-cpp
c81192e00b572b76d175d84dff77185bd17ae1ac
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/codepipeline/CodePipeline_EXPORTS.h> #include <aws/codepipeline/model/ArtifactLocationType.h> #include <aws/codepipeline/model/S3ArtifactLocation.h> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace CodePipeline { namespace Model { /** * <p>Represents information about the location of an artifact.</p> */ class AWS_CODEPIPELINE_API ArtifactLocation { public: ArtifactLocation(); ArtifactLocation(const Aws::Utils::Json::JsonValue& jsonValue); ArtifactLocation& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The type of artifact in the location.</p> */ inline const ArtifactLocationType& GetType() const{ return m_type; } /** * <p>The type of artifact in the location.</p> */ inline void SetType(const ArtifactLocationType& value) { m_typeHasBeenSet = true; m_type = value; } /** * <p>The type of artifact in the location.</p> */ inline void SetType(ArtifactLocationType&& value) { m_typeHasBeenSet = true; m_type = value; } /** * <p>The type of artifact in the location.</p> */ inline ArtifactLocation& WithType(const ArtifactLocationType& value) { SetType(value); return *this;} /** * <p>The type of artifact in the location.</p> */ inline ArtifactLocation& WithType(ArtifactLocationType&& value) { SetType(value); return *this;} /** * <p>The Amazon S3 bucket that contains the artifact.</p> */ inline const S3ArtifactLocation& GetS3Location() const{ return m_s3Location; } /** * <p>The Amazon S3 bucket that contains the artifact.</p> */ inline void SetS3Location(const S3ArtifactLocation& value) { m_s3LocationHasBeenSet = true; m_s3Location = value; } /** * <p>The Amazon S3 bucket that contains the artifact.</p> */ inline void SetS3Location(S3ArtifactLocation&& value) { m_s3LocationHasBeenSet = true; m_s3Location = value; } /** * <p>The Amazon S3 bucket that contains the artifact.</p> */ inline ArtifactLocation& WithS3Location(const S3ArtifactLocation& value) { SetS3Location(value); return *this;} /** * <p>The Amazon S3 bucket that contains the artifact.</p> */ inline ArtifactLocation& WithS3Location(S3ArtifactLocation&& value) { SetS3Location(value); return *this;} private: ArtifactLocationType m_type; bool m_typeHasBeenSet; S3ArtifactLocation m_s3Location; bool m_s3LocationHasBeenSet; }; } // namespace Model } // namespace CodePipeline } // namespace Aws
31.009524
119
0.695946
[ "model" ]
367b12446941e6793ad369790240b607a73b87de
2,165
c
C
Laboratorio4/Problema1.c
CrysRamos/2022LabSimu201901244
67258999f1667ba1608c69010f2941058cd66a4c
[ "MIT" ]
null
null
null
Laboratorio4/Problema1.c
CrysRamos/2022LabSimu201901244
67258999f1667ba1608c69010f2941058cd66a4c
[ "MIT" ]
null
null
null
Laboratorio4/Problema1.c
CrysRamos/2022LabSimu201901244
67258999f1667ba1608c69010f2941058cd66a4c
[ "MIT" ]
null
null
null
/* Autor: anaramos Compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 Compilado: gcc -o Problema1.out Problema1.c Fecha: 05/07/22 Librerías: stdio Resumen: programa que ordena un vector de forma ascendente o descendente, según lo indique el usuario */ //Librerías #include <stdio.h> //prototipo de funciones void imprimira(int datos[]); // funcion para imprimir los datos de forma ascendente void imprimird(int datos[]); // funcion para imprimir los datos de forma descendente int main(){ //declaracion de variables int nums[10]; char op; //inicializacion de vector for (int i = 0; i < 10; i++) { //se llena el vector solo con numeros pares del 2 al 20 nums[i]=2+2*i; } //se muestra al usuario el menú puts("**Menú**"); printf("a Mostrar vector en orden ascendente\nd Mostrar vector en orden descendente\nx salir\n"); //se le solicita al usuario la opción printf("ingrese una opcion: "); //se guarda la opcion solicitada por el usuario en la variable op scanf("%c", &op); //ciclo para que el programa no termine hasta que el usuario ingrese la opcion de salir while (op!='x') { //casos del menu switch (op) { case 'a': puts("vector ascendente"); //se imprime el vector con la funcion ascendente imprimira(nums); //se guarda la opcion solicitada por el usuario en la variable op scanf("%c", &op); break; case 'd': puts("vector descendente"); //se imprime el vector con la funcion descendente imprimird(nums); scanf("%c", &op); break; case 'x': puts("Salida exitosa"); break; default: puts("Ingrese otra opcion"); scanf("%c", &op); break; } } } void imprimira(int datos[]){ for (int i = 0; i < 10; i++) { //se imprimen los datos del vector printf("%d ",datos[i]); } puts("\n"); } void imprimird(int datos[]){ for (int i = 9; i >= 0; i--) { //se imprimen los datos del vector printf("%d ",datos[i]); } puts("\n"); }
27.75641
107
0.587529
[ "vector" ]
367b2c4dab126f5b051821e5b24b08e4bb14a187
1,675
h
C
component/oai-nssf/src/api-server/model/AccessTokenErr.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-nssf/src/api-server/model/AccessTokenErr.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-nssf/src/api-server/model/AccessTokenErr.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/** * NRF OAuth2 * NRF OAuth2 Authorization. © 2019, 3GPP Organizational Partners (ARIB, ATIS, * CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.0.2 * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ /* * AccessTokenErr.h * * */ #ifndef AccessTokenErr_H_ #define AccessTokenErr_H_ #include <nlohmann/json.hpp> #include <string> namespace oai { namespace nssf_server { namespace model { /// <summary> /// /// </summary> class AccessTokenErr { public: AccessTokenErr(); virtual ~AccessTokenErr(); void validate(); ///////////////////////////////////////////// /// AccessTokenErr members /// <summary> /// /// </summary> std::string getError() const; void setError(std::string const& value); /// <summary> /// /// </summary> std::string getErrorDescription() const; void setErrorDescription(std::string const& value); bool errorDescriptionIsSet() const; void unsetError_description(); /// <summary> /// /// </summary> std::string getErrorUri() const; void setErrorUri(std::string const& value); bool errorUriIsSet() const; void unsetError_uri(); friend void to_json(nlohmann::json& j, const AccessTokenErr& o); friend void from_json(const nlohmann::json& j, AccessTokenErr& o); protected: std::string m_Error; std::string m_Error_description; bool m_Error_descriptionIsSet; std::string m_Error_uri; bool m_Error_uriIsSet; }; } // namespace model } // namespace nssf_server } // namespace oai #endif /* AccessTokenErr_H_ */
21.202532
79
0.671045
[ "model" ]
367d109879b3d7fb934af6a8b3970296a01abcaf
1,508
h
C
programs/ziti-edge-tunnel/include/instance.h
openziti/ziti-tunnel-sdk-c
74d99970f9462b5d6136030dc6e40d57802d05b4
[ "Apache-2.0" ]
7
2020-11-21T16:10:45.000Z
2022-03-22T14:30:18.000Z
programs/ziti-edge-tunnel/include/instance.h
openziti/ziti-tunnel-sdk-c
74d99970f9462b5d6136030dc6e40d57802d05b4
[ "Apache-2.0" ]
60
2020-08-27T13:26:20.000Z
2022-03-31T21:56:05.000Z
programs/ziti-edge-tunnel/include/instance.h
openziti/ziti-tunnel-sdk-c
74d99970f9462b5d6136030dc6e40d57802d05b4
[ "Apache-2.0" ]
5
2021-04-05T21:39:10.000Z
2022-01-24T03:18:40.000Z
/* Copyright 2019-2021 NetFoundry Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef ZITI_TUNNEL_SDK_C_INSTANCE_H #define ZITI_TUNNEL_SDK_C_INSTANCE_H #include <ziti/ziti_model.h> #include "model/dtos.h" extern tunnel_identity *find_tunnel_identity(char* identifier); extern tunnel_identity *get_tunnel_identity(char* identifier); extern void set_mfa_status(char* identifier, bool mfa_enabled, bool mfa_needed); extern void update_mfa_time(char* identifier); extern tunnel_service *get_tunnel_service(tunnel_identity* identifier, ziti_service* zs); extern tunnel_service *find_tunnel_service(tunnel_identity* id, char* svc_id); extern void add_or_remove_services_from_tunnel(tunnel_identity *id, tunnel_service_array added_services, tunnel_service_array removed_services); extern tunnel_status *get_tunnel_status(); extern tunnel_identity_array get_tunnel_identities(); extern int get_remaining_timeout(int timeout, int timeout_rem, tunnel_identity *tnl_id); #endif //ZITI_TUNNEL_SDK_C_INSTANCE_H
34.272727
144
0.818966
[ "model" ]
367fd7988d41d1de0cc34a456b15a309343f0dd6
25,565
h
C
include/iftObjectModels.h
marcostx/CurvilinearClipping
ad9df22a8406fc448edb10a89c157e361b9abf8c
[ "MIT" ]
1
2019-03-26T05:54:55.000Z
2019-03-26T05:54:55.000Z
include/iftObjectModels.h
marcostx/CurvilinearClipping
ad9df22a8406fc448edb10a89c157e361b9abf8c
[ "MIT" ]
null
null
null
include/iftObjectModels.h
marcostx/CurvilinearClipping
ad9df22a8406fc448edb10a89c157e361b9abf8c
[ "MIT" ]
1
2019-04-14T09:28:21.000Z
2019-04-14T09:28:21.000Z
/** * @file iftObjectModels.h * @brief Definitions and functions about Object Models. * @author Samuel Martins * @date Jan 01, 2017 * @ingroup ObjectModels */ #ifndef IFT_OBJECTMODELS_H_ #define IFT_OBJECTMODELS_H_ #ifdef __cplusplus extern "C" { #endif #include "iftCommon.h" #include "iftDict.h" #include "iftImage.h" #include "iftParamOptimizationProblems.h" #include "iftFImage.h" #include "iftRadiometric.h" #include "iftRegistration.h" #include "iftSegmentation.h" #include "iftSimilarity.h" /** * Function type to extract the Reference Voxel of the Test Image. * @param test_img Testing Image. * @param params Dictionary of Parameters. Each algorithm must provide (and deallocate after) * its parameters. * @return The Reference Voxel of the Testing Image. */ typedef iftVoxel (*iftRefVoxelFinderFunc)(const iftImage *test_img, const iftDict *params); /** * @brief Flag of the supported Algorithms on libIFT to find the Reference Voxel on Test Image. * @author Samuel Martins * @date Dec 16, 2016 */ typedef enum { IFT_IMAGE_CENTER, IFT_GEO_CENTER_AFTER_THRESHOLDING } iftRefVoxelFinderAlg; /** * @brief Algorithms to find the Reference Voxel on Test Image. * @author Samuel Martins * @date Dec 16, 2016 */ typedef struct ift_ref_voxel_finder { /** Finder algorithm flag */ iftRefVoxelFinderAlg alg; /** Finder function */ iftRefVoxelFinderFunc func; /** Parameters of the finder function */ iftDict *params; } iftRefVoxelFinder; /** * @brief Model of a single Object. * @author Samuka * @date Dec 13, 2016 * @ingroup ObjectModel */ typedef struct ift_obj_model { /** Label of the target Object */ int label; /** Model: Prior Probability Map */ iftFImage *prob_map; /** * Displacement vector from the Reference Voxel (on test image) to the coordinate where the center voxel of the * object model must be positioned (on test image domain). * It used to recognize, at the test image, the object to be segmented, positioning * the center of the model over it */ iftVector disp_vec; // search region for the object localization from the reference voxel iftBoundingBox search_region; } iftObjModel; /** * @brief Multi-Object Model. * @author Samuka * @date Dec 13, 2016 * @ingroup ObjectModel */ typedef struct ift_m_obj_model { /** Depth (in bits) of the images considered by the model */ int img_depth; /** Array of labels of each Object Model */ iftIntArray *labels; /** Array of Object Models. */ iftObjModel **models; /** Pointer to function that computes the Reference Voxel of Images. */ iftRefVoxelFinder *finder; /** Reference Image where the object models were built (if required) and/or for histogram matching when segmenting a testing image. */ iftImage *ref_img; /** Dictionary with specific parameters for each kind of Model: (Statistical, Fuzzy, ...) */ iftDict *extra; } iftMObjModel; /** * @brief Struct for the MAGeT-Brain algorithm. * @author Samuka * @date Jan 13, 2017 * @ingroup ObjectModels */ typedef struct ift_maget { /** Set of Template Images (grayscale) */ iftFileSet *template_set; /** Set of Template Label Images. Each template image has a set of label images obtained from the registration of an atlas set. */ iftFileSet **template_label_sets; /** (Temp) Working Directory where the templates are stored. It will be removed when destroying this struct. */ char *workdir; /** Depth (in bits) of the images considered by the model */ int img_depth; } iftMAGeT; ///////////////////////////////////// FUNCTIONS ////////////////////////////////////////////////// /** * @brief Returns the center of the Test Image as the Reference Voxel. It does not required parameters. * @param test_img Testing Image. * @param params Parameters of the function. Not required (use NULL). * @return The central voxel of the image. * * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftVoxel iftRefVoxelByImageCenter(const iftImage *test_img, const iftDict *params); /** * @brief Returns the geometric center of the segmented testing image by threshold (t1 <= test_img[p] <= t2) * as the Reference Voxel. * * Required keys of <b>params</b>: \n * "t1": lower thresholding (integer) \n * "t2": upper thresholding (integer) \n * * @param test_img Testing Image. * @param params Parameters of the function. Not required (use NULL). * @return The central voxel of the image. * * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftVoxel iftRefVoxelByGeoCenterAfterThres(const iftImage *test_img, const iftDict *params); /** * @brief Creates a finder to determine a Reference Voxel in images. The dict <params> are just assigned (not copied). * * A finder function is associated for each algorithm's flag <alg>. * * @param alg Required Algorithm flag. * @param params Parameters used by the finder function. * @return A reference voxel finder. * * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftRefVoxelFinder *iftCreateRefVoxelFinder(iftRefVoxelFinderAlg alg, iftDict *params); /** * @brief Destroys a reference voxel finder. * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ void iftDestroyRefVoxelFinder(iftRefVoxelFinder **finder); /** * @brief Copies a reference voxel finder. * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftRefVoxelFinder *iftCopyRefVoxelFinder(const iftRefVoxelFinder *finder); /** * @brief Destroys a Multi-Object Shape Model. * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ void iftDestroyMObjModel(iftMObjModel **mmodel); /** * @brief Reads a Multi-Object Shape Model. It does not read the specific attributes of specialized * shape models (sosm, fuzzy, ...). * * @param path Pathname from the Shape Model. * @param tmp_dir Returns (if != NULL) the pathname from the temp directory where the files were unzipped. * If NULL, such dir will be deleted. * @return Multi-Object Shape Model. * * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftMObjModel *iftReadMObjModel(const char *path, char **tmp_dir); /** * @brief Destroys a Statistical Object Shape Model. * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ void iftDestroySOSM(iftMObjModel **sosm); /** * @brief Stores on disk the Statistical Object Shape Model. * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ void iftWriteSOSM(const iftMObjModel *sosm, const char *path); /** * @brief Reads from disk a Statistical Object Shape Model. * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftMObjModel *iftReadSOSM(const char *path); /** * @brief Destroys a Movable and Adaptive Probabilistic Atlas. * @author samuka * @date Jan 5, 2017 * @ingroup ObjectModels */ void iftDestroyMAPA(iftMObjModel **mapa); /** * @brief Stores on disk a Movable and Adaptive Probabilistic Atlas. * @author samuka * @date Jan 5, 2017 * @ingroup ObjectModels */ void iftWriteMAPA(const iftMObjModel *mapa, const char *path); /** * @brief Reads from disk a Movable and Adaptive Probabilistic Atlas. * @author samuka * @date Jan 5, 2017 * @ingroup ObjectModels */ iftMObjModel *iftReadMAPA(const char *path); /** * @brief Stores on disk the Fuzzy Shape Model. * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ void iftWriteFuzzyModel(const iftMObjModel *fuzzy, const char *path); /** * @brief Reads from disk a Fuzzy Shape Model. * @author samuka * @date Jan 3, 2017 * @ingroup ObjectModels */ iftMObjModel *iftReadFuzzyModel(const char *path); /** * @brief Destroys a Fuzzy Shape Model. * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ void iftDestroyFuzzyModel(iftMObjModel **fuzzy); /** * Writes a MAGeT struture. * @author samuka * @date Jan 13, 2017 * @ingroup ObjectModels */ void iftWriteMAGeT(const iftMAGeT *maget, const char *path); /** * @brief Reads a MAGeT struct. * @author samuka * @date Jan 16, 2017 * @ingroup ObjectModels */ iftMAGeT *iftReadMAGeT(const char *path); /** * Destroys a MAGeT struture. * @author samuka * @date Jan 13, 2017 * @ingroup ObjectModels */ void iftDestroyMAGeT(iftMAGeT **maget); /** * @brief Builds a Statistical Object Shape Model from a set of registered segmentation masks. * * @param label_paths Set of pathnames from registered segmentation mask (one for each image). * @param ref_img Reference Image (coordinate space). * @param labels Array with the object labels * @return Statistical Object Shape Model. * * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftMObjModel *iftBuildSOSM(const iftFileSet *label_paths, const iftImage *ref_img, iftIntArray *labels); /** * @brief Builds a Movable and Adaptive Probabilistic Atlas (MAPA), proposed in [1] (there named SOSM-A). * * Trained OPF Texture classifier and smooth_factor are assigned in extra dict, respectively, in keys * "texture-clf" and "smooth-factor". \n * [1] Martins, 2017 - SPIE - A Multi-Object Statistical Atlas Adaptive for Deformable Registration Errors in Anomalous Medical Image Segmentation * * @param label_paths Set of pathnames from registered segmentation mask (one for each image). * @param ref_img Reference Image (coordinate space). * @param labels Array with the object labels * @param marker_path File with the markers used to train the OPF texture classifier. * @param smooth_factor Factor (> 0) used to smooth the image before texture classifier (e.g., 0.3). * @return MAPA. * * @author samuka * @date Jan 5, 2017 * @ingroup ObjectModels */ iftMObjModel *iftBuildMAPA(const iftFileSet *label_paths, const iftImage *ref_img, iftIntArray *labels, const char *marker_path, float smooth_factor); /** * @brief Builds a Fuzzy Shape Model from a set of images and their segmentation masks. * * @param img_paths Set of images. * @param label_paths Segmentation masks of the input images. * @param ref_img Reference Image used for histogram matching when segmenting a testing image. * @param labels Array with the object labels. * @param finder Algorithm to find the reference voxel in images. * @param img_depth Depth (in bits) of the * @return Fuzzy Shape Model. * * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftMObjModel *iftBuildFuzzyModel(const iftFileSet *img_paths, const iftFileSet *label_paths, const iftImage *ref_img, iftIntArray *labels, iftRefVoxelFinder *finder); /** * @brief Builds a MAGeT-Brain with elastix for registration for the labels <labels>. * * [1] Pipitone, 2014 - Neuroimage - Multi-atlas segmentation of the whole hippocampus and subfields * using multiple automatically generated templates. * * @param train_img_entry Dir with the Train. Images or a CSV file with their pathnames. * @param train_label_entry Dir with the Train. Label Images or a CSV file with their pathnames. * @param template_img_entry Dir with the Template Images or a CSV file with their pathnames. * @param img_depth Depth of the Images: e.g: 12 -> [0,4095] * @param labels Array with the target object labels. * @param affine_params_path Elastix Affine (or Rigid or another) Parameter File * @param bspline_params_path Elastix BSpline Parameter File (required for Non-Rigid Registration) * @return MAGeT-Brain * * @author samuka * @date Jan 17, 2017 * @ingroup ObjectModels */ iftMAGeT *iftBuildElastixMAGeT(const char *train_img_entry, const char *train_label_entry, const char *template_img_entry, int img_depth, const iftIntArray *labels, const char *affine_params_path, const char *bspline_params_path); /** * @brief Finds the Displacement Vector between the Reference Voxel (from each Image) * and the Geometric Center of the target object. Histogram of the images are matched with the reference image * before. * * Resulting displacement vector is obtained by the weighted average displacement vector from all images. \n * PS: gcs[i] is the geometric center of the object from the image img_paths[i]. * * * @param img_paths Set of Images. * @param gcs Array of Geometric Centers of the target object for each image. * @param finder Algorithm to find the reference voxel in images. * @param ref_img Reference Image whose input histograms of the input images are matched. * @return Resulting displacement vector. * * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftVector iftFindDispVector(const iftFileSet *img_paths, iftVoxel *gcs, const iftImage *ref_img, const iftRefVoxelFinder *finder); /** * @brief Segments a Testing Image using the Statistical Multi-Object Shape Model SOSM-S (Phellan, 2016). * * It applies an Object Location by MSPS translating the seed models over the test image gradient. \n * Phellan, 2016 - Medical physics - Medical image segmentation via atlases and fuzzy object models * * @param test_img Test Image to be segmented. * @param sosm_s Statistical Object Shape Model. * @return Segmented Image. * * @author samuka * @date Jan 3, 2016 * @ingroup ObjectModels */ iftImage *iftSegmentBySOSM_S(const iftImage *test_img, const iftMObjModel *sosm_s, float e_radius, float d_radius); /** * @brief Segments a Testing Image using Movable and Adaptive Probabilistic Atlas (MAPA), proposed in (Martins, 2017) (there called SOSM-A). * * It applies an Object Location by MSPS translating the seed models over the test image gradient. \n * Final Test Gradient is: \n * Gt = grad of Test Image \n * Gm = gradient of the object map (resulting from test image classification) \n * Gi = (alpha * Gt) + ((1-alpha) * Gm) \n * Gp = gradient of Prob. Atlas after optimum search \n * Gf = (beta * Gi) + ((1-beta) * Gp) \n\n * * Martins, 2017 - SPIE - A Atlas Multi-Object Statistical Adaptive for Deformable Registration Errors * in Anomalous Medical Image Segmentation. * * @param test_img Test Image to be segmented. * @param mapa Movable and Adaptive Probabilistic Atlas. * @param grad_alg Gradient Algorithm. * @param alpha Factor used to combine linearly the Test Image Gradient and the Classified Image Gradient. * @param beta Factor used to combine linearly the Test Image Gradient and the MAPA gradient. * @param e_radius Erosion Radius that used to find the Inner Seeds (Certain Region Border of the Target Object). * @param d_radius Radius Dilation that is used to find the Outer Seeds (Certain Region Border of the Background). * @return Segmented Image. * * @author samuka * @date Jan 4, 2016 * @ingroup ObjectModels */ iftImage *iftSegmentByMAPA(const iftImage *test_img, const iftMObjModel *mapa, iftGradientAlg grad_alg, float alpha, float beta, float e_radius, float d_radius); /** * @brief Segments a Testing Image using the Fuzzy Model proposed in (Phellan, 2016). * * It applies an Object Location by MSPS translating the seed models over the test image gradient. \n * Actually, it is a slightly different from [1], because it applies a histogram matching with a * reference image from training set, finding the reference voxel from it. \n\n * * Phellan, 2016 - Medical physics - Medical image segmentation via atlases and fuzzy object models * * @param test_img Test Image to be segmented (or the final test image's gradient used for delineation). * @param fuzzy Fuzzy Model. * @return Segmented Image. * * @author samuka * @date Jan 3, 2016 * @ingroup ObjectModels */ iftImage *iftSegmentByFuzzyModel(const iftImage *test_img, const iftMObjModel *fuzzy); /** * @brief Segments an Image by Classical MALF. This functions considers the training label set is already registered on testing image. * * Classical MALF registers all atlases (img + label img) on test image's space. \n * The label of each voxel from segmentated image is the most frequent label (Majority Voting) \n * * @param test_img Testing Image to be segmented. * @param train_label_set Training label set already registered on testing image's space. * @return Segmented image. */ iftImage *iftSegmentByClassicalMALF(const iftImage *test_img, const iftFileSet *train_label_set); /** * @brief Gets the set of registered label images, used to segment a testing image, by MAGeT-Brain * (Multiple Automatically Generated Templates) (Pipitone, 2014). * * It registers each template image (grayscale) on test image's space, and maps the set of template label images * after. \n * We use Elastix for registration, instead of ANTs as the paper proposes. * * Pipitone, 2014 - Neuroimage - Multi-atlas segmentation of the whole hippocampus and subfields * using multiple automatically generated templates. * * @param test_img Testing image which will be segmented. * @param maget MAGeT approach. * @param affine_params_path Affine Elaxtix Registation params. * @param bspline_params_path BSpline Elaxtix Registation params. * @param out_dir Directory where the registered template label images will be stored. * @return File Set with the registered label images. */ iftFileSet *iftGetLabelSetByMAGeT(const iftImage *test_img, const iftMAGeT *maget, const char *affine_params_path, const char *bspline_params_path, char **tmp_dir); /** * @brief Puts the (cropped) shape model on test image's domain by aligning its center voxel with * the reference testing voxel by the displacement vector <disp_vec>. * * @param model (Cropped) Shape Model * @param test_img Testing Image. * @param ref_voxel_test Reference Voxel of testing image. * @param disp_vec Displacement Vector * @return Model on Test Image's domain. * * @author samuka * @date Jan 5, 2017 * @ingroup ObjectModels */ iftFImage *iftModelOnTestImageDomain(const iftFImage *model, const iftImage *test_img, iftVoxel ref_voxel_test, iftVector disp_vec); /** * @brief Puts the (cropped) shape model image on test image's domain by aligning its center voxel with * the reference testing voxel by the displacement vector <disp_vec>. * * @param model_img (Cropped) Shape Model Image * @param test_img Testing Image. * @param ref_voxel_test Reference Voxel of testing image. * @param disp_vec Displacement Vector * @return Model Image on Test Image's domain. * * @author samuka * @date Jan 5, 2017 * @ingroup ObjectModels */ iftImage *iftModelImageOnTestImageDomain(const iftImage *model_img, const iftImage *test_img, iftVoxel ref_voxel_test, iftVector disp_vec); /** * Computes the gradient of a Shape Model * * @param model Shape model. * @param max_img_val Maximum value of the images, based on image depth: (255, 4095, ...) * @param grad_alg Gradient Algorithm. * @return Gradient of the Shape Model. * * @author samuka * @date Dec 20, 2016 * @ingroup ObjectModels */ iftImage *iftShapeModelGradient(const iftFImage *model, int max_img_val, iftGradientAlg grad_alg); /** * @brief Finds the Object Model's Seeds (on test image space) for delineation. * * Given a Model (probabilistic map), background's seeds are those with prob 0 and object's seeds * with prob 1, after eroding and dilating the target object. \n * Finally, resulting seeds are filtered by a membership map (if != NULL), which is the test image previously classified, * where 0 are the background and 1 is the target object. \n * Filtering follows the rule: Inner seeds classified as backround become outer seeds. * * @param test_img Testing Image. * @param ref_voxel_test Reference Voxel from the test image. * @param obj_model Object Model. * @param e_radius Erosion radius used to get the inner seeds for delineation. * @param d_radius Dilation radius used to get the external seeds for delineation. * @param membership_map Membership Map (test image previsously classified) used to filtered the seeds. If NULL, no filtering. * @return Labeled seeds for delineation. * * @author samuka * @date Jan 3, 2017 * @ingroup ObjectModels */ iftLabeledSet *iftFindModelSeeds(const iftImage *test_img, iftVoxel ref_voxel_test, const iftObjModel *obj_model, double e_radius, double d_radius, const iftImage *membership_map); /** * @brief Register a test image on reference image's space of a multi-object shape model. * * Deformation fields are not saved. * * @param test_img Testing Image. * @param mmodel Multi-Object Statistical Shape Model. * @param affine_params_path Affine Elaxtix Registation params. * @param bspline_params_path BSpline Elaxtix Registation params. * @return Registered Testing Image Space * * @author samuka * @date Jan 6, 2017 * @ingroup ObjectModels */ iftImage *iftRegisterImageOnMObjModelByElastix(const iftImage *test_img, const iftMObjModel *mmodel, const char *affine_params_path, const char *bspline_params_path); /** * @brief Register (by Elastix) a Multi-Object Statistical Shape Model on a test image's space. Resulting registrations * and mapping are assigned in the own input model. * * Reference image is registerd with the test one. This will be the new reference image. \n * Then, all object models are mapped to new space using the deformation fields. \n * Deformation fields are not saved. * * @param mmodel Multi-Object Statistical Shape Model. * @param test_img Testing Image. * @param affine_params_path Affine Elaxtix Registation params. * @param bspline_params_path BSpline Elaxtix Registation params. * * @author samuka * @date Jan 6, 2017 * @ingroup ObjectModels */ void iftRegisterMObjModelByElastix(iftMObjModel *mmodel, const iftImage *test_img, const char *affine_params_path, const char *bspline_params_path); /** * @brief Selects the best atlases to a test image by Normalized Mutual Information. Train set and test * image must be already registered. * * The higher the NMI, more similar (better) the train image is. \n * If a train label set is passed, it considers only the bounding box around the objects to compute the NMI. \n * Be sure that train_label_set[i] corresponds to label image from image train_img_set[i]. * * @param[in] test_img (Registered) Testing Image. * @param[in] train_img_set (Registered) Training Image Set. * @param[in] train_label_set (Registered) Training Label Set. If != NULL, it considers tmasks the train_img_set before NMI. * @param[in] n_atlases Number of atlases to be selected. * @param chosen_idxs_out If != NULL, returns the indexes of the selected atlas in the train image set. * * @return A file set with the pathnames from the selected images. * * @author Samuka * @date Jan 27, 2017 * @ingroup ObjectModels */ iftFileSet *iftAtlasSelectionByNMI(const iftImage *test_img, const iftFileSet *train_img_set, const iftFileSet *train_label_set, int n_atlases, iftIntArray **chosen_idxs); /** * @brief Runs the program iftSegmentByClassicalMALF and returns the segmented Image. * * @param[in] test_img_path Test Image pathname. * @param[in] img_entry Train Image Set entry. * @param[in] label_entry Train Label Set entry. * @param[in] affine_params_path Affine parameter file (it can be NULL). * @param[in] bspline_params_path BSpline parameter file (it can be NULL). * * @return Segmented Image By MALF. * * @author Samuka * @date Jan 30, 2017 * @ingroup ObjectModels */ iftImage *iftRunProgSegmentByClassicalMALF(const char *test_img_path, const char *img_entry, const char *label_entry, const char *affine_params_path, const char *bspline_params_path); /** * @brief Apply the N4 algorithm for Inhomogeneity Correct in a MRI Image. * * It is used the default parameters, suggested by 3D Slicer tool [2], for N4 [1].\n * [1] Tustison, Nicholas J., et al. \"N4ITK: improved N3 bias correction.\" IEEE transactions on medical imaging 29.6 (2010): 1310-1320.\n * [2] https://www.slicer.org/ * * @param input_img Image to be corrected. * @param mask Binary mask that defines the structure of your interest. If NULL, N4 considers the entire image. * @param out_bias The resulting Bias Field Image by the N4 correction. If NULL, it is not considered. * @return Correct image by N4. */ iftImage *iftN4BiasFieldCorrection(const iftImage *input_img, const iftImage *mask, iftImage **out_bias); #ifdef __cplusplus } #endif #endif
35.165062
146
0.699315
[ "object", "shape", "vector", "model", "3d" ]
368378b5775a1121bb240fa6a117e33b06d695b3
77,857
c
C
genomics/assembly/unitig/unitig_walker.c
gkthiruvathukal/biosal
60f31174054ea628224569104e80d91e3076456c
[ "BSD-2-Clause" ]
null
null
null
genomics/assembly/unitig/unitig_walker.c
gkthiruvathukal/biosal
60f31174054ea628224569104e80d91e3076456c
[ "BSD-2-Clause" ]
null
null
null
genomics/assembly/unitig/unitig_walker.c
gkthiruvathukal/biosal
60f31174054ea628224569104e80d91e3076456c
[ "BSD-2-Clause" ]
null
null
null
#include "unitig_walker.h" #include "path_status.h" #include "../assembly_graph_store.h" #include "../assembly_vertex.h" #include <genomics/data/coverage_distribution.h> #include <genomics/data/dna_kmer.h> #include <genomics/data/dna_codec.h> #include <genomics/helpers/dna_helper.h> #include <genomics/helpers/command.h> #include <core/patterns/writer_process.h> #include <core/helpers/order.h> #include <core/hash/hash.h> #include <core/system/command.h> #include <core/system/debugger.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include <stdint.h> /* * Debug the walker. */ /* #define BIOSAL_UNITIG_WALKER_DEBUG */ #define MINIMUM_PATH_LENGTH_IN_NUCLEOTIDES 100 #define SIGNATURE_SEED (0xd948c134) /* #define DEBUG_SYNCHRONIZATION */ /* #define DEBUG_PATH_NAMES */ /* #define HIGHLIGH_STARTING_POINT */ #define OPERATION_FETCH_FIRST 0 #define OPERATION_FETCH_PARENTS 1 #define OPERATION_FETCH_CHILDREN 2 #define OPERATION_SELECT_CHILD 8 #define OPERATION_SELECT_PARENT 9 #define STATUS_NO_STATUS (-1) #define STATUS_NO_EDGE 0 #define STATUS_IMPOSSIBLE_CHOICE 1 #define STATUS_NOT_REGULAR 2 #define STATUS_WITH_CHOICE 3 #define STATUS_ALREADY_VISITED 4 #define STATUS_DISAGREEMENT 5 #define STATUS_DEFEAT 6 #define STATUS_NOT_UNITIG_VERTEX 7 #define STATUS_CYCLE 8 /* * Statuses for a path. */ #define PATH_STATUS_DEFEAT_BY_SHORT_LENGTH 0 #define PATH_STATUS_DEFEAT_BY_FAILED_CHALLENGE 1 #define PATH_STATUS_DEFEAT_WITH_CHALLENGER 2 #define PATH_STATUS_VICTORY_WITHOUT_CHALLENGERS 3 #define PATH_STATUS_VICTORY_WITH_CHALLENGERS 4 #define PATH_STATUS_IN_PROGRESS_WITHOUT_CHALLENGERS 5 #define PATH_STATUS_IN_PROGRESS_WITH_CHALLENGERS 6 #define PATH_STATUS_DUPLICATE_VERTEX 7 #define MEMORY_POOL_NAME_WALKER 0x78e238cd void biosal_unitig_walker_init(struct thorium_actor *self); void biosal_unitig_walker_destroy(struct thorium_actor *self); void biosal_unitig_walker_receive(struct thorium_actor *self, struct thorium_message *message); void biosal_unitig_walker_get_starting_kmer_reply(struct thorium_actor *self, struct thorium_message *message); void biosal_unitig_walker_start(struct thorium_actor *self, struct thorium_message *message); void biosal_unitig_walker_get_vertex_reply(struct thorium_actor *self, struct thorium_message *message); void biosal_unitig_walker_get_vertices_and_select(struct thorium_actor *self, struct thorium_message *message); void biosal_unitig_walker_get_vertices_and_select_reply(struct thorium_actor *self, struct thorium_message *message); void biosal_unitig_walker_get_vertex_reply_starting_vertex(struct thorium_actor *self, struct thorium_message *message); void biosal_unitig_walker_clear(struct thorium_actor *self); void biosal_unitig_walker_dump_path(struct thorium_actor *self); void biosal_unitig_walker_begin(struct thorium_actor *self, struct thorium_message *message); int biosal_unitig_walker_select(struct thorium_actor *self, int *output_status); void biosal_unitig_walker_write(struct thorium_actor *self, uint64_t name, char *sequence, int sequence_length, int circular, uint64_t signature); void biosal_unitig_walker_make_decision(struct thorium_actor *self); void biosal_unitig_walker_set_current(struct thorium_actor *self, struct biosal_dna_kmer *kmer, struct biosal_assembly_vertex *vertex); uint64_t biosal_unitig_walker_get_path_name(struct thorium_actor *self, int length, char *sequence); void biosal_unitig_walker_check_symmetry(struct thorium_actor *self, int parent_choice, int child_choice, int *choice, int *status); void biosal_unitig_walker_check_agreement(struct thorium_actor *self, int parent_choice, int child_choice, int *choice, int *status); void biosal_unitig_walker_check_usage(struct thorium_actor *self, int *choice, int *status, struct core_vector *selected_kmers); int biosal_unitig_walker_get_current_length(struct thorium_actor *self); void biosal_unitig_walker_notify(struct thorium_actor *self, struct thorium_message *message); void biosal_unitig_walker_notify_reply(struct thorium_actor *self, struct thorium_message *message); void biosal_unitig_walker_mark_vertex(struct thorium_actor *self, struct biosal_dna_kmer *kmer); int biosal_unitig_walker_select_old_version(struct thorium_actor *self, int *output_status); void biosal_unitig_walker_normalize_cycle(struct thorium_actor *self, int length, char *sequence); void biosal_unitig_walker_select_strand(struct thorium_actor *self, int length, char *sequence); struct thorium_script biosal_unitig_walker_script = { .identifier = SCRIPT_UNITIG_WALKER, .name = "biosal_unitig_walker", .init = biosal_unitig_walker_init, .destroy = biosal_unitig_walker_destroy, .receive = biosal_unitig_walker_receive, .size = sizeof(struct biosal_unitig_walker), .description = "Testbed for testing ideas." }; void biosal_unitig_walker_init(struct thorium_actor *self) { struct biosal_unitig_walker *concrete_self; #ifdef BIOSAL_UNITIG_WALKER_USE_PRIVATE_FILE int argc; char **argv; char name_as_string[64]; char *directory_name; char *path; int name; #endif concrete_self = thorium_actor_concrete_actor(self); concrete_self->writer_process = THORIUM_ACTOR_NOBODY; concrete_self->start_messages = 0; /* * Initialize the memory pool first. */ core_memory_pool_init(&concrete_self->memory_pool, 1048576, MEMORY_POOL_NAME_WALKER); core_map_init(&concrete_self->path_statuses, sizeof(int), sizeof(struct biosal_path_status)); core_map_set_memory_pool(&concrete_self->path_statuses, &concrete_self->memory_pool); concrete_self->dried_stores = 0; concrete_self->skipped_at_start_used = 0; concrete_self->skipped_at_start_not_unitig = 0; /* argc = thorium_actor_argc(self); argv = thorium_actor_argv(self); */ /* * Building the set with a key length of 0 does nothing * and does not allocate any memory whatsoever. */ core_set_init(&concrete_self->visited, 0); core_set_set_memory_pool(&concrete_self->visited, &concrete_self->memory_pool); core_vector_init(&concrete_self->graph_stores, sizeof(int)); thorium_actor_add_action(self, ACTION_ASSEMBLY_GET_STARTING_KMER_REPLY, biosal_unitig_walker_get_starting_kmer_reply); thorium_actor_add_action(self, ACTION_START, biosal_unitig_walker_start); thorium_actor_add_action(self, ACTION_ASSEMBLY_GET_VERTEX_REPLY, biosal_unitig_walker_get_vertex_reply); thorium_actor_add_action(self, ACTION_ASSEMBLY_GET_VERTICES_AND_SELECT, biosal_unitig_walker_get_vertices_and_select); thorium_actor_add_action(self, ACTION_ASSEMBLY_GET_VERTICES_AND_SELECT_REPLY, biosal_unitig_walker_get_vertices_and_select_reply); thorium_actor_add_action(self, ACTION_BEGIN, biosal_unitig_walker_begin); thorium_actor_add_action_with_condition(self, ACTION_ASSEMBLY_GET_VERTEX_REPLY, biosal_unitig_walker_get_vertex_reply_starting_vertex, &concrete_self->has_starting_vertex, 0); thorium_actor_add_action(self, ACTION_NOTIFY, biosal_unitig_walker_notify); thorium_actor_add_action(self, ACTION_NOTIFY_REPLY, biosal_unitig_walker_notify_reply); core_vector_init(&concrete_self->left_path, sizeof(int)); core_vector_set_memory_pool(&concrete_self->left_path, &concrete_self->memory_pool); core_vector_init(&concrete_self->right_path, sizeof(int)); core_vector_set_memory_pool(&concrete_self->right_path, &concrete_self->memory_pool); core_vector_init(&concrete_self->child_vertices, sizeof(struct biosal_assembly_vertex)); core_vector_set_memory_pool(&concrete_self->child_vertices, &concrete_self->memory_pool); core_vector_init(&concrete_self->child_kmers, sizeof(struct biosal_dna_kmer)); core_vector_set_memory_pool(&concrete_self->child_kmers, &concrete_self->memory_pool); core_vector_init(&concrete_self->parent_vertices, sizeof(struct biosal_assembly_vertex)); core_vector_set_memory_pool(&concrete_self->parent_vertices, &concrete_self->memory_pool); core_vector_init(&concrete_self->parent_kmers, sizeof(struct biosal_dna_kmer)); core_vector_set_memory_pool(&concrete_self->parent_kmers, &concrete_self->memory_pool); /* * Configure the codec. */ biosal_dna_codec_init(&concrete_self->codec); if (biosal_dna_codec_must_use_two_bit_encoding(&concrete_self->codec, thorium_actor_get_node_count(self))) { biosal_dna_codec_enable_two_bit_encoding(&concrete_self->codec); } biosal_dna_kmer_init_empty(&concrete_self->current_kmer); biosal_assembly_vertex_init(&concrete_self->current_vertex); concrete_self->path_index = 0; #ifdef BIOSAL_UNITIG_WALKER_USE_PRIVATE_FILE directory_name = core_command_get_output_directory(argc, argv); #endif #ifdef BIOSAL_UNITIG_WALKER_USE_PRIVATE_FILE name = thorium_actor_name(self); sprintf(name_as_string, "%d", name); core_string_init(&concrete_self->file_path, directory_name); core_string_append(&concrete_self->file_path, "/unitig_walker_"); core_string_append(&concrete_self->file_path, name_as_string); core_string_append(&concrete_self->file_path, ".fasta"); path = core_string_get(&concrete_self->file_path); biosal_buffered_file_writer_init(&concrete_self->writer, path); #endif concrete_self->fetch_operation = OPERATION_FETCH_FIRST; concrete_self->select_operation = OPERATION_SELECT_CHILD; biosal_unitig_heuristic_init(&concrete_self->heuristic, biosal_command_get_minimum_coverage(thorium_actor_argc(self), thorium_actor_argv(self))); concrete_self->current_is_circular = 0; } void biosal_unitig_walker_destroy(struct thorium_actor *self) { struct biosal_unitig_walker *concrete_self; concrete_self = thorium_actor_concrete_actor(self); core_map_destroy(&concrete_self->path_statuses); biosal_dna_codec_destroy(&concrete_self->codec); #ifdef BIOSAL_UNITIG_WALKER_USE_PRIVATE_FILE core_string_destroy(&concrete_self->file_path); biosal_buffered_file_writer_destroy(&concrete_self->writer); #endif core_set_destroy(&concrete_self->visited); core_vector_destroy(&concrete_self->graph_stores); biosal_unitig_walker_clear(self); core_vector_destroy(&concrete_self->left_path); core_vector_destroy(&concrete_self->right_path); core_vector_destroy(&concrete_self->child_kmers); core_vector_destroy(&concrete_self->child_vertices); core_vector_destroy(&concrete_self->parent_kmers); core_vector_destroy(&concrete_self->parent_vertices); biosal_dna_kmer_destroy(&concrete_self->current_kmer, &concrete_self->memory_pool); biosal_assembly_vertex_destroy(&concrete_self->current_vertex); biosal_unitig_heuristic_destroy(&concrete_self->heuristic); printf("DEBUG unitig_walker skipped_at_start_used %d skipped_at_start_not_unitig %d\n", concrete_self->skipped_at_start_used, concrete_self->skipped_at_start_not_unitig); /* * Destroy the memory pool at the end. */ core_memory_pool_destroy(&concrete_self->memory_pool); } void biosal_unitig_walker_receive(struct thorium_actor *self, struct thorium_message *message) { int tag; struct biosal_unitig_walker *concrete_self; struct biosal_dna_kmer kmer; struct core_memory_pool *ephemeral_memory; if (thorium_actor_take_action(self, message)) { return; } tag = thorium_message_action(message); concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); if (tag == ACTION_START) { /* * This is useless because ACTION_START is configured to be handled * by biosal_unitig_walker_start(). */ biosal_unitig_walker_start(self, message); } else if (tag == ACTION_SET_CONSUMER) { thorium_message_unpack_int(message, 0, &concrete_self->writer_process); thorium_actor_send_reply_empty(self, ACTION_SET_CONSUMER_REPLY); /* * Try to start now. */ biosal_unitig_walker_start(self, message); } else if (tag == ACTION_MARK_VERTEX_AS_VISITED_REPLY) { /* * Continue the work now. */ thorium_actor_send_to_self_empty(self, ACTION_ASSEMBLY_GET_VERTICES_AND_SELECT); } else if (tag == ACTION_ASK_TO_STOP) { thorium_actor_send_to_self_empty(self, ACTION_STOP); } else if (tag == ACTION_ASSEMBLY_GET_KMER_LENGTH_REPLY) { thorium_message_unpack_int(message, 0, &concrete_self->kmer_length); biosal_dna_kmer_init_mock(&kmer, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); concrete_self->key_length = biosal_dna_kmer_pack_size(&kmer, concrete_self->kmer_length, &concrete_self->codec); /* * This uses 2-bit encoding to store the visited kmers * when there are at least 2 nodes. */ core_set_init(&concrete_self->visited, concrete_self->key_length); core_set_set_memory_pool(&concrete_self->visited, &concrete_self->memory_pool); biosal_dna_kmer_destroy(&kmer, ephemeral_memory); #if 0 printf("KeyLength %d\n", concrete_self->key_length); #endif thorium_actor_send_to_self_empty(self, ACTION_BEGIN); } } void biosal_unitig_walker_begin(struct thorium_actor *self, struct thorium_message *message) { struct biosal_unitig_walker *concrete_self; int store_index; int store; int size; concrete_self = thorium_actor_concrete_actor(self); size = core_vector_size(&concrete_self->graph_stores); store_index = concrete_self->store_index; ++concrete_self->store_index; concrete_self->store_index %= size; store = core_vector_at_as_int(&concrete_self->graph_stores, store_index); #if 0 printf("DEBUG_WALKER BEGIN\n"); #endif thorium_actor_send_empty(self, store, ACTION_ASSEMBLY_GET_STARTING_KMER); } void biosal_unitig_walker_start(struct thorium_actor *self, struct thorium_message *message) { void *buffer; struct biosal_unitig_walker *concrete_self; int graph; int source; int size; int count; int position; int action; action = thorium_message_action(message); count = thorium_message_count(message); #if 0 thorium_actor_send_reply_empty(self, ACTION_START_REPLY); return; #endif concrete_self = thorium_actor_concrete_actor(self); /* * 2 start messages are required: ACTION_START and ACTION_SET_CONSUMER */ ++concrete_self->start_messages; source = thorium_message_source(message); buffer = thorium_message_buffer(message); concrete_self->source = source; CORE_DEBUGGER_ASSERT_NOT_NULL(buffer); /* * This entry point is invoked by ACTION_START and also by * ACTION_SET_CONSUMER. */ if (action == ACTION_START) { position = core_vector_unpack(&concrete_self->graph_stores, buffer); CORE_DEBUGGER_ASSERT(position <= count); } /* * wait for ACTION_SET_CONSUMER... */ if (concrete_self->start_messages != 2) { return; } size = core_vector_size(&concrete_self->graph_stores); printf("%s/%d is ready to surf the graph (%d stores => writer/%d)!\n", thorium_actor_script_name(self), thorium_actor_name(self), size, concrete_self->writer_process); /* * Use a random starting point. */ concrete_self->store_index = rand() % size; graph = core_vector_at_as_int(&concrete_self->graph_stores, concrete_self->store_index); thorium_actor_send_empty(self, graph, ACTION_ASSEMBLY_GET_KMER_LENGTH); } void biosal_unitig_walker_get_starting_kmer_reply(struct thorium_actor *self, struct thorium_message *message) { struct biosal_unitig_walker *concrete_self; void *buffer; int count; struct thorium_message new_message; char *new_buffer; struct core_memory_pool *ephemeral_memory; int new_count; char *key; count = thorium_message_count(message); concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); /* * No more vertices to consume. */ if (count == 0) { ++concrete_self->dried_stores; /* * All the graph was explored. */ if (concrete_self->dried_stores == core_vector_size(&concrete_self->graph_stores)) { thorium_actor_send_empty(self, concrete_self->source, ACTION_START_REPLY); } else { /* * Otherwise, begin a new round using the next graph store. */ thorium_actor_send_to_self_empty(self, ACTION_BEGIN); } return; } buffer = thorium_message_buffer(message); biosal_dna_kmer_init_empty(&concrete_self->current_kmer); biosal_dna_kmer_unpack(&concrete_self->current_kmer, buffer, concrete_self->kmer_length, &concrete_self->memory_pool, &concrete_self->codec); #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("%s/%d received starting vertex (%d bytes) from source %d hash %" PRIu64 "\n", thorium_actor_script_name(self), thorium_actor_name(self), count, thorium_message_source(message), biosal_dna_kmer_hash(&concrete_self->current_kmer, concrete_self->kmer_length, &concrete_self->codec)); biosal_dna_kmer_print(&concrete_self->current_kmer, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); #endif /* * First steps: * * - get starting kmer * - get starting vertex * - set starting vertex * - set current kmer * - set current vertex */ biosal_dna_kmer_init_copy(&concrete_self->starting_kmer, &concrete_self->current_kmer, concrete_self->kmer_length, &concrete_self->memory_pool, &concrete_self->codec); /* * Set the key as visited to detect cycles in the graphs * caused by plasmids and other cool stuff. */ key = core_memory_pool_allocate(ephemeral_memory, concrete_self->key_length); biosal_dna_kmer_pack(&concrete_self->starting_kmer, key, concrete_self->kmer_length, &concrete_self->codec); core_set_add(&concrete_self->visited, key); core_memory_pool_free(ephemeral_memory, key); concrete_self->has_starting_vertex = 0; concrete_self->fetch_operation = OPERATION_FETCH_FIRST; new_count = count; /*new_count += sizeof(concrete_self->path_index);*/ new_buffer = thorium_actor_allocate(self, new_count); core_memory_copy(new_buffer, buffer, count); /*core_memory_copy(new_buffer + count, &concrete_self->path_index, sizeof(concrete_self->path_index));*/ #if 0 printf("ACTION_ASSEMBLY_GET_VERTEX path_index %d\n", concrete_self->path_index); #endif thorium_message_init(&new_message, ACTION_ASSEMBLY_GET_VERTEX, new_count, new_buffer); thorium_actor_send_reply(self, &new_message); thorium_message_destroy(&new_message); } void biosal_unitig_walker_get_vertex_reply_starting_vertex(struct thorium_actor *self, struct thorium_message *message) { void *buffer; struct biosal_unitig_walker *concrete_self; struct biosal_path_status *bucket; buffer = thorium_message_buffer(message); concrete_self = thorium_actor_concrete_actor(self); biosal_assembly_vertex_init(&concrete_self->current_vertex); biosal_assembly_vertex_unpack(&concrete_self->current_vertex, buffer); /* * Check if the vertex is already used. ACTION_ASSEMBLY_GET_STARTING_KMER * returns a kmer that has the flag BIOSAL_VERTEX_FLAG_USED set, * but another actor can grab the vertex in the mean time. * * Skip used vertices. */ if (biosal_assembly_vertex_get_flag(&concrete_self->current_vertex, BIOSAL_VERTEX_FLAG_USED)) { biosal_assembly_vertex_destroy(&concrete_self->current_vertex); ++concrete_self->skipped_at_start_used; thorium_actor_send_to_self_empty(self, ACTION_BEGIN); return; } /* * Skip it if it is not a unitig vertex. */ if (!biosal_assembly_vertex_get_flag(&concrete_self->current_vertex, BIOSAL_VERTEX_FLAG_UNITIG)) { biosal_assembly_vertex_destroy(&concrete_self->current_vertex); ++concrete_self->skipped_at_start_not_unitig; thorium_actor_send_to_self_empty(self, ACTION_BEGIN); return; } /* * Set an initial status. */ bucket = core_map_add(&concrete_self->path_statuses, &concrete_self->path_index); #if 0 printf("%d DEBUG add status path_index %d PATH_STATUS_IN_PROGRESS_WITHOUT_CHALLENGERS\n", thorium_actor_name(self), concrete_self->path_index); #endif bucket->status = PATH_STATUS_IN_PROGRESS_WITHOUT_CHALLENGERS; bucket->length_in_nucleotides = -1; /* * This is the starting vertex. */ biosal_assembly_vertex_init_copy(&concrete_self->starting_vertex, &concrete_self->current_vertex); #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("Connectivity for starting vertex: \n"); biosal_assembly_vertex_print(&concrete_self->current_vertex); #endif /* * At this point, this information is fetched: * * - current_kmer * - current_vertex * * From these, the children kmers can be generated. */ concrete_self->has_starting_vertex = 1; biosal_unitig_walker_clear(self); thorium_actor_send_to_self_empty(self, ACTION_ASSEMBLY_GET_VERTICES_AND_SELECT); } void biosal_unitig_walker_get_vertices_and_select(struct thorium_actor *self, struct thorium_message *message) { struct biosal_unitig_walker *concrete_self; struct thorium_message new_message; int new_count; char *new_buffer; struct core_memory_pool *ephemeral_memory; int store_index; int store; int i; int child_count; int parent_count; int code; struct biosal_dna_kmer child_kmer; struct biosal_dna_kmer *child_kmer_to_fetch; struct biosal_dna_kmer parent_kmer; struct biosal_dna_kmer *parent_kmer_to_fetch; concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); /* * - generate child kmers * - get child vertices * - select * - append code * - set current kmer * - set current vertex */ /* * Generate child kmers and parent kmers. */ child_count = biosal_assembly_vertex_child_count(&concrete_self->current_vertex); parent_count = biosal_assembly_vertex_parent_count(&concrete_self->current_vertex); if (core_vector_size(&concrete_self->child_kmers) != child_count) { #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("Generate child kmers\n"); #endif for (i = 0; i < child_count; i++) { code = biosal_assembly_vertex_get_child(&concrete_self->current_vertex, i); biosal_dna_kmer_init_as_child(&child_kmer, &concrete_self->current_kmer, code, concrete_self->kmer_length, &concrete_self->memory_pool, &concrete_self->codec); core_vector_push_back(&concrete_self->child_kmers, &child_kmer); } } if (core_vector_size(&concrete_self->parent_kmers) != parent_count) { for (i = 0; i < parent_count; i++) { code = biosal_assembly_vertex_get_parent(&concrete_self->current_vertex, i); biosal_dna_kmer_init_as_parent(&parent_kmer, &concrete_self->current_kmer, code, concrete_self->kmer_length, &concrete_self->memory_pool, &concrete_self->codec); core_vector_push_back(&concrete_self->parent_kmers, &parent_kmer); } } /* Fetch a child vertex. */ if (concrete_self->current_child < child_count) { child_kmer_to_fetch = core_vector_at(&concrete_self->child_kmers, concrete_self->current_child); new_count = biosal_dna_kmer_pack_size(child_kmer_to_fetch, concrete_self->kmer_length, &concrete_self->codec); /*new_count += sizeof(concrete_self->path_index);*/ new_buffer = thorium_actor_allocate(self, new_count); biosal_dna_kmer_pack(child_kmer_to_fetch, new_buffer, concrete_self->kmer_length, &concrete_self->codec); /* core_memory_copy(new_buffer + new_count - sizeof(concrete_self->path_index), &concrete_self->path_index, sizeof(concrete_self->path_index)); */ store_index = biosal_dna_kmer_store_index(child_kmer_to_fetch, core_vector_size(&concrete_self->graph_stores), concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); store = core_vector_at_as_int(&concrete_self->graph_stores, store_index); concrete_self->fetch_operation = OPERATION_FETCH_CHILDREN; thorium_message_init(&new_message, ACTION_ASSEMBLY_GET_VERTEX, new_count, new_buffer); thorium_actor_send(self, store, &new_message); thorium_message_destroy(&new_message); /* Fetch a parent vertex. */ } else if (concrete_self->current_parent < parent_count) { parent_kmer_to_fetch = core_vector_at(&concrete_self->parent_kmers, concrete_self->current_parent); new_count = biosal_dna_kmer_pack_size(parent_kmer_to_fetch, concrete_self->kmer_length, &concrete_self->codec); /* new_count += sizeof(concrete_self->path_index); */ new_buffer = thorium_actor_allocate(self, new_count); biosal_dna_kmer_pack(parent_kmer_to_fetch, new_buffer, concrete_self->kmer_length, &concrete_self->codec); /* core_memory_copy(new_buffer + new_count - sizeof(concrete_self->path_index), &concrete_self->path_index, sizeof(concrete_self->path_index)); */ store_index = biosal_dna_kmer_store_index(parent_kmer_to_fetch, core_vector_size(&concrete_self->graph_stores), concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); store = core_vector_at_as_int(&concrete_self->graph_stores, store_index); concrete_self->fetch_operation = OPERATION_FETCH_PARENTS; #if 0 printf("DEBUG send %d/%d ACTION_ASSEMBLY_GET_VERTEX Parent ", concrete_self->current_parent, parent_count); biosal_dna_kmer_print(parent_kmer_to_fetch, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); printf("Current: "); biosal_dna_kmer_print(&concrete_self->current_kmer, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); #endif thorium_message_init(&new_message, ACTION_ASSEMBLY_GET_VERTEX, new_count, new_buffer); thorium_actor_send(self, store, &new_message); thorium_message_destroy(&new_message); } else { /* * - select * - append code * - set current kmer * - set current vertex * - send message. */ #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("Got all child vertices (%d)\n", size); #endif biosal_unitig_walker_make_decision(self); } } void biosal_unitig_walker_get_vertices_and_select_reply(struct thorium_actor *self, struct thorium_message *message) { /* struct biosal_unitig_walker *concrete_self; concrete_self = thorium_actor_concrete_actor(self); */ biosal_unitig_walker_dump_path(self); #if 0 if (concrete_self->path_index % 1000 == 0) { printf("path_index is %d\n", concrete_self->path_index); } #endif thorium_actor_send_to_self_empty(self, ACTION_BEGIN); } void biosal_unitig_walker_get_vertex_reply(struct thorium_actor *self, struct thorium_message *message) { void *buffer; struct biosal_unitig_walker *concrete_self; struct biosal_assembly_vertex vertex; int last_actor; int last_path_index; int name; int length; int new_count; char *new_buffer; int position; concrete_self = thorium_actor_concrete_actor(self); buffer = thorium_message_buffer(message); biosal_assembly_vertex_init(&vertex); biosal_assembly_vertex_unpack(&vertex, buffer); #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("Vertex after reception: \n"); biosal_assembly_vertex_print(&vertex); #endif /* * OPERATION_FETCH_FIRST uses a different code path. */ CORE_DEBUGGER_ASSERT(concrete_self->fetch_operation != OPERATION_FETCH_FIRST); if (concrete_self->fetch_operation == OPERATION_FETCH_CHILDREN) { core_vector_push_back(&concrete_self->child_vertices, &vertex); ++concrete_self->current_child; } else if (concrete_self->fetch_operation == OPERATION_FETCH_PARENTS) { core_vector_push_back(&concrete_self->parent_vertices, &vertex); ++concrete_self->current_parent; } /* * Check for competition. */ last_actor = biosal_assembly_vertex_last_actor(&vertex); name = thorium_actor_name(self); if (biosal_assembly_vertex_get_flag(&vertex, BIOSAL_VERTEX_FLAG_USED) && last_actor != name) { last_path_index = biosal_assembly_vertex_last_path_index(&vertex); #if 0 /* ask the other actor about it. */ printf("actor/%d needs to ask actor/%d for solving BIOSAL_VERTEX_FLAG_USED\n", thorium_actor_name(self), actor); #endif length = biosal_unitig_walker_get_current_length(self); new_count = 0; new_count += sizeof(last_path_index); new_count += sizeof(length); new_buffer = thorium_actor_allocate(self, new_count); position = 0; core_memory_copy(new_buffer + position, &last_path_index, sizeof(last_path_index)); position += sizeof(last_path_index); core_memory_copy(new_buffer + position, &length, sizeof(length)); position += sizeof(length); #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("%d sends to %d ACTION_NOTIFY last_path_index %d current_path %d length %d\n", thorium_actor_name(self), last_actor, last_path_index, concrete_self->path_index, length); #endif CORE_DEBUGGER_ASSERT(last_path_index >= 0); /* * Ask the owner about it. */ thorium_actor_send_buffer(self, last_actor, ACTION_NOTIFY, new_count, new_buffer); } else { thorium_actor_send_to_self_empty(self, ACTION_ASSEMBLY_GET_VERTICES_AND_SELECT); } } void biosal_unitig_walker_notify(struct thorium_actor *self, struct thorium_message *message) { struct biosal_unitig_walker *concrete_self; int authorized_to_continue; int length; int other_length; int source; int position; int path_index; struct biosal_path_status *bucket; int name; int check_equal_length; int disable_battle; disable_battle = 1; check_equal_length = 1; name = thorium_actor_name(self); concrete_self = thorium_actor_concrete_actor(self); position = 0; source = thorium_message_source(message); /* * Check if the kmer is in the current set. If not, it was in * a previous set. */ position += thorium_message_unpack_int(message, position, &path_index); position += thorium_message_unpack_int(message, position, &other_length); length = biosal_unitig_walker_get_current_length(self); /* * Get path status. */ bucket = core_map_get(&concrete_self->path_statuses, &path_index); #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("DEBUG ACTION_NOTIFY actor/%d (self) has %d (status %d), actor/%d has %d\n", thorium_actor_name(self), length, bucket->status, source, other_length); #endif #ifdef CORE_DEBUGGER_ENABLE_ASSERT if (bucket == NULL) { printf("Error %d received ACTION_NOTIFY, not found path_index= %d (current path_index %d)\n", thorium_actor_name(self), path_index, concrete_self->path_index); } #endif CORE_DEBUGGER_ASSERT(bucket != NULL); /* * This will tell the source wheteher or not we authorize it to * continue. */ authorized_to_continue = 1; if (disable_battle) { } else if (bucket->status == PATH_STATUS_VICTORY_WITHOUT_CHALLENGERS || bucket->status == PATH_STATUS_VICTORY_WITH_CHALLENGERS) { length = bucket->length_in_nucleotides; /* * The current actor already claimed a victory in the past. */ #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("actor %d path %d past victory status %d length_in_nucleotides %d challenger length %d\n", thorium_actor_name(self), path_index, bucket->status, bucket->length_in_nucleotides, other_length); #endif #ifdef CORE_DEBUGGER_ENABLE_ASSERT_disabled if (!(other_length <= length)) { printf("Error, this is false: %d <= %d\n", other_length, length); } #endif /*CORE_DEBUGGER_ASSERT(other_length <= length);*/ /* This should be 0 */ authorized_to_continue = 0; } else if (bucket->status == PATH_STATUS_IN_PROGRESS_WITHOUT_CHALLENGERS || bucket->status == PATH_STATUS_IN_PROGRESS_WITH_CHALLENGERS) { /* * Fight now !!! * * The longest wins. * * If the lengths are equal, then the highest name wins. */ CORE_DEBUGGER_ASSERT(name != source); if (length > other_length || (check_equal_length && length == other_length && name > source)) { /* this should be 0 */ authorized_to_continue = 0; bucket->status = PATH_STATUS_IN_PROGRESS_WITH_CHALLENGERS; /* *bucket = PATH_STATUS_VICTORY_WITH_CHALLENGERS; */ #if 0 printf("%d victory with length\n", thorium_actor_name(self)); #endif } else { authorized_to_continue = 1; /* * printf("%d DEBUG PATH_STATUS_DEFEAT_WITH_CHALLENGER length %d other_length %d\n", thorium_actor_name(self), length, other_length); */ /* * Stop the current one. */ /* */ bucket->status = PATH_STATUS_DEFEAT_WITH_CHALLENGER; } } else if (bucket->status == PATH_STATUS_DEFEAT_WITH_CHALLENGER || bucket->status == PATH_STATUS_DEFEAT_BY_FAILED_CHALLENGE) { /* * There will be another battle not involving the current actor. */ authorized_to_continue = 1; /* * TODO: provide the name of the winner. */ } thorium_actor_send_reply_int(self, ACTION_NOTIFY_REPLY, authorized_to_continue); } void biosal_unitig_walker_notify_reply(struct thorium_actor *self, struct thorium_message *message) { struct biosal_unitig_walker *concrete_self; int authorized_to_continue; struct biosal_path_status *bucket; concrete_self = thorium_actor_concrete_actor(self); thorium_message_unpack_int(message, 0, &authorized_to_continue); if (!authorized_to_continue) { bucket = core_map_get(&concrete_self->path_statuses, &concrete_self->path_index); CORE_DEBUGGER_ASSERT(bucket != NULL); /* * 2 defeats are necessary. The reason is that the ends of bubbles and tips * are also marked, but meeting just one such marked vertex should not * stop anything. */ /* * accept defeat. */ /* */ bucket->status = PATH_STATUS_DEFEAT_BY_FAILED_CHALLENGE; #if 0 printf("%d path_index %d source %d current_length %d DEBUG PATH_STATUS_DEFEAT_BY_FAILED_CHALLENGE !!!\n", thorium_actor_name(self), concrete_self->path_index, thorium_message_source(message), biosal_unitig_walker_get_current_length(self)); #endif } #ifdef DEBUG_SYNCHRONIZATION printf("DEBUG received ACTION_NOTIFY_REPLY, other_is_longer-> %d\n", authorized_to_continue); #endif thorium_actor_send_to_self_empty(self, ACTION_ASSEMBLY_GET_VERTICES_AND_SELECT); } void biosal_unitig_walker_clear(struct thorium_actor *self) { struct biosal_unitig_walker *concrete_self; int parent_count; int child_count; int i; struct biosal_dna_kmer *kmer; struct biosal_assembly_vertex *vertex; concrete_self = thorium_actor_concrete_actor(self); /* * Clear children */ child_count = core_vector_size(&concrete_self->child_kmers); for (i = 0; i < child_count; i++) { kmer = core_vector_at(&concrete_self->child_kmers, i); vertex = core_vector_at(&concrete_self->child_vertices, i); biosal_dna_kmer_destroy(kmer, &concrete_self->memory_pool); biosal_assembly_vertex_destroy(vertex); } concrete_self->current_child = 0; core_vector_clear(&concrete_self->child_kmers); core_vector_clear(&concrete_self->child_vertices); /* * Clear parents */ parent_count = core_vector_size(&concrete_self->parent_kmers); for (i = 0; i < parent_count; i++) { kmer = core_vector_at(&concrete_self->parent_kmers, i); vertex = core_vector_at(&concrete_self->parent_vertices, i); biosal_dna_kmer_destroy(kmer, &concrete_self->memory_pool); biosal_assembly_vertex_destroy(vertex); } concrete_self->current_parent =0; core_vector_clear(&concrete_self->parent_kmers); core_vector_clear(&concrete_self->parent_vertices); } void biosal_unitig_walker_dump_path(struct thorium_actor *self) { struct biosal_unitig_walker *concrete_self; char *sequence; #ifdef DEBUG_PATH_NAMES int start_position; #endif int left_path_arcs; int right_path_arcs; int sequence_length; struct core_memory_pool *ephemeral_memory; int position; int i; char nucleotide; int code; uint64_t path_name; struct biosal_path_status *bucket; int victory; uint64_t signature; concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); left_path_arcs = core_vector_size(&concrete_self->left_path); right_path_arcs = core_vector_size(&concrete_self->right_path); sequence_length = 0; #if 0 printf("DEBUG dump_path() kmer_length %d left_path_arcs %d right_path_arcs %d\n", concrete_self->kmer_length, left_path_arcs, right_path_arcs); #endif sequence_length += concrete_self->kmer_length; sequence_length += left_path_arcs; sequence_length += right_path_arcs; sequence = core_memory_pool_allocate(ephemeral_memory, sequence_length + 1); position = 0; /* * On the left */ for (i = left_path_arcs - 1 ; i >= 0; --i) { code = core_vector_at_as_int(&concrete_self->left_path, i); nucleotide = biosal_dna_codec_get_nucleotide_from_code(code); sequence[position] = nucleotide; ++position; } CORE_DEBUGGER_ASSERT(position == left_path_arcs); /* * Starting kmer. */ biosal_dna_kmer_get_sequence(&concrete_self->starting_kmer, sequence + position, concrete_self->kmer_length, &concrete_self->codec); #ifdef DEBUG_PATH_NAMES start_position = position; #endif #ifdef HIGHLIGH_STARTING_POINT biosal_dna_helper_set_lower_case(sequence, position, position + concrete_self->kmer_length - 1); #endif position += concrete_self->kmer_length; /* * And on the right. */ for (i = 0 ; i < right_path_arcs; i++) { code = core_vector_at_as_int(&concrete_self->right_path, i); nucleotide = biosal_dna_codec_get_nucleotide_from_code(code); sequence[position] = nucleotide; ++position; } CORE_DEBUGGER_ASSERT(position == sequence_length); sequence[sequence_length] = '\0'; /* * If the sequence is a cycle, normalize it. * Plasmid and virus can be simple circles. * * Although bacteria have in general a circular chromosome, * they are complex enough not to generate one single circle in * the graph. */ if (concrete_self->current_is_circular) { biosal_unitig_walker_normalize_cycle(self, sequence_length, sequence); } /* * Select the good strand. */ biosal_unitig_walker_select_strand(self, sequence_length, sequence); path_name = biosal_unitig_walker_get_path_name(self, sequence_length, sequence); bucket = core_map_get(&concrete_self->path_statuses, &concrete_self->path_index); CORE_DEBUGGER_ASSERT(bucket != NULL); victory = 0; bucket->length_in_nucleotides = sequence_length; #ifdef CORE_DEBUGGER_ENABLE_ASSERT if (!(bucket->status == PATH_STATUS_IN_PROGRESS_WITH_CHALLENGERS || bucket->status == PATH_STATUS_IN_PROGRESS_WITHOUT_CHALLENGERS || bucket->status == PATH_STATUS_DEFEAT_WITH_CHALLENGER || bucket->status == PATH_STATUS_DEFEAT_BY_FAILED_CHALLENGE)) { printf("Error status %d\n", bucket->status); } #endif CORE_DEBUGGER_ASSERT(bucket->status == PATH_STATUS_IN_PROGRESS_WITH_CHALLENGERS || bucket->status == PATH_STATUS_IN_PROGRESS_WITHOUT_CHALLENGERS || bucket->status == PATH_STATUS_DEFEAT_WITH_CHALLENGER || bucket->status == PATH_STATUS_DEFEAT_BY_FAILED_CHALLENGE); if (sequence_length < MINIMUM_PATH_LENGTH_IN_NUCLEOTIDES) { bucket->status = PATH_STATUS_DEFEAT_BY_SHORT_LENGTH; victory = 0; } /* * Convert in-progress status to victory status. */ if (bucket->status == PATH_STATUS_IN_PROGRESS_WITHOUT_CHALLENGERS) { #if 0 printf("actor/%d path %d sequence_length %d PATH_STATUS_IN_PROGRESS_WITHOUT_CHALLENGERS\n", thorium_actor_name(self), concrete_self->path_index, sequence_length); #endif bucket->status = PATH_STATUS_VICTORY_WITHOUT_CHALLENGERS; victory = 1; } else if (bucket->status == PATH_STATUS_IN_PROGRESS_WITH_CHALLENGERS) { #if 0 printf("actor %d path %d sequence_length %d PATH_STATUS_IN_PROGRESS_WITH_CHALLENGERS\n", thorium_actor_name(self), concrete_self->path_index, sequence_length); #endif bucket->status = PATH_STATUS_VICTORY_WITH_CHALLENGERS; victory = 1; } #if 0 if (!victory) { printf("%d sequence_length %d not victorious -> %d\n", thorium_actor_name(self), sequence_length, *bucket); } #endif if (concrete_self->current_is_circular) { #if 0 victory = 0; bucket->status = PATH_STATUS_DUPLICATE_VERTEX; #endif if (victory) { printf("DEBUG current_is_circular name= %" PRIu64 " sequence_length= %d victory %d\n", path_name, sequence_length, victory); } } if (victory && sequence_length >= MINIMUM_PATH_LENGTH_IN_NUCLEOTIDES) { #ifdef DEBUG_PATH_NAMES printf("DEBUG path_name= %" PRIu64 " path_length= %d start_position= %d\n", path_name, sequence_length, start_position); #endif signature = core_hash_data_uint64_t(sequence, sequence_length, SIGNATURE_SEED); biosal_unitig_walker_write(self, path_name, sequence, sequence_length, concrete_self->current_is_circular, signature); } core_memory_pool_free(ephemeral_memory, sequence); core_vector_resize(&concrete_self->left_path, 0); core_vector_resize(&concrete_self->right_path, 0); biosal_dna_kmer_destroy(&concrete_self->starting_kmer, &concrete_self->memory_pool); biosal_assembly_vertex_destroy(&concrete_self->starting_vertex); core_set_clear(&concrete_self->visited); concrete_self->current_is_circular = 0; /* * Update path index */ ++concrete_self->path_index; } int biosal_unitig_walker_select(struct thorium_actor *self, int *output_status) { struct biosal_unitig_walker *concrete_self; int i; int size; struct biosal_assembly_vertex *vertex; int is_unitig_vertex; int choice; int status; struct core_vector *selected_kmers; struct core_vector *selected_vertices; choice = BIOSAL_HEURISTIC_CHOICE_NONE; status = STATUS_NO_STATUS; concrete_self = thorium_actor_concrete_actor(self); /*ephemeral_memory = thorium_actor_get_ephemeral_memory(self);*/ if (concrete_self->select_operation == OPERATION_SELECT_CHILD) { selected_vertices = &concrete_self->child_vertices; selected_kmers = &concrete_self->child_kmers; } else /*if (concrete_self->select_operation == OPERATION_SELECT_PARENT) */{ selected_vertices = &concrete_self->parent_vertices; selected_kmers = &concrete_self->parent_kmers; } size = core_vector_size(selected_vertices); status = STATUS_NOT_UNITIG_VERTEX; for (i = 0; i < size; ++i) { vertex = core_vector_at(selected_vertices, i); is_unitig_vertex = biosal_assembly_vertex_get_flag(vertex, BIOSAL_VERTEX_FLAG_UNITIG); if (is_unitig_vertex) { choice = i; status = STATUS_WITH_CHOICE; break; } } /* * Make sure that the choice is not already in the unitig. */ biosal_unitig_walker_check_usage(self, &choice, &status, selected_kmers); *output_status = status; return choice; } int biosal_unitig_walker_select_old_version(struct thorium_actor *self, int *output_status) { int choice; int status; int parent_choice; int child_choice; struct biosal_unitig_walker *concrete_self; int current_coverage; int parent_size; int child_size; int i; int code; char nucleotide; struct biosal_assembly_vertex *vertex; int coverage; struct core_memory_pool *ephemeral_memory; struct core_vector *selected_vertices; struct core_vector *selected_kmers; struct core_vector parent_coverage_values; struct core_vector child_coverage_values; struct core_vector *selected_path; int size; int print_status; struct biosal_path_status *bucket; status = STATUS_NO_STATUS; /* * This code select the best edge for a unitig. */ concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); if (concrete_self->select_operation == OPERATION_SELECT_CHILD) { selected_vertices = &concrete_self->child_vertices; selected_kmers = &concrete_self->child_kmers; selected_path = &concrete_self->right_path; } else /*if (concrete_self->select_operation == OPERATION_SELECT_PARENT) */{ selected_vertices = &concrete_self->parent_vertices; selected_kmers = &concrete_self->parent_kmers; selected_path = &concrete_self->left_path; } current_coverage = biosal_assembly_vertex_coverage_depth(&concrete_self->current_vertex); size = core_vector_size(selected_vertices); /* * Get the selected parent */ parent_size = core_vector_size(&concrete_self->parent_vertices); core_vector_init(&parent_coverage_values, sizeof(int)); core_vector_set_memory_pool(&parent_coverage_values, ephemeral_memory); for (i = 0; i < parent_size; i++) { vertex = core_vector_at(&concrete_self->parent_vertices, i); coverage = biosal_assembly_vertex_coverage_depth(vertex); core_vector_push_back(&parent_coverage_values, &coverage); } parent_choice = biosal_unitig_heuristic_select(&concrete_self->heuristic, current_coverage, &parent_coverage_values); /* * Select the child. */ child_size = core_vector_size(&concrete_self->child_vertices); core_vector_init(&child_coverage_values, sizeof(int)); core_vector_set_memory_pool(&child_coverage_values, ephemeral_memory); for (i = 0; i < child_size; i++) { vertex = core_vector_at(&concrete_self->child_vertices, i); coverage = biosal_assembly_vertex_coverage_depth(vertex); core_vector_push_back(&child_coverage_values, &coverage); } /* * Use the heuristic to make the call. */ child_choice = biosal_unitig_heuristic_select(&concrete_self->heuristic, current_coverage, &child_coverage_values); /* * Pick up the choice. */ if (concrete_self->select_operation == OPERATION_SELECT_PARENT) choice = parent_choice; else choice = child_choice; /* * Explain the choice */ if (choice == BIOSAL_HEURISTIC_CHOICE_NONE) { if (size == 0) status = STATUS_NO_EDGE; else status = STATUS_IMPOSSIBLE_CHOICE; } else { status = STATUS_WITH_CHOICE; } /* * Check symmetry. */ biosal_unitig_walker_check_symmetry(self, parent_choice, child_choice, &choice, &status); /* * Verify agreement */ biosal_unitig_walker_check_agreement(self, parent_choice, child_choice, &choice, &status); /* * Make sure that the choice is not already in the unitig. */ biosal_unitig_walker_check_usage(self, &choice, &status, selected_kmers); #if 0 /* * Avoid an infinite loop since this select function is just * a test. */ if (core_vector_size(&concrete_self->left_path) >= 100000) { choice = BIOSAL_HEURISTIC_CHOICE_NONE; } #endif print_status = 0; if (core_vector_size(selected_path) > 1000) print_status = 1; /* * Don't print status if everything went fine. */ if (choice != BIOSAL_HEURISTIC_CHOICE_NONE) print_status = 0; if (print_status) { printf("actor %d path_index %d Notice: can not select, current_coverage %d, selected_path.size %d", thorium_actor_name(self), concrete_self->path_index, current_coverage, (int)core_vector_size(selected_path)); /* * Print edges. */ printf(", %d parents: ", parent_size); for (i = 0; i < parent_size; i++) { code = biosal_assembly_vertex_get_parent(&concrete_self->current_vertex, i); coverage = core_vector_at_as_int(&parent_coverage_values, i); nucleotide = biosal_dna_codec_get_nucleotide_from_code(code); printf(" (%c %d)", nucleotide, coverage); } printf(", %d children: ", child_size); for (i = 0; i < child_size; i++) { code = biosal_assembly_vertex_get_child(&concrete_self->current_vertex, i); coverage = core_vector_at_as_int(&child_coverage_values, i); nucleotide = biosal_dna_codec_get_nucleotide_from_code(code); printf(" (%c %d)", nucleotide, coverage); } printf("\n"); printf("operation= "); if (concrete_self->select_operation == OPERATION_SELECT_CHILD) printf("OPERATION_SELECT_CHILD"); else printf("OPERATION_SELECT_PARENT"); printf(" status= "); CORE_DEBUGGER_ASSERT(status != STATUS_WITH_CHOICE && status != STATUS_NO_STATUS); if (status == STATUS_NO_EDGE) printf("STATUS_NO_EDGE"); else if (status == STATUS_ALREADY_VISITED) printf("STATUS_ALREADY_VISITED"); else if (status == STATUS_NOT_REGULAR) printf("STATUS_NOT_REGULAR"); else if (status == STATUS_IMPOSSIBLE_CHOICE) printf("STATUS_IMPOSSIBLE_CHOICE"); else if (status == STATUS_DISAGREEMENT) printf("STATUS_DISAGREEMENT"); else if (status == STATUS_DEFEAT) printf("STATUS_DEFEAT"); printf("\n"); } core_vector_destroy(&parent_coverage_values); core_vector_destroy(&child_coverage_values); /* * Check for defeat. */ bucket = core_map_get(&concrete_self->path_statuses, &concrete_self->path_index); if (bucket->status == PATH_STATUS_DEFEAT_WITH_CHALLENGER || bucket->status == PATH_STATUS_DEFEAT_BY_FAILED_CHALLENGE) { choice = BIOSAL_HEURISTIC_CHOICE_NONE; status = STATUS_DEFEAT; } CORE_DEBUGGER_ASSERT(status != STATUS_NO_STATUS); CORE_DEBUGGER_ASSERT(choice == BIOSAL_HEURISTIC_CHOICE_NONE || (0 <= choice && choice < size)); *output_status = status; return choice; } void biosal_unitig_walker_write(struct thorium_actor *self, uint64_t name, char *sequence, int sequence_length, int circular, uint64_t signature) { struct biosal_unitig_walker *concrete_self; int column_width; char *buffer; struct core_memory_pool *ephemeral_memory; int block_length; int i; size_t required; size_t position; char *message_buffer; /* * \see http://en.wikipedia.org/wiki/FASTA_format */ concrete_self = thorium_actor_concrete_actor(self); column_width = 80; ephemeral_memory = thorium_actor_get_ephemeral_memory(self); buffer = core_memory_pool_allocate(ephemeral_memory, column_width + 1); required = 0; #if 0 printf("LENGTH=%d\n", sequence_length); #endif /* * Calculate the required size. */ required += snprintf(NULL, 0, ">path_%" PRIu64 " length=%d circular=%d signature=%" PRIx64 "\n", name, sequence_length, circular, signature); i = 0; while (i < sequence_length) { block_length = sequence_length - i; if (column_width < block_length) { block_length = column_width; } core_memory_copy(buffer, sequence + i, block_length); buffer[block_length] = '\0'; required += snprintf(NULL, 0, "%s\n", buffer); i += block_length; } /* * Generate message. */ message_buffer = thorium_actor_allocate(self, required + 1); position = 0; position += sprintf(message_buffer + position, ">path_%" PRIu64 " length=%d circular=%d signature=%" PRIx64 "\n", name, sequence_length, circular, signature); i = 0; while (i < sequence_length) { block_length = sequence_length - i; if (column_width < block_length) { block_length = column_width; } core_memory_copy(buffer, sequence + i, block_length); buffer[block_length] = '\0'; position += sprintf(message_buffer + position, "%s\n", buffer); i += block_length; } CORE_DEBUGGER_ASSERT(position == required); thorium_actor_send_buffer(self, concrete_self->writer_process, ACTION_WRITE, position, message_buffer); core_memory_pool_free(ephemeral_memory, buffer); } void biosal_unitig_walker_make_decision(struct thorium_actor *self) { struct biosal_dna_kmer *kmer; struct biosal_assembly_vertex *vertex; int choice; void *key; struct biosal_unitig_walker *concrete_self; struct core_vector *selected_vertices; struct core_vector *selected_kmers; struct core_vector *selected_output_path; struct core_memory_pool *ephemeral_memory; int code; int old_size; int status; int remove_irregular_vertices; remove_irregular_vertices = 1; concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); /* * Select a choice and carry on... */ status = STATUS_NO_STATUS; choice = biosal_unitig_walker_select(self, &status); /* * If the thing is circular, don't do anything else. */ if (concrete_self->select_operation == OPERATION_SELECT_PARENT) { if (concrete_self->current_is_circular) { status = STATUS_CYCLE; choice = BIOSAL_HEURISTIC_CHOICE_NONE; } } CORE_DEBUGGER_ASSERT(status != STATUS_NO_STATUS); if (concrete_self->select_operation == OPERATION_SELECT_CHILD) { selected_vertices = &concrete_self->child_vertices; selected_kmers = &concrete_self->child_kmers; selected_output_path = &concrete_self->right_path; } else /* if (concrete_self->select_operation == OPERATION_SELECT_PARENT)*/ { selected_vertices = &concrete_self->parent_vertices; selected_kmers = &concrete_self->parent_kmers; selected_output_path = &concrete_self->left_path; } /* * Proceed with the choice * (this is either for OPERATION_SELECT_CHILD or OPERATION_SELECT_PARENT). */ if (choice != BIOSAL_HEURISTIC_CHOICE_NONE) { CORE_DEBUGGER_ASSERT(status == STATUS_WITH_CHOICE); /* coverage = biosal_assembly_vertex_coverage_depth(&concrete_self->current_vertex); */ if (concrete_self->select_operation == OPERATION_SELECT_CHILD) { code = biosal_assembly_vertex_get_child(&concrete_self->current_vertex, choice); } else if (concrete_self->select_operation == OPERATION_SELECT_PARENT) { code = biosal_assembly_vertex_get_parent(&concrete_self->current_vertex, choice); } /* * Add the choice to the list. */ kmer = core_vector_at(selected_kmers, choice); vertex = core_vector_at(selected_vertices, choice); core_vector_push_back(selected_output_path, &code); key = core_memory_pool_allocate(ephemeral_memory, concrete_self->key_length); biosal_dna_kmer_pack(kmer, key, concrete_self->kmer_length, &concrete_self->codec); core_set_add(&concrete_self->visited, key); #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("Added (%d)\n", (int)core_set_size(&concrete_self->visited)); biosal_dna_kmer_print(kmer, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); #endif #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("coverage= %d, path now has %d arcs\n", coverage, (int)core_vector_size(&concrete_self->path)); #endif /* * Mark the vertex. */ biosal_unitig_walker_mark_vertex(self, kmer); /* * Whenever a choice is made, the vertex is marked as visited. */ biosal_unitig_walker_set_current(self, kmer, vertex); biosal_unitig_walker_clear(self); core_memory_pool_free(ephemeral_memory, key); } else if (concrete_self->select_operation == OPERATION_SELECT_CHILD) { /* * Remove the last one because it is not a "easy" vertex. */ old_size = core_vector_size(&concrete_self->right_path); if (old_size > 0 && (status == STATUS_NOT_REGULAR || status == STATUS_DISAGREEMENT) && remove_irregular_vertices) { core_vector_resize(&concrete_self->right_path, old_size - 1); } /* * Switch now to OPERATION_SELECT_PARENT */ concrete_self->select_operation = OPERATION_SELECT_PARENT; /* * Change the current vertex. */ biosal_unitig_walker_set_current(self, &concrete_self->starting_kmer, &concrete_self->starting_vertex); biosal_unitig_walker_clear(self); thorium_actor_send_to_self_empty(self, ACTION_ASSEMBLY_GET_VERTICES_AND_SELECT); /* Finish */ } else if (concrete_self->select_operation == OPERATION_SELECT_PARENT) { /* * Remove the last one because it is not a "easy" vertex. */ old_size = core_vector_size(&concrete_self->left_path); if (old_size > 0 && (status == STATUS_NOT_REGULAR || status == STATUS_DISAGREEMENT) && remove_irregular_vertices) { core_vector_resize(&concrete_self->left_path, old_size - 1); } biosal_dna_kmer_destroy(&concrete_self->current_kmer, &concrete_self->memory_pool); biosal_assembly_vertex_destroy(&concrete_self->current_vertex); biosal_unitig_walker_clear(self); concrete_self->select_operation = OPERATION_SELECT_CHILD; thorium_actor_send_to_self_empty(self, ACTION_ASSEMBLY_GET_VERTICES_AND_SELECT_REPLY); } } void biosal_unitig_walker_set_current(struct thorium_actor *self, struct biosal_dna_kmer *kmer, struct biosal_assembly_vertex *vertex) { struct biosal_unitig_walker *concrete_self; concrete_self = thorium_actor_concrete_actor(self); biosal_dna_kmer_destroy(&concrete_self->current_kmer, &concrete_self->memory_pool); biosal_dna_kmer_init_copy(&concrete_self->current_kmer, kmer, concrete_self->kmer_length, &concrete_self->memory_pool, &concrete_self->codec); biosal_assembly_vertex_destroy(&concrete_self->current_vertex); biosal_assembly_vertex_init_copy(&concrete_self->current_vertex, vertex); } uint64_t biosal_unitig_walker_get_path_name(struct thorium_actor *self, int length, char *sequence) { struct biosal_dna_kmer kmer1; uint64_t hash_value1; struct biosal_dna_kmer kmer2; uint64_t hash_value2; struct biosal_unitig_walker *concrete_self; char *kmer_sequence; char saved_symbol; struct core_memory_pool *ephemeral_memory; uint64_t name; /* * Get a path name. * To do it, the first and last kmers are selected. * The canonical hash of each of them is computed. * And finally the lower hash value is used for the name. */ concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); /* * Get the left hash value. */ kmer_sequence = sequence; saved_symbol = kmer_sequence[concrete_self->kmer_length]; kmer_sequence[concrete_self->kmer_length] = '\0'; biosal_dna_kmer_init(&kmer1, kmer_sequence, &concrete_self->codec, ephemeral_memory); kmer_sequence[concrete_self->kmer_length] = saved_symbol; hash_value1 = biosal_dna_kmer_canonical_hash(&kmer1, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); /* * Get the second hash value. */ CORE_DEBUGGER_ASSERT(concrete_self->kmer_length <= length); kmer_sequence = sequence + length - concrete_self->kmer_length; biosal_dna_kmer_init(&kmer2, kmer_sequence, &concrete_self->codec, ephemeral_memory); hash_value2 = biosal_dna_kmer_canonical_hash(&kmer2, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); name = hash_value1; if (biosal_dna_kmer_is_lower(&kmer2, &kmer1, concrete_self->kmer_length, &concrete_self->codec)) { name = hash_value2; } biosal_dna_kmer_destroy(&kmer1, ephemeral_memory); biosal_dna_kmer_destroy(&kmer2, ephemeral_memory); /* * Return the lowest value. */ return name; } void biosal_unitig_walker_check_symmetry(struct thorium_actor *self, int parent_choice, int child_choice, int *choice, int *status) { /* * Enforce mathematical symmetry. */ if (parent_choice == BIOSAL_HEURISTIC_CHOICE_NONE || child_choice == BIOSAL_HEURISTIC_CHOICE_NONE) { *choice = BIOSAL_HEURISTIC_CHOICE_NONE; *status = STATUS_NOT_REGULAR; } } void biosal_unitig_walker_check_agreement(struct thorium_actor *self, int parent_choice, int child_choice, int *choice, int *status) { struct biosal_unitig_walker *concrete_self; int right_path_size; int left_path_size; int parent_code; int child_code; int expected_parent_code; int expected_child_code; int previous_position; if (*choice == BIOSAL_HEURISTIC_CHOICE_NONE) { return; } concrete_self = thorium_actor_concrete_actor(self); /* * Verify that there ris no disagreement * (STATUS_DISAGREEMENT). */ /* * This goes from left to right. */ if (concrete_self->select_operation == OPERATION_SELECT_CHILD) { right_path_size = core_vector_size(&concrete_self->right_path); if (right_path_size >= 1) { previous_position = right_path_size - concrete_self->kmer_length - 1; /* * This is in the starting kmer. */ if (previous_position < 0) { previous_position += concrete_self->kmer_length; expected_parent_code = biosal_dna_kmer_get_symbol(&concrete_self->starting_kmer, previous_position, concrete_self->kmer_length, &concrete_self->codec); } else { expected_parent_code = core_vector_at_as_int(&concrete_self->right_path, previous_position); } parent_code = biosal_assembly_vertex_get_parent(&concrete_self->current_vertex, parent_choice); child_code = biosal_assembly_vertex_get_child(&concrete_self->current_vertex, child_choice); if (parent_code != expected_parent_code) { #if 0 printf("DEBUG STATUS_DISAGREEMENT child actual %d expected %d", parent_code, expected_parent_code); printf(" MISMATCH"); printf("\n"); #endif *choice = BIOSAL_HEURISTIC_CHOICE_NONE; *status = STATUS_DISAGREEMENT; } } #if 0 tail_size = 5; if (right_path_size >= concrete_self->kmer_length + tail_size) { printf("actor/%d Test for STATUS_DISAGREEMENT parent_choice_code= %d child_choice_code= %d right_path_size %d last %d codes: [", thorium_actor_name(self), parent_code, child_code, right_path_size, tail_size); for (i = 0; i < tail_size; ++i) { other_code = core_vector_at_as_int(&concrete_self->right_path, right_path_size - concrete_self->kmer_length - tail_size + i); printf(" %d", other_code); } printf("]\n"); } #endif /* * Validate from right to left. */ } else if (concrete_self->select_operation == OPERATION_SELECT_PARENT) { left_path_size = core_vector_size(&concrete_self->left_path); if (left_path_size >= 1) { previous_position = left_path_size - concrete_self->kmer_length - 1; /* * The previous one is in the starting kmer. */ if (previous_position < 0) { previous_position += concrete_self->kmer_length; /* * Invert the polarity of the bio object. */ previous_position = concrete_self->kmer_length - 1 - previous_position; expected_child_code = biosal_dna_kmer_get_symbol(&concrete_self->starting_kmer, previous_position, concrete_self->kmer_length, &concrete_self->codec); } else { expected_child_code = core_vector_at_as_int(&concrete_self->left_path, previous_position); } parent_code = biosal_assembly_vertex_get_parent(&concrete_self->current_vertex, parent_choice); child_code = biosal_assembly_vertex_get_child(&concrete_self->current_vertex, child_choice); if (child_code != expected_child_code) { #if 0 printf("DEBUG STATUS_DISAGREEMENT parent actual %d expected %d", child_code, expected_child_code); printf(" MISMATCH"); printf("\n"); #endif *choice = BIOSAL_HEURISTIC_CHOICE_NONE; *status = STATUS_DISAGREEMENT; } } } } void biosal_unitig_walker_check_usage(struct thorium_actor *self, int *choice, int *status, struct core_vector *selected_kmers) { int found; struct biosal_dna_kmer *kmer; void *key; struct core_memory_pool *ephemeral_memory; struct biosal_unitig_walker *concrete_self; /* * Verify if it was visited already. */ if (*choice == BIOSAL_HEURISTIC_CHOICE_NONE) { return; } concrete_self = thorium_actor_concrete_actor(self); found = 0; ephemeral_memory = thorium_actor_get_ephemeral_memory(self); key = core_memory_pool_allocate(ephemeral_memory, concrete_self->key_length); kmer = core_vector_at(selected_kmers, *choice); biosal_dna_kmer_pack_store_key(kmer, key, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); found = core_set_find(&concrete_self->visited, key); #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("Find result %d\n", found); biosal_dna_kmer_print(kmer, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); #endif if (found) { printf("This one was already visited:\n"); biosal_dna_kmer_print(kmer, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); printf("Starting kmer\n"); biosal_dna_kmer_print(&concrete_self->starting_kmer, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); concrete_self->current_is_circular = 1; *choice = BIOSAL_HEURISTIC_CHOICE_NONE; *status = STATUS_ALREADY_VISITED; } #ifdef BIOSAL_UNITIG_WALKER_DEBUG printf("Choice is %d\n", choice); #endif core_memory_pool_free(ephemeral_memory, key); } int biosal_unitig_walker_get_current_length(struct thorium_actor *self) { struct biosal_unitig_walker *concrete_self; int length; concrete_self = thorium_actor_concrete_actor(self); length = 0; length += concrete_self->kmer_length; length += core_vector_size(&concrete_self->left_path); length += core_vector_size(&concrete_self->right_path); return length; } void biosal_unitig_walker_mark_vertex(struct thorium_actor *self, struct biosal_dna_kmer *kmer) { int new_count; int store_index; int store; int position; char *new_buffer; struct thorium_message new_message; struct biosal_unitig_walker *concrete_self; struct core_memory_pool *ephemeral_memory; concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); /* * Send the marker to the graph store. */ new_count = biosal_dna_kmer_pack_size(kmer, concrete_self->kmer_length, &concrete_self->codec); new_count += sizeof(concrete_self->path_index); new_buffer = thorium_actor_allocate(self, new_count); position = 0; position += biosal_dna_kmer_pack(kmer, new_buffer, concrete_self->kmer_length, &concrete_self->codec); core_memory_copy(new_buffer + position, &concrete_self->path_index, sizeof(concrete_self->path_index)); position += sizeof(concrete_self->path_index); CORE_DEBUGGER_ASSERT(position == new_count); store_index = biosal_dna_kmer_store_index(kmer, core_vector_size(&concrete_self->graph_stores), concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); store = core_vector_at_as_int(&concrete_self->graph_stores, store_index); thorium_message_init(&new_message, ACTION_MARK_VERTEX_AS_VISITED, new_count, new_buffer); thorium_actor_send(self, store, &new_message); thorium_message_destroy(&new_message); } void biosal_unitig_walker_normalize_cycle(struct thorium_actor *self, int length, char *sequence) { int i; int selected_start; struct biosal_dna_kmer selected_kmer; int selected_is_canonical; char saved_symbol; struct biosal_dna_kmer kmer1; struct biosal_unitig_walker *concrete_self; struct core_memory_pool *ephemeral_memory; char *kmer_sequence; concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); selected_start = -1; selected_is_canonical = -1; /* * Find the canonical kmer with the lowest hash. * * N nucleotides = (N - k + 1) vertices */ biosal_dna_kmer_init_empty(&selected_kmer); for (i = 0; i < length - concrete_self->kmer_length + 1; ++i) { kmer_sequence = sequence + i; saved_symbol = kmer_sequence[concrete_self->kmer_length]; kmer_sequence[concrete_self->kmer_length] = '\0'; biosal_dna_kmer_init(&kmer1, kmer_sequence, &concrete_self->codec, ephemeral_memory); kmer_sequence[concrete_self->kmer_length] = saved_symbol; /* hash_value1 = biosal_dna_kmer_canonical_hash(&kmer1, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); */ if (selected_start == -1 || biosal_dna_kmer_is_lower(&kmer1, &selected_kmer, concrete_self->kmer_length, &concrete_self->codec)) { selected_start = i; selected_is_canonical = biosal_dna_kmer_is_canonical(&kmer1, concrete_self->kmer_length, &concrete_self->codec); biosal_dna_kmer_destroy(&selected_kmer, ephemeral_memory); biosal_dna_kmer_init_copy(&selected_kmer, &kmer1, concrete_self->kmer_length, ephemeral_memory, &concrete_self->codec); } biosal_dna_kmer_destroy(&kmer1, ephemeral_memory); } /* * at this point, do some rotation. */ printf("DEBUG CYCLE biosal_unitig_walker_normalize_cycle length= %d selected_start= %d selected_is_canonical= %d\n", length, selected_start, selected_is_canonical); biosal_dna_kmer_destroy(&selected_kmer, ephemeral_memory); printf("CYCLE before %s\n", sequence); core_string_rotate_path(sequence, length, selected_start, concrete_self->kmer_length, ephemeral_memory); printf("CYCLE after %s\n", sequence); } void biosal_unitig_walker_select_strand(struct thorium_actor *self, int length, char *sequence) { struct biosal_dna_kmer kmer1; struct biosal_dna_kmer kmer2; char *kmer_sequence; char saved_symbol; struct core_memory_pool *ephemeral_memory; struct biosal_unitig_walker *concrete_self; concrete_self = thorium_actor_concrete_actor(self); ephemeral_memory = thorium_actor_get_ephemeral_memory(self); /* * Get the first kmer. */ kmer_sequence = sequence; saved_symbol = kmer_sequence[concrete_self->kmer_length]; kmer_sequence[concrete_self->kmer_length] = '\0'; biosal_dna_kmer_init(&kmer1, kmer_sequence, &concrete_self->codec, ephemeral_memory); kmer_sequence[concrete_self->kmer_length] = saved_symbol; CORE_DEBUGGER_ASSERT(concrete_self->kmer_length <= length); /* * Get the second kmer. */ kmer_sequence = sequence + length - concrete_self->kmer_length; biosal_dna_kmer_init(&kmer2, kmer_sequence, &concrete_self->codec, ephemeral_memory); biosal_dna_kmer_reverse_complement_self(&kmer2, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); if (length == 6936) { printf("DEBUG_6936 ends\n"); biosal_dna_kmer_print(&kmer1, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); biosal_dna_kmer_print(&kmer2, concrete_self->kmer_length, &concrete_self->codec, ephemeral_memory); } if (biosal_dna_kmer_is_lower(&kmer2, &kmer1, concrete_self->kmer_length, &concrete_self->codec)) { biosal_dna_helper_reverse_complement_in_place(sequence); } biosal_dna_kmer_destroy(&kmer1, ephemeral_memory); biosal_dna_kmer_destroy(&kmer2, ephemeral_memory); }
32.781895
140
0.677139
[ "object" ]
36837a67fb87f58ba0d1677c00d252410c30af58
4,452
h
C
Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2021-08-08T19:54:51.000Z
2021-08-08T19:54:51.000Z
Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
3
2021-09-08T03:41:27.000Z
2022-03-12T01:01:29.000Z
Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h> #include <Atom/Feature/CoreLights/PhotometricValue.h> #include <Atom/Feature/Utils/GpuBufferHandler.h> #include <Atom/Feature/Utils/IndexedDataVector.h> #include <Shadows/ProjectedShadowFeatureProcessor.h> namespace AZ { class Vector3; class Color; namespace Render { class DiskLightFeatureProcessor final : public DiskLightFeatureProcessorInterface { public: AZ_RTTI(AZ::Render::DiskLightFeatureProcessor, "{F69C0188-2C1C-47A5-8187-17433C34AC2B}", AZ::Render::DiskLightFeatureProcessorInterface); static void Reflect(AZ::ReflectContext* context); DiskLightFeatureProcessor(); virtual ~DiskLightFeatureProcessor() = default; // FeatureProcessor overrides ... void Activate() override; void Deactivate() override; void Simulate(const SimulatePacket & packet) override; void Render(const RenderPacket & packet) override; // DiskLightFeatureProcessorInterface overrides ... LightHandle AcquireLight() override; bool ReleaseLight(LightHandle& handle) override; LightHandle CloneLight(LightHandle handle) override; void SetRgbIntensity(LightHandle handle, const PhotometricColor<PhotometricUnitType>& lightColor) override; void SetPosition(LightHandle handle, const AZ::Vector3& lightPosition) override; void SetDirection(LightHandle handle, const AZ::Vector3& lightDirection) override; void SetAttenuationRadius(LightHandle handle, float attenuationRadius) override; void SetDiskRadius(LightHandle handle, float radius) override; void SetConstrainToConeLight(LightHandle handle, bool useCone) override; void SetConeAngles(LightHandle handle, float innerDegrees, float outerDegrees) override; void SetShadowsEnabled(LightHandle handle, bool enabled) override; void SetShadowBias(LightHandle handle, float bias) override; void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) override; void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) override; void SetPredictionSampleCount(LightHandle handle, uint16_t count) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; void SetPcfMethod(LightHandle handle, PcfMethod method) override; void SetEsmExponent(LightHandle handle, float esmExponent) override; void SetDiskData(LightHandle handle, const DiskLightData& data) override; const Data::Instance<RPI::Buffer> GetLightBuffer()const; uint32_t GetLightCount()const; private: static constexpr const char* FeatureProcessorName = "DiskLightFeatureProcessor"; static constexpr float MaxConeRadians = AZ::DegToRad(90.0f); static constexpr float MaxProjectedShadowRadians = ProjectedShadowFeatureProcessorInterface::MaxProjectedShadowRadians * 0.5f; using ShadowId = ProjectedShadowFeatureProcessor::ShadowId; DiskLightFeatureProcessor(const DiskLightFeatureProcessor&) = delete; static void UpdateBulbPositionOffset(DiskLightData& light); void ValidateAndSetConeAngles(LightHandle handle, float innerRadians, float outerRadians); void UpdateShadow(LightHandle handle); // Convenience function for forwarding requests to the ProjectedShadowFeatureProcessor template <typename Functor, typename ParamType> void SetShadowSetting(LightHandle handle, Functor&&, ParamType&& param); ProjectedShadowFeatureProcessor* m_shadowFeatureProcessor = nullptr; IndexedDataVector<DiskLightData> m_diskLightData; GpuBufferHandler m_lightBufferHandler; bool m_deviceBufferNeedsUpdate = false; }; } // namespace Render } // namespace AZ
47.361702
149
0.713387
[ "render", "3d" ]
3686f95b1c4b1b20a598cb17becb65c72a6f3111
442
h
C
src/mappositiontile.h
Louis-Alexandre/Captain-Markov
386724030b33e3bf996897db6bcf8c7b7d8c5f84
[ "MIT" ]
2
2015-04-24T17:44:11.000Z
2017-10-29T09:47:49.000Z
src/mappositiontile.h
Louis-Alexandre/Captain-Markov
386724030b33e3bf996897db6bcf8c7b7d8c5f84
[ "MIT" ]
null
null
null
src/mappositiontile.h
Louis-Alexandre/Captain-Markov
386724030b33e3bf996897db6bcf8c7b7d8c5f84
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <vector> #include <SFML/System.hpp> // Nom de merde, donne la position de la tuile par rapport a l'arg class Map; class Tile; class MapPositionTile { public: MapPositionTile(std::shared_ptr<Map> _map); sf::Vector2i getPosition(int arg) const; int getArg(std::shared_ptr<Tile> tile) const; void makeMap(); private: std::shared_ptr<Map> map; std::vector<std::shared_ptr<Tile>> mappedTiles; };
19.217391
66
0.733032
[ "vector" ]