blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d2441da5316103dceb7e2669db13d2226be8fcae | befaf0dfc5880d18f42e1fa7e39e27f8d2f8dde9 | /SDK/SCUM_Antibiotics_02_classes.hpp | d7eedc420ccaa8a4c6fa11beb0722fdf73a4151a | [] | no_license | cpkt9762/SCUM-SDK | 0b59c99748a9e131eb37e5e3d3b95ebc893d7024 | c0dbd67e10a288086120cde4f44d60eb12e12273 | refs/heads/master | 2020-03-28T00:04:48.016948 | 2018-09-04T13:32:38 | 2018-09-04T13:32:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 673 | hpp | #pragma once
// SCUM (0.1.17.8320) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SCUM_Antibiotics_02_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Antibiotics_02.Antibiotics_02_C
// 0x0000 (0x0790 - 0x0790)
class AAntibiotics_02_C : public AMedicationItem
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass Antibiotics_02.Antibiotics_02_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
40801c636c003f341867b042cbb7cceb99014605 | 04b978bbc609e3e3d6f5e2a37f7e4f1a33530ba4 | /Partie.h | dd7e79b0c50ce057391c4afe34339fff0beed110 | [] | no_license | nicolasboulas/ServeurThread | a0da3e3e6e7d4faceb5b870bff3d5906fbaa37c6 | 055d00be52332f00db718ac555342c806d136156 | refs/heads/master | 2020-04-21T19:02:15.184759 | 2019-02-17T10:48:26 | 2019-02-17T10:48:26 | 169,791,842 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 338 | h | #pragma once
#pragma once
#include "pch.h"
#include <string>
using namespace std;
class Partie {
public:
int grille[3][3];
void init();
bool EstCordonneValide(int x, int y);
bool cocherX(int x, int y);
bool cocherO(int x, int y);
bool testO(int x, int y);
bool testX(int x, int y);
int tirage();
bool EstPartieGagne();
};
| [
"noreply@github.com"
] | noreply@github.com |
53c0a3c35bf41afb5e3c36f9d78edfd9a4571008 | bf8bd7606e57a3e01615b2ac41462c5fedccab94 | /leetcode string/reverse vowels of a string.cpp | f2a40c0f2a9529643dddd0427d2af060cf7d0a24 | [] | no_license | jamyan99/project | 1618718ef476832df0ca2e5f31bb6e9c00b957c3 | bd9ea6bb1451368a4bf0f1b106f3bb54d6ac30e8 | refs/heads/master | 2020-03-23T19:26:24.511154 | 2018-07-23T14:52:23 | 2018-07-23T14:52:23 | 141,977,717 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | class Solution {
public:
string reverseVowels(string s) {
int n, i, j, c = 0;
string word;
n = s.length();
for (i = 0; i < n && c == 0; i++){
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' || s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U'){
for (j = n - 1; j > 0 && c == 0; j--){
if (s[j] == 'a' || s[j] == 'e' || s[j] == 'i' || s[j] == 'o' || s[j] == 'u' || s[j] == 'u' || s[j] == 'A' || s[j] == 'E' || s[j] == 'I' || s[j] == 'O' || s[j] == 'U'){
swap(s[i], s[j]);
c = 1;
}
}
}
if (c == 1)
n = j + 1;
c = 0;
}
return s;
}
};
| [
"jamyan_08@yahoo.com"
] | jamyan_08@yahoo.com |
14a4682702d0b4f13ba71b11eeac37bc28e1d790 | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtbase/config.tests/unix/freetype/freetype.cpp | df686cc33c310624a9a97c19da18ed0cd2993d9c | [
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-commercial-license",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"LicenseRef-scancode-qt-commercial-1.1",
"LGPL-3.0-only",
"LicenseRef-scancode-qt-company-exception-lgpl-2.1",
... | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 1,830 | cpp | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <ft2build.h>
#include FT_FREETYPE_H
#if ((FREETYPE_MAJOR*10000 + FREETYPE_MINOR*100 + FREETYPE_PATCH) < 20110)
# error "This version of freetype is too old."
#endif
int main(int, char **)
{
FT_Face face;
face = 0;
return 0;
}
| [
"p_pavlov@wargaming.net"
] | p_pavlov@wargaming.net |
f1db5af2072ee4245ff1e9e82d2b797d1a4e717e | f9a99df0eb777e66b1830393daf20379db98f3d2 | /WaterPipe/CopyRight.h | 3b59786e1dc0cbcec2278a47f79d21a46b155580 | [] | no_license | rojama/WaterPipe | f80e0535c2e8dbfbba4730f8b77cebcf5bad7233 | aab20d6fd3bc449cba261beebae914cc0e581541 | refs/heads/master | 2021-04-26T14:38:18.535610 | 2018-02-12T06:04:20 | 2018-02-12T06:04:20 | 121,206,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | h | #pragma once
#include <mzfc_inc.h>
class CopyRight :
public CMzWndEx
{
public:
CopyRight(void);
~CopyRight(void);
protected:
UiScrollWin m_ScrollWin;
UiStatic m_Static;
UiToolbar_Text m_Toolbar;
BOOL OnInitDialog();
void OnMzCommand(WPARAM wParam, LPARAM lParam);
};
| [
"13191562+rojama@users.noreply.github.com"
] | 13191562+rojama@users.noreply.github.com |
ff6a4bb856c224a0eb02562e6de31049b2e46de0 | 9639c4451a7f2845a57931b6a670a2f744f58e0f | /ayeon/week3/bj2133.cpp | 2f1abb6fa8bc2ee735cadc500f1f0088b2a1d329 | [] | no_license | 42somoim/42somoim2 | d00a256c5ca949d89b444e1600043afac2c0c4d6 | 64c9fb657736c84d88df901e3d1662c05ddc5954 | refs/heads/master | 2023-03-24T13:42:43.489332 | 2021-03-15T13:25:57 | 2021-03-15T13:25:57 | 300,144,427 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 227 | cpp | #include <stdio.h>
int dp[31];
int main(){
int n;
scanf("%d", &n);
dp[0] = 1;
for (int i = 2; i<=n; i+=2){
dp[i] = dp[i-2]*3;
for (int j = 4; j<=i; j+=2)
dp[i] += dp[i-j]*2;
}
printf("%d\n", dp[n]);
return 0;
}
| [
"qkrskdjf@naver.com"
] | qkrskdjf@naver.com |
b69097fb64d082fa50f33ef4269f6f8ed2625e50 | e60b22b1b3171cfedccef2560ea1ff129f254152 | /SM2.cpp | ad2d3db3e3971fa77dd8d462b945021846ceac26 | [] | no_license | ttnhuy313/try-again | 0f531cac8bec5c760fb38a08a374c4c00d03160c | 037cd0c580934f021a1ae1f89500bfc8b33a8541 | refs/heads/main | 2022-12-26T23:21:43.974777 | 2020-10-06T16:56:31 | 2020-10-06T16:56:31 | 301,796,979 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 646 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int f[N], g[N];
int main(int argc, char const *argv[])
{
ios_base::sync_with_stdio(0); cin.tie(0);
freopen("SM2.INP", "r", stdin);
freopen("SM2.OUT", "w", stdout);
int tc;
cin >> tc;
for (int i = 1; i <= 1e5; ++i) {
int d = i;
while (d % 2 == 0 && d > 0) {
f[i]++;
d /= 2;
}
d = i;
while (d % 5 == 0 && d) {
g[i]++;
d /= 5;
}
f[i] += f[i - 1];
g[i] += g[i - 1];
}
while (tc--) {
int n, k;
cin >> n >> k;
cerr << f[n] - f[n - k] - f[k] << endl;
cout << min(f[n] - f[n - k] - f[k], g[n] - g[n - k] - g[k]) << endl;
}
return 0;
} | [
"39652384+ttnhuy313@users.noreply.github.com"
] | 39652384+ttnhuy313@users.noreply.github.com |
4affafc692ade9402fc6ee96c589aff937ea5b10 | eb04153da96666ec0942756d0a10d158b5b54be3 | /iotsaRT.h | 3d152d6525c682514f61c5af4b7f82e33f3de01d | [
"MIT"
] | permissive | cwi-dis/iotsaResponseTime | 69122709fd5d51f11642fe2d197915f433b20431 | 2a7dfd5d4366664120543998f0a9039cbbca8fc5 | refs/heads/master | 2022-08-08T03:25:07.401114 | 2022-08-01T08:11:37 | 2022-08-01T08:11:37 | 130,610,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | h | #ifndef _IOTSART_H_
#define _IOTSART_H_
#include "iotsa.h"
#include "iotsaApi.h"
typedef enum {stim_rise, stim_fall, stim_toggle} stimulusType;
typedef enum {resp_same, resp_reverse, resp_rise, resp_fall} responseType;
class IotsaRTMod : public IotsaApiMod {
public:
IotsaRTMod(IotsaApplication& _app, int _outPin, int _inPin)
: IotsaApiMod(_app),
outPin(_outPin),
inPin(_inPin),
stimulus(stim_rise),
response(resp_same),
duration(0),
trigger(false)
{}
void setup() override;
void serverSetup() override;
void loop() override;
String info() override;
protected:
bool getHandler(const char *path, JsonObject& reply) override;
bool putHandler(const char *path, const JsonVariant& request, JsonObject& reply) override;
void configLoad() override;
void configSave() override;
void handler();
bool canDoStimulus();
void doStimulus();
int outPin;
int inPin;
stimulusType stimulus;
responseType response;
int duration;
bool trigger;
};
#endif
| [
"Jack.Jansen@cwi.nl"
] | Jack.Jansen@cwi.nl |
6c082c9b0e21e4db99611f8570418b9559f68846 | 1bcace59faa920f8cec256917df750d41864dea9 | /twosum.cpp | 0754ae9cb5e6faf6371f4a8e851d2c13b6adc114 | [] | no_license | HugoLnx/programming-challenges | abd02f4074228dffdaa2e4ca95ea39a467a55766 | d48412b0f0c49a55e4049b7f72da5ec3057fbffa | refs/heads/master | 2021-12-14T07:48:13.540444 | 2021-12-07T22:48:19 | 2021-12-07T22:48:19 | 116,039,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | cpp | // https://leetcode.com/problems/two-sum
#include <map>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> ns;
vector<int> v(2);
for(int i = 0; i < nums.size(); i++) {
ns[nums[i]] = i+1;
}
for(int i = 0; i < nums.size(); i++) {
if(ns[target-nums[i]] && i != ns[target-nums[i]]-1) {
v[0] = i;
v[1] = ns[target-nums[i]]-1;
return v;
}
}
return v;
}
};
| [
"hugolnx@gmail.com"
] | hugolnx@gmail.com |
c80e26a8616593e6a55ffecb71e468f72e3e6b5d | 554c91f1cc7173c64ea47b4176372272292f98e8 | /sketch_dec12b/sketch_dec12b.ino | 3b6e5b326e17ca0e4341a5ede87f8c485f9babd4 | [] | no_license | MatsWallden/Arduino | 749df5065fc25977e19f1ce9b97a66ce7ee34ed9 | 132d2f5d0c55f441d7b42c03ec7967b1fe094701 | refs/heads/master | 2021-09-08T12:54:38.955229 | 2018-03-09T21:35:58 | 2018-03-09T21:35:58 | 124,569,081 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,124 | ino | #include <Wire.h>
/*Register Map*/
#define IA_ADDRESS 0x0D //IA
#define BLOCK_WRITE_CMD 0xA0 //block write command
#define BLOCK_READ_CMD 0xA1 //block read command
#define ADR_PTR_CMD 0xB0 //address pointer command
/*Register Map*/
#define CONTROL_REG 0x80
#define START_FREQUENCY_REG 0x82
#define FREQUENCY_INCREMENT_REG 0x85
#define NUM_INCREMENTS_REG 0x88
#define NUM_SETTLING_TIME_REG 0x8A
#define STATUS_REG 0x8F
#define TEMP_DATA_REG 0x92
#define REAL_DATA_REG 0x94
#define IMAG_DATA_REG 0x96
/*CONTROL REGISTER COMMANDS*/
#define INIT_START_FREQ 0x10
#define START_FREQ_SWEEP 0x20
#define INC_FREQ 0x30
#define REPEAT_FREQ 0x40
#define MEASURE_TEMP 0x90
#define PWR_DOWN 0xA0
#define STAND_BY 0xB0
void setup()
{
// initialization
Wire.begin();
Serial.begin(9600);
// send Command to Control Register
Wire.beginTransmission(IA_ADDRESS);
Wire.write(0x80);
Wire.write(0x90);
Wire.endTransmission();
// set Register Pointer to Status Register
Wire.beginTransmission(IA_ADDRESS);
Wire.write(0xB0); // WRITE TO THE POINTER
Wire.write(0x8F); // THIS IS WHERE THE MEASUREMENT HAPPENS
Wire.endTransmission();
// Read from Status Register
delay(500);
Wire.requestFrom(0x0D, 1);
uint8_t disp_status;
disp_status = Wire.read();
Wire.endTransmission();
Serial.println("Current register status is:");
Serial.println(disp_status,BIN);
// set Register Pointer to Control Register
Wire.beginTransmission(0x0D);
Wire.write(0xB0);
Wire.write(0x80);
Wire.endTransmission();
delay(20);
// Read from Status Register
delay(500);
Wire.requestFrom(0x0D, 1);
uint8_t disp_control;
disp_control = Wire.read();
Wire.endTransmission();
Serial.println("Current control register is:");
Serial.println(disp_control,BIN);
}
void loop()
{
}
| [
"wallden.mats@gmail.com"
] | wallden.mats@gmail.com |
2ace94f81f1791a0a2c56d97affc73b92e0a656d | 7e4895025ddf4d17147596508026ccd7d824f1bd | /hmrM2500_Ontake/hmLib_v3_04/filterbuf.hpp | 260b3b4355bb5a59af798ac7d18ff93f61ab491c | [] | no_license | HomuraVehicle/HomuraMachine_Ontake | 23effe3fe993c1e06fd64888e7afb83ef9e8346f | ba9ef38885801379e9d19c9be262511104b4fba1 | refs/heads/master | 2020-04-02T13:10:52.137985 | 2016-08-06T07:48:28 | 2016-08-06T07:48:28 | 64,088,198 | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 2,938 | hpp | #ifndef HMLIB_FILTERBUF_INC
#define HMLIB_FILTERBUF_INC 102
#
/*===filterbuf===
filterbuf_v1_02/130101 hmIto
iostreamé╔Ĺ╬ë×
*/
#include<streambuf>
#include<iostream>
namespace hmLib{
template<class _Elem,class _Traits=std::char_traits<_Elem>>
class basic_filterbuf{
protected:
typedef std::basic_istream<_Elem,_Traits> istream;
typedef std::basic_ostream<_Elem,_Traits> ostream;
typedef std::basic_iostream<_Elem,_Traits> iostream;
typedef basic_filterbuf<_Elem,_Traits> my_type;
typedef std::ios::pos_type pos_type;
typedef std::ios::off_type off_type;
private:
iostream* ptr_io;
istream* ptr_i;
ostream* ptr_o;
public:
basic_filterbuf()
:ptr_io(nullptr)
,ptr_o(nullptr)
,ptr_i(nullptr){
}
basic_filterbuf(iostream& io_)
:ptr_io(&io_)
,ptr_o(&io_)
,ptr_i(&io_){
}
basic_filterbuf(istream& in_)
:ptr_io(nullptr)
,ptr_o(nullptr)
,ptr_i(&in_){
}
basic_filterbuf(ostream& out_)
:ptr_io(nullptr)
,ptr_o(&out_)
,ptr_i(nullptr){
}
public:
iostream& ref_io(){return *ptr_io;}
istream& ref_i(){return *ptr_i;}
ostream& ref_o(){return *ptr_o;}
const iostream& ref_io(){return *ptr_io;}
const istream& cref_i()const{return *ptr_i;}
const ostream& cref_o()const{return *ptr_o;}
bool has_i()const{return ptr_i!=nullptr;}
bool has_o()const{return ptr_o!=nullptr;}
bool has_io()const{return has_io!=nullptr;}
bool is_open()const{return has_i() || has_o();}
bool open(iostream& io_){
if(is_open())return true;
ptr_io=&io_;
ptr_o=&io_;
ptr_i=&io_;
return false;
}
bool open(ostream& out_){
if(is_open())return true;
ptr_io=nullptr;
ptr_o=&out_;
ptr_i=nullptr;
return false;
}
bool open(istream& in_){
if(is_open())return true;
ptr_io=nullptr;
ptr_o=nullptr;
ptr_i=&in_;
return false;
}
bool close(){
if(!is_open())return true;
ptr_io=nullptr;
ptr_o=nullptr;
ptr_i=nullptr;
return false;
}
pos_type tell_i()const{
hmLib_assert(has_i(),"There is no istream");
return ptr_i->tellg();
}
pos_type tell_o()const{
hmLib_assert(has_o(),"There is no ostream");
return ptr_o->tellp();
}
void seek_i(pos_type pos){
hmLib_assert(has_i(),"There is no istream");
return ptr_i->seelg(pos);
}
void seek_o(pos_type pos){
hmLib_assert(has_o(),"There is no ostream");
return ptr_o->seelp(pos);
}
void seek_i(off_type off,std::ios_base::seekdir way){
hmLib_assert(has_i(),"There is no istream");
return ptr_i->seelg(off,way);
}
void seek_o(off_type off,std::ios_base::seekdir way){
hmLib_assert(has_o(),"There is no ostream");
return ptr_o->seelg(off,way);
}
bool eof_i()const{
hmLib_assert(has_i(),"There is no istream");
return ptr_i->eof();
}
bool eof_o()const{
hmLib_assert(has_o(),"There is no ostream");
return ptr_o->eof();
}
};
typedef basic_filterbuf<char,std::char_traits<char>> filterbuf;
}
#
#endif
| [
"hmito@outlook.com"
] | hmito@outlook.com |
37f397a34b78bd7ea7c3f46ee39da601b90e89ef | 716e85aabb54bfee29f4094f9912edf67ce1e7b6 | /arduino_SERIAL/o_SERIAL/o_SERIAL.ino | ca583f0c36adfb2381544af3f7cf7e71ee5d5ded | [] | no_license | marcodemutiis/monotaskers | 1dcc29d2126cef2b26ba228290692f42178f438f | 3d345c7e365fbde878313c8b99f89f1e72422013 | refs/heads/master | 2019-01-02T08:32:02.035653 | 2015-05-23T15:40:32 | 2015-05-23T15:40:32 | 22,776,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,542 | ino | /*
O
info: http://monotaskers.com
Author Marco De Mutiis
Date 24/7/14
Version 0
This is a sample code to be uploaded for the o, a Monotaskers module made of a rotary encoder (push-button enabled) with a 24 led ring around it,
inspired by similar controller knob interfaces, like the arc and the duet.
In this example the lights will turn on according to the position of the rotary encoder, and will blink all at once if the encoder is pushed. If the monotasker
is not touched for longer than 10 minutes it will start a light animation unti it is touched again.
Requires ShiftOutX library by Juan Hernandez and the QuandEncoder library by Pedro Rodrigues.
useful teaching applications:
- Rotary encoder
- Controlling leds
- Pin extension with shift registers IC 74HC595
- Debounce
- Serial communication ( int )
*/
//#define ABSOLUTE //prints absolute position to serial
#define LIGHTPOS //prints light position (0-23) to serial
//#define PROCESSING //for Processing we will use Serial.write
#define OPENFRAMEWORKS //for openFrameworks we will use Serial.print
#include <QuadEncoder.h>
#include <SPI.h>
#include <ShiftOutX.h>
#include <ShiftPinNo.h>
////LED_stuff////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//_latchPin connected to ST_CP of 74HC595
//_dataPin connected to DS of 74HC595
//_clockPin connected to SH_CP of 74HC595
shiftOutX regOne(A2, A1, A3, MSBFIRST, 3);
uint64_t ledArray[24] = {
shPin1, shPin2, shPin3, shPin4, shPin5, shPin6, shPin7, shPin8,
shPin9, shPin10, shPin11, shPin12, shPin13, shPin14, shPin15, shPin16,
shPin17, shPin18, shPin19, shPin20, shPin21, shPin22, shPin23, shPin24};
//Rotary Encoder stuff////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int qe1Move=0;
QuadEncoder qe(12,10);
int lightPos=0; //between 0 and 23
int lastReportedPos;
int absolutePos = 0;
int encoderSwitchPin = 11; //encoder push btn
int push, oldPush;
//general variables//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int frameCounter;
int ledCounter;
int indexLED;
bool reverse;
//nobody has touched the controller for more than 1 minute/////////////////////////////////////////////////////////////////////////////////////////////////
boolean noTouch = true;
long previousMillisBUTTON = 0; // will store last time button was updated
long intervalBUTTON = 3500; // interval at which to change random light
long previousMillisNOTOUCH = 0; // will store last time timer was updated
long intervalNOTOUCH = 600000; // interval at which to trigger the auto blinking [10 min = 10 x 60000 millis]
//SENDTOLED:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
void sendToLed(int index){
if(reverse == true){
for (int i = 23; i > -1; i--){
if (i >= index)regOne.pinOn(ledArray[i]);
else regOne.pinOff(ledArray[i]);
}
}
else{
for (int i = 0; i < 24; i++){
if (i <= index) regOne.pinOn(ledArray[i]);
else regOne.pinOff(ledArray[i]);
}
}
}
//LIGHTANIMATION:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
void oneRing(int frameRate){
if(frameCounter%frameRate == 0){
ledCounter++;
if(ledCounter>=24) ledCounter=0;
regOne.pinOn(ledArray[ledCounter]);
if(ledCounter>2) regOne.pinOff(ledArray[ledCounter-3]);
else regOne.pinOff(ledArray[ledCounter+21]);
}
}
//DEBOUNCE :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// debounce returns true if the switch in the given pin is closed and stable
bool debounce(int pin)
{
boolean state;
boolean previousState;
previousState = digitalRead(pin); // store switch state
for(int counter=0; counter < 1; counter++)
{
delay(1); // wait for 1 millisecond
state = digitalRead(pin); // read the pin
if( state != previousState)
{
counter = 0; // reset the counter if the state changes
previousState = state; // and save the current state
}
}
// here when the switch state has been stable longer than the debounce period
return state;
}
//SETUP:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
void setup(){
regOne.allOff(); //switch off all leds
Serial.begin(9600); //init Serial communication
digitalWrite(encoderSwitchPin, HIGH); //internal pull up resistors for pushbutton reading
frameCounter = 0;
ledCounter = -1;
reverse = false;
for(int i=0; i<24; i++){
regOne.pinOn(ledArray[i]);
delay(10);
if(i>2) regOne.pinOff(ledArray[i-3]);
else regOne.pinOff(ledArray[i+21]);
delay(10);
}
}
//LOOP:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
void loop(){
frameCounter++;
//NOTOUCH::if the device is plugged in and noone touches it for more than one minute it starts randomly turning on and off buttons.
if(noTouch){
oneRing(25);
unsigned long currentMillisBUTTON = millis();
if(currentMillisBUTTON - previousMillisBUTTON > intervalBUTTON) {
previousMillisBUTTON = currentMillisBUTTON;
}
}
unsigned long currentMillisNOTOUCH = millis();
//NOTOUCH ends///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
frameCounter++;
//BTN///////////////////////////////////////PUSHHHHH/////////////////////////////////////////////////////////////////////////////////
push = digitalRead(encoderSwitchPin);
if(debounce(encoderSwitchPin)==true){
if(oldPush!=push){
if(push == 0) {
noTouch = false;
lastReportedPos = lightPos-1;
#ifdef OPENFRAMEWORKS
Serial.println("P");
#endif
#ifdef PROCESSING
Serial.write("P");
#endif
//light animation for push/////
for(int looping=0; looping<2; looping++){
for(int i=0; i<24; i++){
regOne.pinOn(ledArray[i]);
//delay(5);
}
delay(10);
for(int i=0; i<24; i++){
regOne.pinOff(ledArray[i]);
//delay(5);
}
delay(10);
}
//light animation end///////////
}
}
oldPush = push;
}
//ROTATION////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
qe1Move=qe.tick();
if (qe1Move=='>'){
lightPos++;
if(lightPos>23) {
lightPos=0;
reverse = false;
}
absolutePos++;
#ifdef ABSOLUTE
#ifdef OPENFRAMEWORKS
Serial.println(absolutePos);
#endif
#ifdef PROCESSING
Serial.write(absolutePos);
#endif
#endif
#ifdef LIGHTPOS
#ifdef OPENFRAMEWORKS
Serial.println(lightPos);
#endif
#ifdef PROCESSING
Serial.write(lightPos);
#endif
#endif
}
else if (qe1Move=='<'){
lightPos--;
if(lightPos<0) {
lightPos=23;
reverse = true;
}
absolutePos--;
#ifdef ABSOLUTE
Serial.write(absolutePos);
#endif
#ifdef LIGHTPOS
Serial.write(lightPos);
#endif
}
//TO//LEDS////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (lastReportedPos != lightPos) {
indexLED = lightPos;
lastReportedPos = lightPos;
sendToLed(indexLED);
noTouch = false;
}
else{
if(!noTouch){
//Serial.println(currentMillisNOTOUCH - previousMillisNOTOUCH);
if(currentMillisNOTOUCH - previousMillisNOTOUCH > intervalNOTOUCH) {
previousMillisNOTOUCH = currentMillisNOTOUCH;
noTouch=true;
}
}
}
}
void oneRingIndexLED(int index){
// index = 12;
if(frameCounter%50 == 0){
ledCounter++;
if(ledCounter+index>=24) ledCounter=0;
regOne.pinOn(ledArray[ledCounter+index]);
//
if(ledCounter>2) regOne.pinOff(ledArray[ledCounter+index-3]);
else regOne.pinOff(ledArray[ledCounter+21]);
}
}
| [
"marcodemutiis@Marcos-MacBook-Air.local"
] | marcodemutiis@Marcos-MacBook-Air.local |
817198d4ecd68591b6d2e918b4665cc637e06910 | b7d94577d69d3d0a67d6f2d00f9fe2618bee4308 | /tkEngine/EffekseerRuntime130/RuntimeSample/Distortion/main.cpp | 07aba56197d74edfedf1110bccdd68bbab2c7832 | [] | no_license | MurakamiS/GameProject | 85fb743e7101eee85d7adac89ac792bed5679d81 | 8c1bc159258641d39bde52a130256a84757a5c4a | refs/heads/master | 2021-04-06T01:06:17.418292 | 2018-07-13T06:34:56 | 2018-07-13T06:34:56 | 125,322,751 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 11,859 | cpp |
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#include <stdio.h>
#include <windows.h>
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#include <d3d9.h>
#include <XAudio2.h>
#pragma comment(lib, "d3d9.lib" )
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#include <Effekseer.h>
#include <EffekseerRendererDX9.h>
#include <EffekseerSoundXAudio2.h>
#if _DEBUG
#pragma comment(lib, "VS2013/Debug/Effekseer.lib" )
#pragma comment(lib, "VS2013/Debug/EffekseerRendererDX9.lib" )
#pragma comment(lib, "VS2013/Debug/EffekseerSoundXAudio2.lib" )
#else
#pragma comment(lib, "VS2013/Release/Effekseer.lib" )
#pragma comment(lib, "VS2013/Release/EffekseerRendererDX9.lib" )
#pragma comment(lib, "VS2013/Release/EffekseerSoundXAudio2.lib" )
#endif
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
static HWND g_window_handle = NULL;
static int g_window_width = 800;
static int g_window_height = 600;
static ::Effekseer::Manager* g_manager = NULL;
static ::EffekseerRenderer::Renderer* g_renderer = NULL;
static ::EffekseerSound::Sound* g_sound = NULL;
static ::Effekseer::Vector3D g_position;
static ::Effekseer::Effect* g_effect = NULL;
static ::Effekseer::Handle g_handle = -1;
static LPDIRECT3D9 g_d3d = NULL;
static LPDIRECT3DDEVICE9 g_d3d_device = NULL;
static IXAudio2* g_xa2 = NULL;
static IXAudio2MasteringVoice* g_xa2_master = NULL;
static int32_t g_timer = 0;
static IDirect3DSurface9* g_backgroundSurface = nullptr;
static IDirect3DTexture9* g_backgroundTexture = nullptr;
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
static bool CopyRenderTargetToBackground()
{
bool ret = false;
HRESULT hr;
IDirect3DSurface9* tempRender = nullptr;
IDirect3DSurface9* tempDepth = nullptr;
hr = g_d3d_device->GetRenderTarget(0, &tempRender);
if (FAILED(hr))
{
goto Exit;
}
hr = g_d3d_device->GetDepthStencilSurface(&tempDepth);
if (FAILED(hr))
{
goto Exit;
}
g_d3d_device->SetRenderTarget(0, g_backgroundSurface);
g_d3d_device->SetDepthStencilSurface(nullptr);
D3DSURFACE_DESC desc;
tempRender->GetDesc(&desc);
g_d3d_device->StretchRect(
tempRender,
nullptr,
g_backgroundSurface,
nullptr,
D3DTEXF_POINT
);
g_d3d_device->SetRenderTarget(0, tempRender);
g_d3d_device->SetDepthStencilSurface(tempDepth);
ret = true;
Exit:;
ES_SAFE_RELEASE(tempRender);
ES_SAFE_RELEASE(tempDepth);
return ret;
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
class DistortingCallback
: public EffekseerRenderer::DistortingCallback
{
public:
DistortingCallback()
{
}
virtual ~DistortingCallback()
{
}
bool OnDistorting()
{
if (g_backgroundTexture == NULL)
{
((EffekseerRendererDX9::Renderer*)g_renderer)->SetBackground(NULL);
return false;
}
CopyRenderTargetToBackground();
((EffekseerRendererDX9::Renderer*)g_renderer)->SetBackground(g_backgroundTexture);
return true;
}
};
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void InitWindow()
{
WNDCLASS wndClass;
wchar_t szClassNme[] = L"RuntimeSample";
wndClass.style = CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = WndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = GetModuleHandle(0);
wndClass.hIcon = NULL;
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = szClassNme;
RegisterClass(&wndClass);
g_window_handle = CreateWindow(
szClassNme,
L"RuntimeSample",
WS_SYSMENU,
CW_USEDEFAULT,
CW_USEDEFAULT,
g_window_width,
g_window_height,
NULL,
NULL,
GetModuleHandle(0),
NULL);
ShowWindow( g_window_handle, true );
UpdateWindow( g_window_handle );
// COMの初期化
CoInitializeEx( NULL, NULL );
// DirectX9の初期化を行う
D3DPRESENT_PARAMETERS d3dp;
ZeroMemory(&d3dp, sizeof(d3dp));
d3dp.BackBufferWidth = g_window_width;
d3dp.BackBufferHeight = g_window_height;
d3dp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dp.BackBufferCount = 1;
d3dp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dp.Windowed = TRUE;
d3dp.hDeviceWindow = g_window_handle;
d3dp.EnableAutoDepthStencil = TRUE;
d3dp.AutoDepthStencilFormat = D3DFMT_D16;
g_d3d = Direct3DCreate9(D3D_SDK_VERSION);
g_d3d->CreateDevice(
D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
g_window_handle,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&d3dp,
&g_d3d_device );
// XAudio2の初期化を行う
XAudio2Create( &g_xa2 );
g_xa2->CreateMasteringVoice( &g_xa2_master );
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void MainLoop()
{
for(;;)
{
MSG msg;
if (PeekMessage (&msg,NULL,0,0,PM_NOREMOVE))
{
if( msg.message == WM_QUIT )
{
return ;
}
GetMessage (&msg,NULL,0,0);
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
// エフェクトの更新処理を行う。
g_manager->Update();
g_d3d_device->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );
g_d3d_device->BeginScene();
// エフェクトの描画開始処理を行う。
g_renderer->BeginRendering();
// エフェクトの描画を行う。
g_manager->Draw();
// エフェクトの描画終了処理を行う。
g_renderer->EndRendering();
g_d3d_device->EndScene();
g_timer++;
{
HRESULT hr;
hr = g_d3d_device->Present( NULL, NULL, NULL, NULL );
// デバイスロスト処理
switch ( hr )
{
// デバイスロスト
case D3DERR_DEVICELOST:
while ( FAILED( hr = g_d3d_device->TestCooperativeLevel() ) )
{
switch ( hr )
{
// デバイスロスト
case D3DERR_DEVICELOST:
::SleepEx( 1000, true );
break;
// デバイスロスト:リセット可
case D3DERR_DEVICENOTRESET:
// デバイスロストの処理を行う前に実行する
g_renderer->OnLostDevice();
D3DPRESENT_PARAMETERS d3dp;
ZeroMemory(&d3dp, sizeof(d3dp));
d3dp.BackBufferWidth = g_window_width;
d3dp.BackBufferHeight = g_window_height;
d3dp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dp.BackBufferCount = 1;
d3dp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dp.Windowed = TRUE;
d3dp.hDeviceWindow = g_window_handle;
d3dp.EnableAutoDepthStencil = TRUE;
d3dp.AutoDepthStencilFormat = D3DFMT_D16;
g_d3d_device->Reset( &d3dp );
// デバイスロストの処理の後に実行する
g_renderer->OnResetDevice();
break;
}
}
break;
}
}
}
}
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
int main()
{
InitWindow();
// 描画用インスタンスの生成
g_renderer = ::EffekseerRendererDX9::Renderer::Create( g_d3d_device, 2000 );
// 歪み機能を設定
g_renderer->SetDistortingCallback(new DistortingCallback());
// 背景バッファの生成
g_d3d_device->CreateTexture(
640,
480,
1,
D3DUSAGE_RENDERTARGET,
D3DFMT_A8R8G8B8,
D3DPOOL_DEFAULT,
&g_backgroundTexture,
NULL
);
g_backgroundTexture->GetSurfaceLevel(0, &g_backgroundSurface);
// エフェクト管理用インスタンスの生成
g_manager = ::Effekseer::Manager::Create( 2000 );
// 描画用インスタンスから描画機能を設定
g_manager->SetSpriteRenderer( g_renderer->CreateSpriteRenderer() );
g_manager->SetRibbonRenderer( g_renderer->CreateRibbonRenderer() );
g_manager->SetRingRenderer( g_renderer->CreateRingRenderer() );
g_manager->SetModelRenderer( g_renderer->CreateModelRenderer() );
// 描画用インスタンスからテクスチャの読込機能を設定
// 独自拡張可能、現在はファイルから読み込んでいる。
g_manager->SetTextureLoader( g_renderer->CreateTextureLoader() );
g_manager->SetModelLoader( g_renderer->CreateModelLoader() );
// 音再生用インスタンスの生成
g_sound = ::EffekseerSound::Sound::Create( g_xa2, 16, 16 );
// 音再生用インスタンスから再生機能を指定
g_manager->SetSoundPlayer( g_sound->CreateSoundPlayer() );
// 音再生用インスタンスからサウンドデータの読込機能を設定
// 独自拡張可能、現在はファイルから読み込んでいる。
g_manager->SetSoundLoader( g_sound->CreateSoundLoader() );
// 視点位置を確定
g_position = ::Effekseer::Vector3D(10.0f, 5.0f, 20.0f);
// 投影行列を設定
g_renderer->SetProjectionMatrix(
::Effekseer::Matrix44().PerspectiveFovRH(90.0f / 180.0f * 3.14f, (float)g_window_width / (float)g_window_height, 1.0f, 50.0f));
// カメラ行列を設定
g_renderer->SetCameraMatrix(
::Effekseer::Matrix44().LookAtRH(g_position, ::Effekseer::Vector3D(0.0f, 0.0f, 0.0f), ::Effekseer::Vector3D(0.0f, 1.0f, 0.0f)));
// エフェクトの読込
g_effect = Effekseer::Effect::Create(g_manager, (const EFK_CHAR*)L"distortion.efk");
// エフェクトの再生
g_handle = g_manager->Play(g_effect, 0, 0, 0);
MainLoop();
// エフェクトの停止
g_manager->StopEffect(g_handle);
// エフェクトの破棄
ES_SAFE_RELEASE(g_effect);
// 先にエフェクト管理用インスタンスを破棄
g_manager->Destroy();
// 次に音再生用インスタンスを破棄
g_sound->Destroy();
// 次に描画用インスタンスを破棄
g_renderer->Destroy();
// XAudio2の解放
if( g_xa2_master != NULL )
{
g_xa2_master->DestroyVoice();
g_xa2_master = NULL;
}
ES_SAFE_RELEASE( g_xa2 );
// バックバッファの破棄
ES_SAFE_RELEASE( g_backgroundTexture );
ES_SAFE_RELEASE( g_backgroundSurface );
// DirectXの解放
ES_SAFE_RELEASE( g_d3d_device );
ES_SAFE_RELEASE( g_d3d );
// COMの終了処理
CoUninitialize();
return 0;
}
//----------------------------------------------------------------------------------
//
//---------------------------------------------------------------------------------- | [
"kbc17b21@stu.kawahara.ac.jp"
] | kbc17b21@stu.kawahara.ac.jp |
9fc85c5db8edf1f88673e19f17844483273334b1 | eedd904304046caceb3e982dec1d829c529da653 | /QT/ageCalc/main.cpp | b5e9021fd0af6b8ed9743b32061317f2f2156e95 | [] | no_license | PaulFSherwood/cplusplus | b550a9a573e9bca5b828b10849663e40fd614ff0 | 999c4d18d2dd4d0dd855e1547d2d2ad5eddc6938 | refs/heads/master | 2023-06-07T09:00:20.421362 | 2023-05-21T03:36:50 | 2023-05-21T03:36:50 | 12,607,904 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cpp | #include <QCoreApplication>
#include <QDebug>
#include "agecalc.h"
void print(AgeCalc &calc)
{
qInfo() << calc.name() << "Human Years" << calc.humanYears();
qInfo() << calc.name() << "Human Years" << calc.catYears();
qInfo() << calc.name() << "Human Years" << calc.dogYears();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
AgeCalc bryan;
AgeCalc tammy;
bryan.setName("Bryan");
bryan.setAge(46);
tammy.setName("Tammy");
tammy.setAge(27);
print(bryan);
print(tammy);
return a.exec();
}
| [
"paulfsherwood@gmail.com"
] | paulfsherwood@gmail.com |
9f25ad847749618f07b69244871c12210469dcea | 457df228a71eba8d9aba9bbdda47438709cfcf19 | /autopilot/myArduPilot1.0/src/PIDControl.cpp | 2e9757f3f41a32886b66e571ad64b144df4742eb | [] | no_license | lmpizarro/gauchoPiloto | 3cb7a84883e60d2eef048cec656d5cb31fbf3513 | 45bd638861eef83034b5bdbf3cc5d8bf0dd7ca8d | refs/heads/master | 2020-05-17T11:46:16.648267 | 2015-06-03T17:25:10 | 2015-06-03T17:25:10 | 34,933,632 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,678 | cpp | #include "include/PIDControl.h"
/****************************************************************************************
* PID= P+I+D
***************************************************************/
int PID_heading(int PID_error)
{
static unsigned int heading_PID_timer; //Timer to calculate the dt of the PID
static float heading_D; //Stores the result of the derivator
static int heading_output; //Stores the result of the PID loop
float dt=(float)(millis()-heading_PID_timer)/1000;//calculating dt, you must divide it by 1000, because this system only undestands seconds.. and is normally given in millis
//Integratior part
heading_I+= (float)PID_error*(float)dt; //1000 microseconds / 1000 = 1 millisecond
heading_I=constrain(heading_I,heading_min,heading_max); //Limit the PID integrator...
//Derivation part
heading_D=((float)PID_error-(float)heading_previous_error)/(float)dt;
heading_output=0;//Clearing the variable.
heading_output=(kp[0]*PID_error);//Proportional part, is just the KP constant * error.. and addidng to the output
heading_output+= (ki[0]*heading_I);//Adding integrator result...
heading_output+= (kd[0]*heading_D);//Adding derivator result....
//Adds all the PID results and limit the output...
heading_output = constrain(heading_output,heading_min,heading_max);//limiting the output....
heading_previous_error=PID_error;//Saving the actual error to use it later (in derivating part)...
heading_PID_timer=millis();//Saving the last execution time, important to calculate the dt...
//Now checking if the user have selected normal or reverse mode (servo)...
if(reverse_yaw == 1)
{
return (int)(-1*heading_output);
}
else
{
return (int)(heading_output);
}
}
/* ---------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*/
int PID_altitude(int PID_set_Point, int PID_current_Point)
{
static unsigned int altitude_PID_timer;//Timer to calculate the dt of the PID
static float altitude_D; //Stores the result of the derivator
static int altitude_output; //Stores the result of the PID loop
int PID_error=0;
float dt=(float)(millis()-altitude_PID_timer)/1000; //calculating dt, you must divide it by 1000, because this system only undestand seconds.. and is normally given in millis
//Computes the error
PID_error=PID_set_Point-PID_current_Point;
//Integratior part
altitude_I+= (float)PID_error*dt; //
altitude_I=constrain(altitude_I,20,-20); //Limit the PID integrator...
//Derivation part
altitude_D=(float)((float)PID_error-(float)altitude_previous_error)/((float)dt);
altitude_output= (kp[1]*PID_error);//Adding proportional
altitude_output+=(ki[1]*altitude_I);//Adding integrator result..
altitude_output+= (kd[1]*altitude_D);//Adding Derivator result..
//Plus all the PID results and limit the output...
altitude_output = constrain(altitude_output,altitude_min,altitude_max);//PID_P+PID_I+PID_D
altitude_previous_error=PID_error;//Saving the actual error to use it later (in derivating part)...
altitude_PID_timer=millis();//Saving the last execution time, important to calculate the dt...
return altitude_output; //Returns the result
}
/*************************************************************************
* Reset all the PIDs
*************************************************************************/
void reset_PIDs(void)
{
heading_previous_error=0;
heading_I=0;
altitude_previous_error=0;
altitude_I=0;
}
| [
"lmpbici@gmail.com"
] | lmpbici@gmail.com |
c002a87c6eb8ece1adc59f0ea642c0bba258bd96 | 0e416e008936559e458de8ddf1ecf479c7377153 | /2.1/integers_to_romans.cpp | a64302608d37c2a378b4752128e9c622f4948556 | [] | no_license | JaredAll/Compilers-PTT | fee2741bf1e40c3377acd73e2cac981dccce2d29 | fc1cdbce8d7905f2119b2151be7e7885219945ad | refs/heads/master | 2023-02-17T09:55:53.307571 | 2021-01-18T18:25:32 | 2021-01-18T18:25:32 | 328,488,639 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,339 | cpp | #include <iostream>
using namespace std;
void digit( int input );
void digit_prime( int input );
void parse( int input );
int main()
{
while( true )
{
int input;
cin >> input;
parse( input );
}
}
void parse( int input )
{
if( input > 0 && input < 10 )
{
digit( input );
cout << endl;
}
else if( input >= 10 && input <= 50 )
{
digit_prime( input / 10 );
digit( input % 10 );
cout << endl;
}
else
{
cout << "out of bounds";
cout << endl;
}
}
void digit( int input )
{
string output;
switch( input )
{
case 1:
output = "I";
break;
case 2:
output = "II";
break;
case 3:
output = "III";
break;
case 4:
output = "IV";
break;
case 5:
output = "V";
break;
case 6:
output = "VI";
break;
case 7:
output = "VII";
break;
case 8:
output = "VIII";
break;
case 9:
output = "IX";
break;
default:
output = "";
break;
}
cout << output;
}
void digit_prime( int input )
{
string output;
switch( input )
{
case 1:
output = "X";
break;
case 2:
output = "XX";
break;
case 3:
output = "XXX";
break;
case 4:
output = "XL";
break;
case 5:
output = "L";
break;
default:
output = "";
break;
}
cout << output;
}
| [
"jaredlallen76@gmail.com"
] | jaredlallen76@gmail.com |
4272dfcb0feba076b31ab914ee133feccad574d8 | b3c47795e8b6d95ae5521dcbbb920ab71851a92f | /Leetcode/Algorithm/python/2000/01525-Number of Good Ways to Split a String.cc | 20cd2d50ec93e12e44f529897ef23c85eb7397a4 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | Wizmann/ACM-ICPC | 6afecd0fd09918c53a2a84c4d22c244de0065710 | 7c30454c49485a794dcc4d1c09daf2f755f9ecc1 | refs/heads/master | 2023-07-15T02:46:21.372860 | 2023-07-09T15:30:27 | 2023-07-09T15:30:27 | 3,009,276 | 51 | 23 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cc | class Solution(object):
def numSplits(self, s):
l, r = [], []
st = set()
for c in s:
st.add(c)
l.append(len(st))
st = set()
for c in s[::-1]:
st.add(c)
r.append(len(st))
r = r[::-1]
n = len(s)
ans = 0
for i in xrange(n - 1):
if l[i] == r[i + 1]:
ans += 1
return ans
| [
"noreply@github.com"
] | noreply@github.com |
5b0c72e6afb08c1d88f13e556dc8cb40001d485a | cc6adf990fb627284fe4bfc0423d2853a151e0a6 | /c++/ICMP-Backdoor/icmp.cpp | 2c8b2898e44c62aaf8d5fc27227802372eb1b24e | [] | no_license | mnihyc/legacy-toolset | db2e57faaa123fcec4d143a7e873df9a2092b2c9 | e4d0c402ada84b097eca1a3a6d816f817d3fbaba | refs/heads/main | 2023-06-02T19:20:42.632759 | 2021-06-25T06:37:51 | 2021-06-25T06:37:51 | 380,017,543 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,981 | cpp | #include "icmp.h"
ICMP_CONTROL::ICMP_CONTROL()
{
OutputString=true;
fromlen=sizeof(from);
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
fprintf(stderr, "WSAStartup failed: %d\n", GetLastError());
ExitProcess(STATUS_FAILED);
}
}
ICMP_CONTROL::~ICMP_CONTROL()
{
closesocket(sockRaw);
WSACleanup();
}
void ICMP_CONTROL::SetTimeOut(int type,int timeout)
{
setsockopt(sockRaw, SOL_SOCKET, type==0?SO_SNDTIMEO:SO_RCVTIMEO, (char *) &timeout, sizeof(timeout));
if(type==0)sendtimeout=timeout;
else recvtimeout=timeout;
}
int ICMP_CONTROL::GetTimeOut(int type)
{
return (type==0?sendtimeout:recvtimeout);
}
void ICMP_CONTROL::socket(const char*ip)
{
sockRaw=::socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
memset(&dest,0,sizeof(dest));
dest.sin_addr.s_addr=inet_addr(ip);
dest.sin_family=AF_INET;
memset(this->ipaddress,0,sizeof(this->ipaddress));strcpy(this->ipaddress,ip);
}
bool ICMP_CONTROL::send(const char*buffer,long buflen)
{
//datasize=strlen(buffer);
//Pay attention to this !
if(buflen==0)
buflen=strlen(buffer)+1;
datasize=buflen;
datasize+=sizeof(IcmpHeader);
datasize+=sizeof(int);
if(OutputString)printf("ICMP packet size is %d",datasize);
icmp_data= (char*)xmalloc(MAX_PACKET);
recvbuf= (char *)xmalloc(MAX_PACKET);
memset(icmp_data,0, MAX_PACKET);
//fill_icmp_data(icmp_data, datasize,recvtimeout);
IcmpHeader *icmp_hdr;
char *datapart;
icmp_hdr= (IcmpHeader *)icmp_data;
icmp_hdr->i_type=0;
icmp_hdr->i_code=0;
icmp_hdr->i_id=(USHORT)GetCurrentProcessId();
icmp_hdr->timestamp =GetTickCount();
icmp_hdr->i_seq=ICMP_PASSWORD;
datapart=icmp_data + sizeof(IcmpHeader);
memcpy(datapart,&recvtimeout,sizeof(int));
datapart+=sizeof(int);
memcpy(datapart,buffer,/*strlen(buffer)+1*/buflen);
((IcmpHeader *)icmp_data)->i_cksum=0;
((IcmpHeader *)icmp_data)->i_cksum=checksum((USHORT *)icmp_data, datasize);
int bwrote=sendto(sockRaw, icmp_data, datasize, 0, (struct sockaddr *) &dest, sizeof(dest));
xfree(icmp_data);
if (bwrote == SOCKET_ERROR)
{
if(OutputString)
{
if (WSAGetLastError() == WSAETIMEDOUT) printf("Timed out\n");
fprintf(stderr,"sendto failed: %d\n",WSAGetLastError());
}
return false;
}
if (bwrote<datasize ) {
if(OutputString)printf("send only %d datas but total %d datas.\n",bwrote,datasize);
return false;
}
if(OutputString)printf("\nSend Packet to %s Success!\n",ipaddress);
return true;
}
bool ICMP_CONTROL::recv(void)
{
if(!recv1())
if(!recv1())
if(!recv1())
{
printf("Failed more then 3 times !!!\n");
return false;
}
return true;
}
bool ICMP_CONTROL::recv1(void)
{
//DWORD start = GetTickCount();
//for(;;){
//if((GetTickCount() - start) >= 1000) break;
memset(recvbuf,0,MAX_PACKET);
int bread=recvfrom(sockRaw, recvbuf, MAX_PACKET, 0, (struct sockaddr *) &from, &fromlen);
if(bread == SOCKET_ERROR)
{
if(WSAGetLastError() == WSAETIMEDOUT)
{
if(OutputString)printf("recv timed out\n");
return false;
//break;
}
if(OutputString)fprintf(stderr, "recvfrom failed: %d\n", WSAGetLastError());
//break;
return false;
}
//decode_resp(recvbuf, bread, &from);
memset(arg,0,sizeof(arg));
IpHeader *iphdr;
IcmpHeader *icmphdr;
unsigned short iphdrlen;
iphdr = (IpHeader *)recvbuf;
iphdrlen = iphdr->h_len * 4 ;
icmphdr = (IcmpHeader*)(recvbuf + iphdrlen);
if(icmphdr->i_seq==ICMP_REVERSE_PASSWORD)//??????????
{
memcpy(arg,recvbuf+iphdrlen+12,sizeof(arg)-1);
argSizeRecv=bread-iphdrlen-12;
if(OutputString)
{
printf("%d bytes from %s:",bread, inet_ntoa(from.sin_addr));
printf(" IcmpType %d",icmphdr->i_type);
printf(" IcmpCode %d",icmphdr->i_code);
printf("\n");
printf("------------------\n%s\n",arg);
}
}
else
{
if(OutputString)printf("Other ICMP Packets! (seq->%d)\n",icmphdr->i_seq);
return false;
}
//}
return true;
}
| [
"rmnihyc@gmail.com"
] | rmnihyc@gmail.com |
21b2232f850311e114273adfcff8d6785f1a94d5 | 39a1bd091b84a0e3a2062b5759decb76bc59ed83 | /1030A/1030A.cpp | f33ac289cd91bc0214bdabe2eb9f6cd42c7a1030 | [] | no_license | kunnapatt/Competitive | 15801e1db97d56890a57d0e9417614dd8d6f7184 | 0107fd77d8b3a86e163632667bf729384c176f92 | refs/heads/master | 2022-01-06T18:37:56.391755 | 2019-05-19T17:09:30 | 2019-05-19T17:09:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | cpp | #include <bits/stdc++.h>
using namespace std ;
int n = 0 ;
int main() {
cin >> n ;
int x[n] ;
for ( int i = 0 ; i < n ; i++ ) {
cin >> x[i] ;
}
for ( int i = 0 ; i < n ; i++ ) {
if ( x[i] == 1 ) {
cout << "HARD" ;
return 0 ;
}
}
cout << "Easy" ;
return 0 ;
}
| [
"folk_qq@hotmail.com"
] | folk_qq@hotmail.com |
9bdadb9cfe3541ec5fe2fc2a24ebffb3c835c981 | e4ba082517257ee2aebabbccbc7de8a30bd91f7c | /algorithms/cpp/longestPalindromicSubsequence/LongestPalindromicSubsequence.cpp | b4be0756a3d853f5b1f7b7da00fa74f34379e91f | [] | no_license | wm901115nwpu/leetcode | 27441dc0ce8154fec341734dea983f28042ff403 | e60e08855d9b23812838df635053c84bb0242481 | refs/heads/master | 2022-07-13T21:06:57.216203 | 2022-07-03T15:40:59 | 2022-07-03T15:40:59 | 220,498,389 | 1 | 0 | null | 2019-11-08T15:47:24 | 2019-11-08T15:47:24 | null | UTF-8 | C++ | false | false | 2,764 | cpp | // Source : https://leetcode.com/problems/longest-palindromic-subsequence/
// Author : Hao Chen
// Date : 2021-03-27
/*****************************************************************************************************
*
* Given a string s, find the longest palindromic subsequence's length in s.
*
* A subsequence is a sequence that can be derived from another sequence by deleting some or no
* elements without changing the order of the remaining elements.
*
* Example 1:
*
* Input: s = "bbbab"
* Output: 4
* Explanation: One possible longest palindromic subsequence is "bbbb".
*
* Example 2:
*
* Input: s = "cbbd"
* Output: 2
* Explanation: One possible longest palindromic subsequence is "bb".
*
* Constraints:
*
* 1 <= s.length <= 1000
* s consists only of lowercase English letters.
******************************************************************************************************/
/*
supposed s = "abbcba"
we can have a matrix,
- dp[start, end] is the longest from s[start] to s[end]
- if (start == end) dp[statr, end] = 1, it means every char can be palindromic
a b b c b a
a 1 0 0 0 0 0
b 0 1 0 0 0 0
b 0 0 1 0 0 0
c 0 0 0 1 0 0
b 0 0 0 0 1 0
a 0 0 0 0 0 1
calculating from the bottom to up. (Note: only care about the top-right trangle)
a b b c b a
a 1 1 2 2 3 [5] <-- a == a , so "abbcba" comes from "bbcb" + 2
b 0 1 [2] 2 3 3 <-- b == b , so "bb" comes from "" + 2
b 0 0 1 1 [3] 3 <-- b == b , so "bcb" comes from "c" + 2
c 0 0 0 1 1 [1] <-- c != a , so "cba" comes from max("cb", "a")
b 0 0 0 0 1 [1] <-- b != a , so "ba" comes from max ("b", "a")
a 0 0 0 0 0 1
So, we can have the following formular:
s[start] != s[end] ==> dp[start, end] = max (dp[start+1, end], dp[start, end-1]);
s[start] == s[end] ==> dp[start, end] = dp[start+1, end-1] + 2;
*/
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int start = n-1; start>=0; start--) {
for (int end = start ; end < n ; end++) {
if (start == end) {
dp[start][end] = 1;
continue;
}
if (s[start] == s[end]) {
dp[start][end] = dp[start+1][end-1] + 2;
}else{
dp[start][end] = max (dp[start+1][end], dp[start][end-1]);
}
}
}
return dp[0][n-1];
}
};
| [
"unicorn@192.168.1.11"
] | unicorn@192.168.1.11 |
d29566eb978b77e701a4c5fb4d1a7d874830d6c6 | 770cec80a8bb58b8c3e070baf2b424fa5bbb61f2 | /instructional_software/实验8.h | cd90ea392c1b8c1702a4edcf2461ac1f247f9f4b | [] | no_license | xujunmingbest/instructional_software | 76e6ea0962522d88bc17798f1e4e3c3dc05b206e | c94157121559a0762aeec6a80ad56d4be7b6d4ac | refs/heads/master | 2020-04-11T00:44:37.057180 | 2018-03-27T06:16:56 | 2018-03-27T06:16:56 | 124,214,740 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,470 | h | #pragma once
#include "实验8实验目的.h"
#include "实验8选用组件.h"
#include "实验8实验方法.h"
#include "实验8讨论题.h"
extern bool 实验8Status;
namespace instructional_software {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// 实验8 摘要
/// </summary>
public ref class 实验8 : public System::Windows::Forms::Form
{
public:
实验8(void)
{
InitializeComponent();
实验8Status = true;
//
//TODO: 在此处添加构造函数代码
//
}
protected:
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
~实验8()
{
实验8Status = false;
if (components)
{
delete components;
}
}
private: System::Windows::Forms::MenuStrip^ menuStrip1;
protected:
private: System::Windows::Forms::ToolStripMenuItem^ 实验目的ToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ 选用组件ToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ 实验方法ToolStripMenuItem;
private: System::Windows::Forms::ToolStripMenuItem^ 讨论题ToolStripMenuItem;
private:
/// <summary>
/// 必需的设计器变量。
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
void InitializeComponent(void)
{
this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip());
this->实验目的ToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->选用组件ToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->实验方法ToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->讨论题ToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->menuStrip1->SuspendLayout();
this->SuspendLayout();
//
// menuStrip1
//
this->menuStrip1->Font = (gcnew System::Drawing::Font(L"微软雅黑", 15, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(134)));
this->menuStrip1->ImageScalingSize = System::Drawing::Size(20, 20);
this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(4) {
this->实验目的ToolStripMenuItem,
this->选用组件ToolStripMenuItem, this->实验方法ToolStripMenuItem, this->讨论题ToolStripMenuItem
});
this->menuStrip1->Location = System::Drawing::Point(0, 0);
this->menuStrip1->Name = L"menuStrip1";
this->menuStrip1->Size = System::Drawing::Size(946, 41);
this->menuStrip1->TabIndex = 1;
this->menuStrip1->Text = L"menuStrip1";
//
// 实验目的ToolStripMenuItem
//
this->实验目的ToolStripMenuItem->Name = L"实验目的ToolStripMenuItem";
this->实验目的ToolStripMenuItem->Size = System::Drawing::Size(127, 37);
this->实验目的ToolStripMenuItem->Text = L"实验目的";
this->实验目的ToolStripMenuItem->Click += gcnew System::EventHandler(this, &实验8::实验目的ToolStripMenuItem_Click);
//
// 选用组件ToolStripMenuItem
//
this->选用组件ToolStripMenuItem->Name = L"选用组件ToolStripMenuItem";
this->选用组件ToolStripMenuItem->Size = System::Drawing::Size(127, 37);
this->选用组件ToolStripMenuItem->Text = L"选用组件";
this->选用组件ToolStripMenuItem->Click += gcnew System::EventHandler(this, &实验8::选用组件ToolStripMenuItem_Click);
//
// 实验方法ToolStripMenuItem
//
this->实验方法ToolStripMenuItem->Name = L"实验方法ToolStripMenuItem";
this->实验方法ToolStripMenuItem->Size = System::Drawing::Size(127, 37);
this->实验方法ToolStripMenuItem->Text = L"实验方法";
this->实验方法ToolStripMenuItem->Click += gcnew System::EventHandler(this, &实验8::实验方法ToolStripMenuItem_Click);
//
// 讨论题ToolStripMenuItem
//
this->讨论题ToolStripMenuItem->Name = L"讨论题ToolStripMenuItem";
this->讨论题ToolStripMenuItem->Size = System::Drawing::Size(102, 37);
this->讨论题ToolStripMenuItem->Text = L"讨论题";
this->讨论题ToolStripMenuItem->Click += gcnew System::EventHandler(this, &实验8::讨论题ToolStripMenuItem_Click);
//
// 实验8
//
this->AutoScaleDimensions = System::Drawing::SizeF(8, 15);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(946, 492);
this->Controls->Add(this->menuStrip1);
this->IsMdiContainer = true;
this->MainMenuStrip = this->menuStrip1;
this->Name = L"实验8";
this->Text = L"实验8";
this->Load += gcnew System::EventHandler(this, &实验8::实验8_Load);
this->menuStrip1->ResumeLayout(false);
this->menuStrip1->PerformLayout();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void 实验8_Load(System::Object^ sender, System::EventArgs^ e) {
}
/***********实验8子窗体指针***********/
private:
实验8实验目的 ^实验8实验目的wnd;
实验8选用组件 ^实验8选用组件wnd;
实验8实验方法 ^实验8实验方法wnd;
实验8讨论题 ^实验8讨论题wnd;
private: System::Void 实验目的ToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
if (实验8实验目的Status == true)
{
实验8实验目的wnd->BringToFront(); //这个可以置于最前面
实验8实验目的wnd->WindowState = FormWindowState::Maximized;
return;
}
实验8实验目的wnd = gcnew 实验8实验目的;
实验8实验目的wnd->MdiParent = this;
实验8实验目的wnd->Show();
实验8实验目的wnd->WindowState = FormWindowState::Maximized;
}
private: System::Void 选用组件ToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
if (实验8选用组件Status == true)
{
实验8选用组件wnd->BringToFront(); //这个可以置于最前面
实验8选用组件wnd->WindowState = FormWindowState::Maximized;
return;
}
实验8选用组件wnd = gcnew 实验8选用组件;
实验8选用组件wnd->MdiParent = this;
实验8选用组件wnd->Show();
实验8选用组件wnd->WindowState = FormWindowState::Maximized;
}
private: System::Void 实验方法ToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
if (实验8实验方法Status == true)
{
实验8实验方法wnd->BringToFront(); //这个可以置于最前面
实验8实验方法wnd->WindowState = FormWindowState::Maximized;
return;
}
实验8实验方法wnd = gcnew 实验8实验方法;
实验8实验方法wnd->MdiParent = this;
实验8实验方法wnd->Show();
实验8实验方法wnd->WindowState = FormWindowState::Maximized;
}
private: System::Void 讨论题ToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
if (实验8讨论题Status == true)
{
实验8讨论题wnd->BringToFront(); //这个可以置于最前面
实验8讨论题wnd->WindowState = FormWindowState::Maximized;
return;
}
实验8讨论题wnd = gcnew 实验8讨论题;
实验8讨论题wnd->MdiParent = this;
实验8讨论题wnd->Show();
实验8讨论题wnd->WindowState = FormWindowState::Maximized;
}
};
}
| [
"925271237@qq.com"
] | 925271237@qq.com |
393ffa23b2c65ea47d0d4f50a79802d16a5d9895 | efaf97003db0acabd3a64573c3d4d0297fd945ff | /Student_Code/AVLInterface.h | 033c5d4180f480ac0a77ba44f73117b8781fd40b | [] | no_license | ahwang2008/AVL | b90de921df8eb49372c25db54bda1101595df809 | 694a461471dba38821ad624f0ad170d118e6b8f8 | refs/heads/master | 2020-04-09T17:12:40.190631 | 2018-12-05T06:52:28 | 2018-12-05T06:52:28 | 160,473,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | h | //YOU MAY NOT MODIFY THIS DOCUMENT
/*
* Last Updated on: April 2, 2015
*/
#pragma once
#include "NodeInterface.h"
using namespace std;
class AVLInterface {
public:
AVLInterface() {}
virtual ~AVLInterface() {}
//Please note that the class that implements this interface must be made
//of objects which implement the NodeInterface
/*
* Returns the root node for this tree
*
* @return the root node for this tree.
*/
virtual NodeInterface * getRootNode() = 0;
/*
* Attempts to add the given int to the AVL tree
* Rebalances the tree if data is successfully added
*
* @return true if added
* @return false if unsuccessful (i.e. the int is already in tree)
*/
virtual bool add(int data) = 0;
/*
* Attempts to remove the given int from the AVL tree
* Rebalances the tree if data is successfully removed
*
* @return true if successfully removed
* @return false if remove is unsuccessful(i.e. the int is not in the tree)
*/
virtual bool remove(int data) = 0;
};
| [
"ahwang2008@gmail.com"
] | ahwang2008@gmail.com |
f058bbe69c9300b199b7ab14b10fa9f4e1426dc1 | 28575efd4495389d76e9941efca2d00d82ec11f3 | /ogre/RenderSystems/GLES2/src/NONE/OgreNoneGLContext.h | 9f9f2399a821cfa87c785d1ad66968634c484cc0 | [] | no_license | dorgonman/cocos2d-x-ogre | f3db3e0a74f676d56b1468dd3792ecc21f8277ea | bc9347e3416932812a6b9e52f95e4f2f2f9f2e8e | refs/heads/master | 2021-01-22T09:17:44.331761 | 2013-12-13T08:55:04 | 2013-12-13T08:55:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,960 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __NoneGLContext_H__
#define __NoneGLContext_H__
#include "OgreGLES2Context.h"
namespace Ogre {
class NoneGLSupport;
class _OgrePrivate NoneGLContext: public GLES2Context
{
protected:
const NoneGLSupport* mGLSupport;
public:
NoneGLContext(const NoneGLSupport* glsupport);
virtual ~NoneGLContext();
virtual void setCurrent();
virtual void endCurrent();
virtual GLES2Context* clone() const = 0;
};
}
#endif
| [
"27001909@qq.com"
] | 27001909@qq.com |
1f3f530fd41e41270bacae5c41a810acf386aa34 | b363901145ec9446a514c21e5766f04acb06215c | /main.cpp | 22944e7bb0cc46e46289c78ea516af3186b29a9a | [] | no_license | e2e4b6b7/Algebra | 1955c581caf3774b0fcc5a4158617bc1e753360c | f43b318cd45bf768921d777a24e23cccb0ab8fe3 | refs/heads/master | 2023-01-22T21:26:13.846805 | 2020-12-02T18:35:29 | 2020-12-02T18:35:29 | 317,883,526 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,243 | cpp | #include <vector>
#include <iostream>
#include <ctime>
#include "Integer.hpp"
#include "FactorInteger.hpp"
#include "Polynomial.hpp"
#include "FactorPolynomial.hpp"
void additions() {
Polynomial<FactorInteger<long, 13>> p1{{2, 5, 4}};
Polynomial<FactorInteger<long, 13>> p2{{4, 1, 8, 5}};
for (int i = 0; i < 100; ++i) {
p2 = p2 + p1;
}
std::cout << p2.view() << std::endl;
}
void gcd() {
Polynomial<FactorInteger<long, 13>> p1{{2, 5, 4, 7, 2}};
Polynomial<FactorInteger<long, 13>> p2{{4, 1, 8, 5}};
for (int i = 0; i < 100; ++i) {
p2 = p2 + p1;
p2 = gcd(p2, p1);
}
std::cout << p2.view() << std::endl;
}
void bezout() {
Polynomial<FactorInteger<long, 13>> p1{{2, 5, 4, 7, 2}};
Polynomial<FactorInteger<long, 13>> p2{{4, 1, 8, 5}};
for (int i = 0; i < 100; ++i) {
p2 = p2 + p1;
auto[p3, p4] = bezout_ratio(p2, p1);
p2 = p3 + p4;
}
std::cout << p2.view() << std::endl;
}
void multiplications() {
Polynomial<FactorInteger<long, 13>> p1{{2, 5, 4}};
Polynomial<FactorInteger<long, 13>> p2{{4, 1, 8, 5}};
for (int i = 0; i < 100; ++i) {
p2 = p2 * p1;
}
std::cout << p2.view() << std::endl;
}
void additions_factor() {
Polynomial<FactorInteger<long, 13>> fac{{2, 5, 4}};
FactorPolynomial<FactorInteger<long, 13>>::FactorPolynomialBase base{fac, true};
Polynomial<FactorInteger<long, 13>> p1{{2, 5, 4}};
Polynomial<FactorInteger<long, 13>> p2{{4, 1, 8, 5}};
FactorPolynomial<FactorInteger<long, 13>> fp1{p1, base};
FactorPolynomial<FactorInteger<long, 13>> fp2{p2, base};
for (int i = 0; i < 100; ++i) {
fp2 = fp2 + fp1;
}
}
void multiplications_factor() {
Polynomial<FactorInteger<long, 13>> fac{{2, 5, 4}};
FactorPolynomial<FactorInteger<long, 13>>::FactorPolynomialBase base{fac, true};
Polynomial<FactorInteger<long, 13>> p1{{2, 5, 4}};
Polynomial<FactorInteger<long, 13>> p2{{4, 1, 8, 5}};
FactorPolynomial<FactorInteger<long, 13>> fp1{p1, base};
FactorPolynomial<FactorInteger<long, 13>> fp2{p2, base};
for (int i = 0; i < 100; ++i) {
fp2 = fp2 * fp1;
}
}
void reverse_factor() {
Polynomial<FactorInteger<>> fac{{1, 1, 0, 1, 1, 0, 0, 0, 1}};
FactorPolynomial<FactorInteger<>>::FactorPolynomialBase base{fac, true};
Polynomial<FactorInteger<>> p1{{2, 5, 4}};
Polynomial<FactorInteger<>> p2{{4, 1, 8, 5}};
FactorPolynomial fp1{p1, base};
FactorPolynomial fp2{p2, base};
for (int i = 0; i < 100; ++i) {
fp1 = fp2;
fp2 = reverse(reverse(fp2));
std::cout << (fp1 == fp2);
}
std::cout << '\n';
}
int main() {
long time = clock();
/*additions();
std::cout << clock() - time << std::endl;
time = clock();
multiplications();
std::cout << clock() - time << std::endl;
time = clock();
gcd();
std::cout << clock() - time << std::endl;
time = clock();
additions_factor();
std::cout << clock() - time << std::endl;
time = clock();
multiplications_factor();
std::cout << clock() - time << std::endl;
time = clock();*/
reverse_factor();
std::cout << clock() - time << std::endl;
time = clock();
} | [
"e2e4b6b7@gmail.com"
] | e2e4b6b7@gmail.com |
cd503e95402157e3f9ba515bff54cb79f697cf01 | f0f688f683188d72a182f7b980d759fea662ee1d | /[7]ReverseInteger.cpp | ccef1f1abcc06d469bad2d7fc2021e83b9f87ca7 | [] | no_license | emoy-kim/LeetCode | 2c49b93edd6b64e2a9f300f47e40f82cbd23b15d | 037d1c30a24025104b9bf59abaff700e08767aa7 | refs/heads/master | 2020-05-03T14:59:07.063694 | 2019-07-22T03:03:12 | 2019-07-22T03:03:12 | 178,692,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,565 | cpp | /*
* [7] Reverse Integer
*
* https://leetcode.com/problems/reverse-integer/description/
*
* algorithms
* Easy (24.43%)
* Total Accepted: 479.2K
* Total Submissions: 2M
* Testcase Example: '123'
*
* Given a 32-bit signed integer, reverse digits of an integer.
*
* Example 1:
*
*
* Input: 123
* Output: 321
*
*
* Example 2:
*
*
* Input: -123
* Output: -321
*
*
* Example 3:
*
*
* Input: 120
* Output: 21
*
*
* Note:
* Assume we are dealing with an environment which could only store integers
* within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of
* this problem, assume that your function returns 0 when the reversed integer
* overflows.
*
*/
#include <iostream>
#include <vector>
using namespace std;
int reverse(int x)
{
const bool sign = x < 0;
int abs_x = abs( x );
vector<int> digits;
while ( abs_x != 0 ) {
digits.push_back( abs_x % 10 );
abs_x /= 10;
}
// 1534236469
int reversed = 0;
const int digit_num = digits.size();
for (size_t i = 0; i < digits.size(); ++i) {
reversed += static_cast<int>(digits[i] * pow( 10, digit_num - i - 1 ));
}
if (reversed < 0) return 0;
int check = reversed;
vector<int> check_digits;
while ( check != 0 ) {
check_digits.push_back( check % 10 );
check /= 10;
}
for (size_t i = 0; i < check_digits.size(); ++i) {
if (check_digits[i] != digits[digit_num - i - 1])
return 0;
}
if (sign) reversed = -reversed;
return reversed;
} | [
"emoy.kim@gmail.com"
] | emoy.kim@gmail.com |
23cfb2c94b9ba8d001085b4f6b3aa3809677555c | 86c9303af38a78e580cb31f65d4e855a7251a0bd | /equipement.h | 347bf771992477fea6695635015d2cb86f6bf21b | [] | no_license | nadi-cloud/smart-hotel2A10 | 3844321048f5d7339ca77899f22b2e6bf3882c89 | d7ee2c00972245231ff2cbc1040bf2b3ee93afe2 | refs/heads/master | 2022-07-03T11:36:54.819422 | 2020-05-14T09:03:26 | 2020-05-14T09:03:26 | 254,223,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | h | #ifndef EQUIPEMENT_H
#define EQUIPEMENT_H
#include <QString>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QTableView>
#include <QWidget>
class Equipement
{public:
Equipement();
Equipement(int , QString , QString , QString , int );
int get_ide();
QString get_nom();
QString get_type();
QString get_nomf();
int get_nombre();
bool ajouter();
QSqlQueryModel * afficher();
bool supprimer(int );
bool modifier( );
QSqlQueryModel * recherche(QString );
QSqlQueryModel * trier();
QSqlQueryModel statistic();
private:
QString nom,type,nomf;
int nombre,ide;
};
#endif // EQUIPEMENT_H
| [
"noreply@github.com"
] | noreply@github.com |
44fd910a24bedf7682556c69f2a8509022e5d68f | b403154400d65c159d4ab6ad88b1ab9ad8fd7198 | /inc/wxPanelMethod.h | 09e99a2c2d9e2bc5c425fcf3f2c413c32f3fa846 | [
"MIT"
] | permissive | gaviscada/opcua-modeling-tool | 0f9e8c806a0ea9498575d147cefdde07521b9dce | f8c3d940a61334b0e6deda9099844a6b429d7c08 | refs/heads/master | 2021-05-20T14:57:28.684380 | 2018-04-14T15:39:51 | 2018-04-14T15:39:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,518 | h | #ifndef WXPANELMETHOD_H
#define WXPANELMETHOD_H
//(*Headers(wxPanelMethod)
#include <wx/listctrl.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/checkbox.h>
#include <wx/panel.h>
#include <wx/gbsizer.h>
#include <wx/combobox.h>
//*)
#include "synthesis/opc.hxx"
#include <wx/treebase.h>
class wxPanelInstance;
class wxFrameMain;
class wxPanelMethod: public wxPanel
{
public:
wxPanelMethod(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize);
virtual ~wxPanelMethod();
//(*Declarations(wxPanelMethod)
wxStaticText* StaticText2;
wxComboBox* cboTypeDefinition;
wxStaticText* StaticText1;
wxStaticText* StaticText3;
wxStaticText* StaticText5;
wxCheckBox* chkNonExecutable;
wxTextCtrl* txtSymbolicName;
wxListView* listOutput;
wxListView* listInput;
wxStaticText* StaticText4;
//*)
protected:
//(*Identifiers(wxPanelMethod)
static const long ID_STATICTEXT1;
static const long ID_TEXTCTRL1;
static const long ID_STATICTEXT4;
static const long ID_CHECKBOX1;
static const long ID_STATICTEXT2;
static const long ID_LISTVIEW_INPUT;
static const long ID_STATICTEXT3;
static const long ID_LISTVIEW_OUTPUT;
static const long ID_STATICTEXT5;
static const long ID_COMBOBOX1;
//*)
private:
//(*Handlers(wxPanelMethod)
void OnlistInputBeginDrag(wxListEvent& event);
void OnButton1Click(wxCommandEvent& event);
void OnButton1Click1(wxCommandEvent& event);
void OnButton1Click2(wxCommandEvent& event);
void OnlistInputBeginDrag1(wxListEvent& event);
void OnlistInputBeginDrag2(wxListEvent& event);
void OnlistInputBeginDrag3(wxListEvent& event);
void OnlistInputItemRClick1(wxListEvent& event);
void OntxtSymbolicNameText(wxCommandEvent& event);
void OnlistInputBeginDrag4(wxListEvent& event);
void OnlistInputBeginDrag5(wxListEvent& event);
void OnlistInputBeginDrag6(wxListEvent& event);
//*)
DECLARE_EVENT_TABLE()
private:
void OnPopupList(wxCommandEvent &evt);
void SetListItemParameter(Parameter *param, wxListView *listView, int nodeId, bool disabled);
//Custom Event Handlers
void OnlistInputItemRClick(wxCommandEvent& event);
void OnlistOutputItemRClick(wxCommandEvent& event);
void AddParameter(Parameter ¶m, bool isInput);
void DeleteParameter(bool isInput);
void PopulateInputArgs();
void PopulateOutputArgs();
public:
//This method has to be called every time a node is clicked to associate
//this panel with the new node value.
//@param showTypeDef: Type Definition attribute is only available for Child Method because
// it uses the Method instances defined, as the type. This is another opc quirk
// where Method are InstanceDesign instead of a TypeDesign.
void Init(MethodDesign *method, ModelDesign *model, wxTreeItemId treeItemId,
wxFrameMain *mainFrame, bool userOwner, bool showTypeDef);
void PopulateData();
void Clear();
bool UpdateData();
private:
MethodDesign *m_method;
ModelDesign* m_model;
wxTreeItemId m_treeItemId;
wxFrameMain *m_mainFrame;
bool m_showTypeDef;
bool m_userOwner;
//This will store temporarily the input/output parameters to allow the user to manually Update the changes.
std::auto_ptr<MethodDesign> m_tempMethod;
};
#endif
| [
"cos@beeond.net"
] | cos@beeond.net |
74565358eec3619a952b33f02b84b9f771344fda | 7fa00d7ab8377c6dd582957279f15955067b2309 | /bowling/main.cpp | 4c4d5373f896f79328891114c170f1114626ff41 | [] | no_license | prajmus/exercises | d1e95d629c230ad534c5278b7abb702f3719b091 | 977f3fea8b027d0d0e1d76498362accd03f98231 | refs/heads/master | 2021-01-10T04:37:38.454511 | 2015-10-22T13:25:02 | 2015-10-22T13:25:02 | 43,503,946 | 0 | 0 | null | 2015-10-22T13:25:03 | 2015-10-01T15:18:31 | C++ | UTF-8 | C++ | false | false | 935 | cpp | /* Copyright (c) 2015, Jakub Borowski */
#include <gtest/gtest.h>
#include "bowling.hpp"
class BowlingTest : public ::testing::Test {
public:
Game g;
void roll_many(int n, int pins) {
for (int i = 0; i < n; i++)
g.roll(pins);
}
void roll_spare() {
g.roll(5);
g.roll(5);
}
void roll_strike() {
g.roll(10);
}
};
TEST_F(BowlingTest, test_game) {
roll_many(20, 0);
EXPECT_EQ(g.score(), 0);
}
TEST_F(BowlingTest, test_all_ones) {
roll_many(20, 1);
EXPECT_EQ(g.score(), 20);
}
TEST_F(BowlingTest, test_one_spare) {
roll_spare();
g.roll(3);
roll_many(17, 0);
EXPECT_EQ(g.score(), 16);
}
TEST_F(BowlingTest, test_one_strike) {
roll_strike();
g.roll(3);
g.roll(4);
roll_many(16, 0);
EXPECT_EQ(g.score(), 24);
}
TEST_F(BowlingTest, test_perfect_game) {
roll_many(12, 10);
EXPECT_EQ(300, g.score());
}
| [
"prajmus@gmail.com"
] | prajmus@gmail.com |
38a70ddad5d2239b35c8499dd8049b2dd18df885 | 246a7f4cbbbdfdf03ffeb829dccbe5426c274bcb | /Compare_Latest/Frameworks/MapKit/CDStructures.h | 2d744145a410de5decd2a4d41e3a9830dca64d36 | [] | no_license | davidashman/iOS-Headers | 27e6eab84d5d3bd810a84d7646b319057af5b31f | 7f53ee84eed65265627578721889a7bed81ad9e7 | refs/heads/master | 2020-12-28T22:01:34.359885 | 2014-12-21T19:21:21 | 2014-12-21T19:21:21 | 15,954,172 | 5 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 7,306 | h | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#pragma mark Function Pointers and Blocks
typedef void (*CDUnknownFunctionPointerType)(void); // return type and parameters are unknown
typedef void (^CDUnknownBlockType)(void); // return type and parameters are unknown
#pragma mark Named Structures
struct CADoublePoint {
double _field1;
double _field2;
};
struct CADoubleRect {
struct CADoublePoint _field1;
struct CADoubleSize _field2;
};
struct CADoubleSize {
double _field1;
double _field2;
};
struct CATransform3D {
float _field1;
float _field2;
float _field3;
float _field4;
float _field5;
float _field6;
float _field7;
float _field8;
float _field9;
float _field10;
float _field11;
float _field12;
float _field13;
float _field14;
float _field15;
float _field16;
};
struct CGAffineTransform {
float a;
float b;
float c;
float d;
float tx;
float ty;
};
struct CGPoint {
float x;
float y;
};
struct CGRect {
struct CGPoint origin;
struct CGSize size;
};
struct CGSize {
float width;
float height;
};
struct UIEdgeInsets {
float top;
float left;
float bottom;
float right;
};
struct UIImage {
Class _field1;
void *_field2;
float _field3;
struct {
unsigned int :1;
unsigned int :3;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :2;
unsigned int :1;
unsigned int :1;
} _field4;
};
struct UILabel {
Class _field1;
id _field2;
id _field3;
id _field4;
id _field5;
float _field6;
int _field7;
id _field8;
id _field9;
unsigned int _field10;
CDStruct_40634de2 _field11;
};
struct UIView {
Class _field1;
id _field2;
id _field3;
id _field4;
id _field5;
float _field6;
int _field7;
id _field8;
id _field9;
unsigned int _field10;
CDStruct_40634de2 _field11;
};
struct _GEOTileKey {
unsigned int z:6;
unsigned int x:26;
unsigned int y:26;
unsigned int type:6;
unsigned int pixelSize:8;
unsigned int textScale:8;
unsigned int provider:8;
unsigned int expires:1;
unsigned int reserved1:7;
unsigned char reserved2[4];
};
struct _NSRange {
unsigned int _field1;
unsigned int _field2;
};
struct deque<float, std::__1::allocator<float>> {
struct __split_buffer<float *, std::__1::allocator<float *>> {
float **__first_;
float **__begin_;
float **__end_;
struct __compressed_pair<float **, std::__1::allocator<float *>> {
float **__first_;
} __end_cap_;
} __map_;
unsigned int __start_;
struct __compressed_pair<unsigned long, std::__1::allocator<float>> {
unsigned long __first_;
} __size_;
};
#pragma mark Typedef'd Structures
typedef struct {
unsigned int hasMultiplePhotos;
unsigned int isFirstImageRequested;
unsigned int isFirstImagePreloaded;
} CDStruct_0e9d808f;
typedef struct {
unsigned long long _field1;
unsigned long long _field2;
} CDStruct_4bcfbbae;
typedef struct {
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :6;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :5;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :2;
unsigned int :2;
unsigned int :1;
unsigned int :2;
unsigned int :1;
unsigned int :3;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
unsigned int :1;
} CDStruct_40634de2;
typedef struct {
double _field1;
double _field2;
double _field3;
} CDStruct_39925896;
typedef struct {
int x;
int y;
int z;
float contentScaleFactor;
} CDStruct_a1199def;
typedef struct {
float _field1;
struct {
double _field1;
double _field2;
} _field2;
} CDStruct_0c7fa811;
typedef struct {
int _field1;
int _field2;
int _field3;
struct {
unsigned int :1;
unsigned int :1;
unsigned int :1;
} _field4;
} CDStruct_e02beb0c;
typedef struct {
int _field1;
int _field2;
struct {
unsigned int :1;
unsigned int :1;
} _field3;
} CDStruct_c55e649d;
typedef struct {
int _field1;
struct {
double _field1;
double _field2;
} _field2;
struct CGPoint _field3;
struct CGPoint _field4;
id _field5;
char _field6;
} CDStruct_dc034332;
typedef struct {
struct CGSize _field1;
float _field2;
float _field3;
float _field4;
struct CGSize _field5;
float _field6;
float _field7;
float _field8;
int _field9;
float _field10;
float _field11;
float _field12;
float _field13;
float _field14;
float _field15;
float _field16;
float _field17;
float _field18;
float _field19;
float _field20;
float _field21;
float _field22;
float _field23;
float _field24;
float _field25;
char _field26;
float _field27;
float _field28;
float _field29;
char _field30;
char _field31;
} CDStruct_209374b2;
// Ambiguous groups
typedef struct {
double _field1;
double _field2;
} CDStruct_c3b9c2ee;
typedef struct {
double latitude;
double longitude;
} CDStruct_2c43369c;
typedef struct {
double width;
double height;
} CDStruct_8caa76fc;
typedef struct {
struct {
double _field1;
double _field2;
} _field1;
struct {
double _field1;
double _field2;
} _field2;
} CDStruct_90e2a262;
typedef struct {
CDStruct_2c43369c center;
struct {
double latitudeDelta;
double longitudeDelta;
} span;
} CDStruct_feeb6407;
typedef struct {
struct {
double x;
double y;
} origin;
CDStruct_8caa76fc size;
} CDStruct_02837cd9;
| [
"manzopower@icloud.com"
] | manzopower@icloud.com |
f53eb098f252ae2071e95b5739d453631643d62d | 2f874d5907ad0e95a2285ffc3592b8f75ecca7cd | /src/protobuf/src/google/protobuf/stubs/atomicops_internals_pnacl.h | 52c1241f7b0131a3c444f623645ec4646a80d433 | [
"MIT-Wu",
"MIT",
"ISC",
"BSL-1.0",
"LicenseRef-scancode-protobuf"
] | permissive | dzcoin/DzCoinService | fb93809a37fad0a26bf26189266b44cf4c797865 | b0056717d6bcc1741f4fb3f3f166cd8ce78393f9 | refs/heads/master | 2021-01-20T20:28:41.639585 | 2016-08-15T06:21:51 | 2016-08-15T06:21:51 | 65,678,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,861 | h | // protocol buffers - google's data interchange format
// copyright 2012 google inc. all rights reserved.
// http://code.google.com/p/protobuf/
//
// 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 google inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// this software is provided by the copyright holders and contributors
// "as is" and any express or implied warranties, including, but not
// limited to, the implied warranties of merchantability and fitness for
// a particular purpose are disclaimed. in no event shall the copyright
// owner or contributors be liable for any direct, indirect, incidental,
// special, exemplary, or consequential damages (including, but not
// limited to, procurement of substitute goods or services; loss of use,
// data, or profits; or business interruption) however caused and on any
// theory of liability, whether in contract, strict liability, or tort
// (including negligence or otherwise) arising in any way out of the use
// of this software, even if advised of the possibility of such damage.
// this file is an internal atomic implementation, use atomicops.h instead.
#ifndef google_protobuf_atomicops_internals_pnacl_h_
#define google_protobuf_atomicops_internals_pnacl_h_
namespace google {
namespace protobuf {
namespace internal {
inline atomic32 nobarrier_compareandswap(volatile atomic32* ptr,
atomic32 old_value,
atomic32 new_value) {
return __sync_val_compare_and_swap(ptr, old_value, new_value);
}
inline void memorybarrier() {
__sync_synchronize();
}
inline atomic32 acquire_compareandswap(volatile atomic32* ptr,
atomic32 old_value,
atomic32 new_value) {
atomic32 ret = nobarrier_compareandswap(ptr, old_value, new_value);
memorybarrier();
return ret;
}
inline void release_store(volatile atomic32* ptr, atomic32 value) {
memorybarrier();
*ptr = value;
}
inline atomic32 acquire_load(volatile const atomic32* ptr) {
atomic32 value = *ptr;
memorybarrier();
return value;
}
} // namespace internal
} // namespace protobuf
} // namespace google
#endif // google_protobuf_atomicops_internals_pnacl_h_
| [
"dzgrouphelp@foxmail.com"
] | dzgrouphelp@foxmail.com |
0819bca683b9522421266e49ba550cdebafae3a2 | 7a17d90d655482898c6777c101d3ab6578ccc6ba | /SDK/PUBG_BP_MasteryPose_VehicleLean_structs.hpp | a8bcdaf38ab44a1875796af9cb57e4828ad4fe90 | [] | no_license | Chordp/PUBG-SDK | 7625f4a419d5b028f7ff5afa5db49e18fcee5de6 | 1b23c750ec97cb842bf5bc2b827da557e4ff828f | refs/heads/master | 2022-08-25T10:07:15.641579 | 2022-08-14T14:12:48 | 2022-08-14T14:12:48 | 245,409,493 | 17 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 252 | hpp | #pragma once
// PUBG (9.1.5.3) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_Basic.hpp"
#include "PUBG_BP_MasteryPose_classes.hpp"
#include "PUBG_Engine_classes.hpp"
namespace SDK
{
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"1263178881@qq.com"
] | 1263178881@qq.com |
e5d69ca71865668c93a3326bc000a2f7a3a72739 | 9a3fc0a5abe3bf504a63a643e6501a2f3452ba6d | /tc/testprograms/TwiceString.cpp | 5f08bd18671248b680bbc1171dea6b6dcbe61f16 | [] | no_license | rodolfo15625/algorithms | 7034f856487c69553205198700211d7afb885d4c | 9e198ff0c117512373ca2d9d706015009dac1d65 | refs/heads/master | 2021-01-18T08:30:19.777193 | 2014-10-20T13:15:09 | 2014-10-20T13:15:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,806 | cpp | #include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#define all(v) (v).begin(),(v).end()
#define sz size()
#define REP(i,a,b) for(i=int(a);i<int(b);i++)
#define fill(x,i) memset(x,i,sizeof(x))
#define foreach(c,it) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++)
using namespace std;
class TwiceString {
public:string getShortest(string s) {
int i,j,n=s.sz;
string aux,ans="";
REP(i,0,n){
aux=s+s.substr(i);
aux[0]='1';
if(aux.find(s)!=-1)
ans=s+s.substr(i);
}
return ans;
}
//Powered by [Ziklon]
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, string p0, bool hasAnswer, string p1) {
cout << "Test " << testNum << ": [" << "\"" << p0 << "\"";
cout << "]" << endl;
TwiceString *obj;
string answer;
obj = new TwiceString();
clock_t startTime = clock();
answer = obj->getShortest(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << "\"" << p1 << "\"" << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << "\"" << answer << "\"" << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
string p0;
string p1;
{
// ----- test 0 -----
p0 = "aba";
p1 = "ababa";
all_right = KawigiEdit_RunTest(0, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 1 -----
p0 = "xxxxx";
p1 = "xxxxxx";
all_right = KawigiEdit_RunTest(1, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 2 -----
p0 = "topcoder";
p1 = "topcodertopcoder";
all_right = KawigiEdit_RunTest(2, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 3 -----
p0 = "abracadabra";
p1 = "abracadabracadabra";
all_right = KawigiEdit_RunTest(3, p0, true, p1) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
| [
"winftc@gmail.com"
] | winftc@gmail.com |
9b0d0951ab68c4c4d6052207eb1465666a7c79bc | ec749cdca9d7c9efda5a6ad6481b14382ddb4119 | /bluetoothTesting/SoftwareSerial.h | 1cbe5564a9d64ef59fadbf39be4106eb128d8f61 | [] | no_license | AryaMirshafii/hearingCarFall2018Arduino | ab7406dd5f5717853556b98470610490b0eafba5 | 08b584a2842cc389a62520dc3c3bf027dbed10e8 | refs/heads/master | 2020-04-02T22:34:55.825737 | 2019-01-15T15:51:52 | 2019-01-15T15:51:52 | 154,838,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,168 | h | /*
SoftwareSerial.cpp - library for Arduino M0/M0 pro
Copyright (c) 2016 Arduino Srl. All rights reserved.
Written by Chiara Ruggeri (chiara@arduino.org)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Enjoy!
*/
#ifndef SoftwareSerial_h
#define SoftwareSerial_h
#include <inttypes.h>
#include <Stream.h>
#include <variant.h>
/******************************************************************************
* Definitions
******************************************************************************/
#define _SS_MAX_RX_BUFF 64 // RX buffer size
#ifndef GCC_VERSION
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
class SoftwareSerial : public Stream
{
private:
// per object data
uint8_t _transmitPin;
uint8_t _receivePin;
uint32_t _receiveBitMask;
volatile PORT_IN_Type *_receivePortRegister;
uint32_t _transmitBitMask;
volatile PORT_OUT_Type *_transmitPortRegister;
// Expressed as 4-cycle delays (must never be 0!)
uint16_t _rx_delay_centering;
uint16_t _rx_delay_intrabit;
uint16_t _rx_delay_stopbit;
uint16_t _tx_delay;
uint16_t _buffer_overflow:1;
uint16_t _inverse_logic:1;
// static data
static char _receive_buffer[_SS_MAX_RX_BUFF];
static volatile uint8_t _receive_buffer_tail;
static volatile uint8_t _receive_buffer_head;
static SoftwareSerial *active_object;
// private methods
void recv() __attribute__((__always_inline__));
uint32_t rx_pin_read();
void tx_pin_write(uint8_t pin_state) __attribute__((__always_inline__));
void setTX(uint8_t transmitPin);
void setRX(uint8_t receivePin);
void setRxIntMsk(bool enable) __attribute__((__always_inline__));
public:
// public methods
SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);
~SoftwareSerial();
void begin(long speed);
bool listen();
void end();
bool isListening() { return this == active_object; }
bool stopListening();
bool overflow() { bool ret = _buffer_overflow; if (ret) _buffer_overflow = false; return ret; }
int peek();
virtual size_t write(uint8_t byte);
virtual int read();
virtual int available();
virtual void flush();
operator bool() { return true; }
using Print::write;
// public only for easy access by interrupt handlers
static inline void handle_interrupt() __attribute__((__always_inline__));
};
// Arduino 0012 workaround
#undef int
#undef char
#undef long
#undef byte
#undef float
#undef abs
#undef round
#endif
| [
"amirshafii3@gatech.edu"
] | amirshafii3@gatech.edu |
fcaf7e904db2e7091454cba01fb71ddcea51f316 | a6945379ff5d85ffb7834baeb130c67d08b3c8ca | /v8/src/compiler/access-info.cc | 8e331c94cf77b7ebccef30def2b820fdc27c13d5 | [
"bzip2-1.0.6",
"BSD-3-Clause",
"SunPro"
] | permissive | superfly/deno_third_party | 03c2dcc9c56db7f780e80a98d0cd694817f5fc8b | 88acf8ea59d67442f7e06abf6fe73cf9d2ef3261 | refs/heads/master | 2020-05-18T10:18:23.933753 | 2019-04-23T15:57:05 | 2019-04-23T15:57:05 | 184,348,349 | 0 | 0 | null | 2019-05-01T00:13:31 | 2019-05-01T00:13:30 | null | UTF-8 | C++ | false | false | 30,041 | cc | // Copyright 2015 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.
#include <ostream>
#include "src/compiler/access-info.h"
#include "src/accessors.h"
#include "src/compiler/compilation-dependencies.h"
#include "src/compiler/type-cache.h"
#include "src/field-index-inl.h"
#include "src/field-type.h"
#include "src/ic/call-optimization.h"
#include "src/objects-inl.h"
#include "src/objects/cell-inl.h"
#include "src/objects/module-inl.h"
#include "src/objects/struct-inl.h"
#include "src/objects/templates.h"
namespace v8 {
namespace internal {
namespace compiler {
namespace {
bool CanInlinePropertyAccess(Handle<Map> map) {
// We can inline property access to prototypes of all primitives, except
// the special Oddball ones that have no wrapper counterparts (i.e. Null,
// Undefined and TheHole).
STATIC_ASSERT(ODDBALL_TYPE == LAST_PRIMITIVE_TYPE);
if (map->IsBooleanMap()) return true;
if (map->instance_type() < LAST_PRIMITIVE_TYPE) return true;
return map->IsJSObjectMap() && !map->is_dictionary_map() &&
!map->has_named_interceptor() &&
// TODO(verwaest): Whitelist contexts to which we have access.
!map->is_access_check_needed();
}
} // namespace
std::ostream& operator<<(std::ostream& os, AccessMode access_mode) {
switch (access_mode) {
case AccessMode::kLoad:
return os << "Load";
case AccessMode::kStore:
return os << "Store";
case AccessMode::kStoreInLiteral:
return os << "StoreInLiteral";
}
UNREACHABLE();
}
ElementAccessInfo::ElementAccessInfo() = default;
ElementAccessInfo::ElementAccessInfo(MapHandles const& receiver_maps,
ElementsKind elements_kind)
: elements_kind_(elements_kind), receiver_maps_(receiver_maps) {
CHECK(!receiver_maps.empty());
}
// static
PropertyAccessInfo PropertyAccessInfo::NotFound(MapHandles const& receiver_maps,
MaybeHandle<JSObject> holder) {
return PropertyAccessInfo(kNotFound, holder, receiver_maps);
}
// static
PropertyAccessInfo PropertyAccessInfo::DataConstant(
MapHandles const& receiver_maps, Handle<Object> constant,
MaybeHandle<JSObject> holder) {
return PropertyAccessInfo(kDataConstant, holder, constant, receiver_maps);
}
// static
PropertyAccessInfo PropertyAccessInfo::DataField(
PropertyConstness constness, MapHandles const& receiver_maps,
FieldIndex field_index, MachineRepresentation field_representation,
Type field_type, MaybeHandle<Map> field_map, MaybeHandle<JSObject> holder,
MaybeHandle<Map> transition_map) {
Kind kind =
constness == PropertyConstness::kConst ? kDataConstantField : kDataField;
return PropertyAccessInfo(kind, holder, transition_map, field_index,
field_representation, field_type, field_map,
receiver_maps);
}
// static
PropertyAccessInfo PropertyAccessInfo::AccessorConstant(
MapHandles const& receiver_maps, Handle<Object> constant,
MaybeHandle<JSObject> holder) {
return PropertyAccessInfo(kAccessorConstant, holder, constant, receiver_maps);
}
// static
PropertyAccessInfo PropertyAccessInfo::ModuleExport(
MapHandles const& receiver_maps, Handle<Cell> cell) {
return PropertyAccessInfo(kModuleExport, MaybeHandle<JSObject>(), cell,
receiver_maps);
}
// static
PropertyAccessInfo PropertyAccessInfo::StringLength(
MapHandles const& receiver_maps) {
return PropertyAccessInfo(kStringLength, MaybeHandle<JSObject>(),
receiver_maps);
}
PropertyAccessInfo::PropertyAccessInfo()
: kind_(kInvalid),
field_representation_(MachineRepresentation::kNone),
field_type_(Type::None()) {}
PropertyAccessInfo::PropertyAccessInfo(Kind kind, MaybeHandle<JSObject> holder,
MapHandles const& receiver_maps)
: kind_(kind),
receiver_maps_(receiver_maps),
holder_(holder),
field_representation_(MachineRepresentation::kNone),
field_type_(Type::None()) {}
PropertyAccessInfo::PropertyAccessInfo(Kind kind, MaybeHandle<JSObject> holder,
Handle<Object> constant,
MapHandles const& receiver_maps)
: kind_(kind),
receiver_maps_(receiver_maps),
constant_(constant),
holder_(holder),
field_representation_(MachineRepresentation::kNone),
field_type_(Type::Any()) {}
PropertyAccessInfo::PropertyAccessInfo(
Kind kind, MaybeHandle<JSObject> holder, MaybeHandle<Map> transition_map,
FieldIndex field_index, MachineRepresentation field_representation,
Type field_type, MaybeHandle<Map> field_map,
MapHandles const& receiver_maps)
: kind_(kind),
receiver_maps_(receiver_maps),
transition_map_(transition_map),
holder_(holder),
field_index_(field_index),
field_representation_(field_representation),
field_type_(field_type),
field_map_(field_map) {}
bool PropertyAccessInfo::Merge(PropertyAccessInfo const* that,
AccessMode access_mode, Zone* zone) {
if (this->kind_ != that->kind_) return false;
if (this->holder_.address() != that->holder_.address()) return false;
switch (this->kind_) {
case kInvalid:
break;
case kDataField:
case kDataConstantField: {
// Check if we actually access the same field (we use the
// GetFieldAccessStubKey method here just like the ICs do
// since that way we only compare the relevant bits of the
// field indices).
if (this->field_index_.GetFieldAccessStubKey() ==
that->field_index_.GetFieldAccessStubKey()) {
switch (access_mode) {
case AccessMode::kLoad: {
if (this->field_representation_ != that->field_representation_) {
if (!IsAnyTagged(this->field_representation_) ||
!IsAnyTagged(that->field_representation_)) {
return false;
}
this->field_representation_ = MachineRepresentation::kTagged;
}
if (this->field_map_.address() != that->field_map_.address()) {
this->field_map_ = MaybeHandle<Map>();
}
break;
}
case AccessMode::kStore:
case AccessMode::kStoreInLiteral: {
// For stores, the field map and field representation information
// must match exactly, otherwise we cannot merge the stores. We
// also need to make sure that in case of transitioning stores,
// the transition targets match.
if (this->field_map_.address() != that->field_map_.address() ||
this->field_representation_ != that->field_representation_ ||
this->transition_map_.address() !=
that->transition_map_.address()) {
return false;
}
break;
}
}
// Merge the field type.
this->field_type_ =
Type::Union(this->field_type_, that->field_type_, zone);
// Merge the receiver maps.
this->receiver_maps_.insert(this->receiver_maps_.end(),
that->receiver_maps_.begin(),
that->receiver_maps_.end());
return true;
}
return false;
}
case kDataConstant:
case kAccessorConstant: {
// Check if we actually access the same constant.
if (this->constant_.address() == that->constant_.address()) {
this->receiver_maps_.insert(this->receiver_maps_.end(),
that->receiver_maps_.begin(),
that->receiver_maps_.end());
return true;
}
return false;
}
case kNotFound:
case kStringLength: {
this->receiver_maps_.insert(this->receiver_maps_.end(),
that->receiver_maps_.begin(),
that->receiver_maps_.end());
return true;
}
case kModuleExport: {
return false;
}
}
UNREACHABLE();
}
Handle<Cell> PropertyAccessInfo::export_cell() const {
DCHECK_EQ(kModuleExport, kind_);
return Handle<Cell>::cast(constant_);
}
AccessInfoFactory::AccessInfoFactory(JSHeapBroker* broker,
CompilationDependencies* dependencies,
Zone* zone)
: broker_(broker),
dependencies_(dependencies),
type_cache_(TypeCache::Get()),
zone_(zone) {}
bool AccessInfoFactory::ComputeElementAccessInfo(
Handle<Map> map, AccessMode access_mode,
ElementAccessInfo* access_info) const {
// Check if it is safe to inline element access for the {map}.
if (!CanInlineElementAccess(map)) return false;
ElementsKind const elements_kind = map->elements_kind();
*access_info = ElementAccessInfo(MapHandles{map}, elements_kind);
return true;
}
bool AccessInfoFactory::ComputeElementAccessInfos(
FeedbackNexus nexus, MapHandles const& maps, AccessMode access_mode,
ZoneVector<ElementAccessInfo>* access_infos) const {
ProcessedFeedback processed(broker()->zone());
ProcessFeedbackMapsForElementAccess(isolate(), maps, &processed);
if (FLAG_concurrent_inlining) {
if (broker()->HasFeedback(nexus)) {
// We have already processed the feedback for this nexus during
// serialization. Use that data instead of the data computed above.
ProcessedFeedback const& preprocessed =
broker()->GetOrCreateFeedback(nexus);
TRACE_BROKER(broker(),
"ComputeElementAccessInfos: using preprocessed feedback "
<< "(slot " << nexus.slot() << " of "
<< Brief(*nexus.vector_handle()) << "; "
<< preprocessed.receiver_maps.size() << "/"
<< preprocessed.transitions.size() << " vs "
<< processed.receiver_maps.size() << "/"
<< processed.transitions.size() << ").\n");
processed.receiver_maps = preprocessed.receiver_maps;
processed.transitions = preprocessed.transitions;
} else {
TRACE_BROKER(broker(),
"ComputeElementAccessInfos: missing preprocessed feedback "
<< "(slot " << nexus.slot() << " of "
<< Brief(*nexus.vector_handle()) << ").\n");
}
}
if (access_mode == AccessMode::kLoad) {
// For polymorphic loads of similar elements kinds (i.e. all tagged or all
// double), always use the "worst case" code without a transition. This is
// much faster than transitioning the elements to the worst case, trading a
// TransitionElementsKind for a CheckMaps, avoiding mutation of the array.
ElementAccessInfo access_info;
if (ConsolidateElementLoad(processed, &access_info)) {
access_infos->push_back(access_info);
return true;
}
}
for (Handle<Map> receiver_map : processed.receiver_maps) {
// Compute the element access information.
ElementAccessInfo access_info;
if (!ComputeElementAccessInfo(receiver_map, access_mode, &access_info)) {
return false;
}
// Collect the possible transitions for the {receiver_map}.
for (auto transition : processed.transitions) {
if (transition.second.is_identical_to(receiver_map)) {
access_info.AddTransitionSource(transition.first);
}
}
// Schedule the access information.
access_infos->push_back(access_info);
}
return true;
}
bool AccessInfoFactory::ComputeDataFieldAccessInfo(
Handle<Map> receiver_map, Handle<Map> map, MaybeHandle<JSObject> holder,
int number, AccessMode access_mode, PropertyAccessInfo* access_info) const {
DCHECK_NE(number, DescriptorArray::kNotFound);
Handle<DescriptorArray> descriptors(map->instance_descriptors(), isolate());
PropertyDetails const details = descriptors->GetDetails(number);
int index = descriptors->GetFieldIndex(number);
Representation details_representation = details.representation();
FieldIndex field_index =
FieldIndex::ForPropertyIndex(*map, index, details_representation);
Type field_type = Type::NonInternal();
MachineRepresentation field_representation = MachineRepresentation::kTagged;
MaybeHandle<Map> field_map;
if (details_representation.IsSmi()) {
field_type = Type::SignedSmall();
field_representation = MachineRepresentation::kTaggedSigned;
} else if (details_representation.IsDouble()) {
field_type = type_cache_->kFloat64;
field_representation = MachineRepresentation::kFloat64;
} else if (details_representation.IsHeapObject()) {
// Extract the field type from the property details (make sure its
// representation is TaggedPointer to reflect the heap object case).
field_representation = MachineRepresentation::kTaggedPointer;
Handle<FieldType> descriptors_field_type(descriptors->GetFieldType(number),
isolate());
if (descriptors_field_type->IsNone()) {
// Store is not safe if the field type was cleared.
if (access_mode == AccessMode::kStore) return false;
// The field type was cleared by the GC, so we don't know anything
// about the contents now.
} else if (descriptors_field_type->IsClass()) {
MapRef map_ref(broker(), map);
map_ref.SerializeOwnDescriptors(); // TODO(neis): Remove later.
dependencies()->DependOnFieldType(map_ref, number);
// Remember the field map, and try to infer a useful type.
Handle<Map> map(descriptors_field_type->AsClass(), isolate());
field_type = Type::For(MapRef(broker(), map));
field_map = MaybeHandle<Map>(map);
}
}
*access_info = PropertyAccessInfo::DataField(
details.constness(), MapHandles{receiver_map}, field_index,
field_representation, field_type, field_map, holder);
return true;
}
bool AccessInfoFactory::ComputeAccessorDescriptorAccessInfo(
Handle<Map> receiver_map, Handle<Name> name, Handle<Map> map,
MaybeHandle<JSObject> holder, int number, AccessMode access_mode,
PropertyAccessInfo* access_info) const {
DCHECK_NE(number, DescriptorArray::kNotFound);
Handle<DescriptorArray> descriptors(map->instance_descriptors(), isolate());
SLOW_DCHECK(number == descriptors->Search(*name, *map));
if (map->instance_type() == JS_MODULE_NAMESPACE_TYPE) {
DCHECK(map->is_prototype_map());
Handle<PrototypeInfo> proto_info(PrototypeInfo::cast(map->prototype_info()),
isolate());
Handle<JSModuleNamespace> module_namespace(
JSModuleNamespace::cast(proto_info->module_namespace()), isolate());
Handle<Cell> cell(
Cell::cast(module_namespace->module()->exports()->Lookup(
ReadOnlyRoots(isolate()), name, Smi::ToInt(name->GetHash()))),
isolate());
if (cell->value()->IsTheHole(isolate())) {
// This module has not been fully initialized yet.
return false;
}
*access_info =
PropertyAccessInfo::ModuleExport(MapHandles{receiver_map}, cell);
return true;
}
Handle<Object> accessors(descriptors->GetStrongValue(number), isolate());
if (!accessors->IsAccessorPair()) return false;
Handle<Object> accessor(access_mode == AccessMode::kLoad
? Handle<AccessorPair>::cast(accessors)->getter()
: Handle<AccessorPair>::cast(accessors)->setter(),
isolate());
if (!accessor->IsJSFunction()) {
CallOptimization optimization(isolate(), accessor);
if (!optimization.is_simple_api_call()) return false;
if (optimization.IsCrossContextLazyAccessorPair(
*broker()->native_context().object(), *map)) {
return false;
}
CallOptimization::HolderLookup lookup;
holder = optimization.LookupHolderOfExpectedType(receiver_map, &lookup);
if (lookup == CallOptimization::kHolderNotFound) return false;
DCHECK_IMPLIES(lookup == CallOptimization::kHolderIsReceiver,
holder.is_null());
DCHECK_IMPLIES(lookup == CallOptimization::kHolderFound, !holder.is_null());
if (V8_UNLIKELY(FLAG_runtime_stats)) return false;
}
if (access_mode == AccessMode::kLoad) {
Handle<Name> cached_property_name;
if (FunctionTemplateInfo::TryGetCachedPropertyName(isolate(), accessor)
.ToHandle(&cached_property_name)) {
if (ComputePropertyAccessInfo(map, cached_property_name, access_mode,
access_info)) {
return true;
}
}
}
*access_info = PropertyAccessInfo::AccessorConstant(MapHandles{receiver_map},
accessor, holder);
return true;
}
bool AccessInfoFactory::ComputePropertyAccessInfo(
Handle<Map> map, Handle<Name> name, AccessMode access_mode,
PropertyAccessInfo* access_info) const {
CHECK(name->IsUniqueName());
// Check if it is safe to inline property access for the {map}.
if (!CanInlinePropertyAccess(map)) return false;
// We support fast inline cases for certain JSObject getters.
if (access_mode == AccessMode::kLoad &&
LookupSpecialFieldAccessor(map, name, access_info)) {
return true;
}
// Remember the receiver map. We use {map} as loop variable.
Handle<Map> receiver_map = map;
MaybeHandle<JSObject> holder;
do {
// Lookup the named property on the {map}.
Handle<DescriptorArray> descriptors(map->instance_descriptors(), isolate());
int const number = descriptors->Search(*name, *map);
if (number != DescriptorArray::kNotFound) {
PropertyDetails const details = descriptors->GetDetails(number);
if (access_mode == AccessMode::kStore ||
access_mode == AccessMode::kStoreInLiteral) {
// Don't bother optimizing stores to read-only properties.
if (details.IsReadOnly()) {
return false;
}
if (details.kind() == kData && !holder.is_null()) {
// This is a store to a property not found on the receiver but on a
// prototype. According to ES6 section 9.1.9 [[Set]], we need to
// create a new data property on the receiver. We can still optimize
// if such a transition already exists.
return LookupTransition(receiver_map, name, holder, access_info);
}
}
if (details.location() == kField) {
if (details.kind() == kData) {
return ComputeDataFieldAccessInfo(receiver_map, map, holder, number,
access_mode, access_info);
} else {
DCHECK_EQ(kAccessor, details.kind());
// TODO(turbofan): Add support for general accessors?
return false;
}
} else {
DCHECK_EQ(kDescriptor, details.location());
if (details.kind() == kData) {
DCHECK(!FLAG_track_constant_fields);
*access_info = PropertyAccessInfo::DataConstant(
MapHandles{receiver_map},
handle(descriptors->GetStrongValue(number), isolate()), holder);
return true;
} else {
DCHECK_EQ(kAccessor, details.kind());
return ComputeAccessorDescriptorAccessInfo(receiver_map, name, map,
holder, number,
access_mode, access_info);
}
}
UNREACHABLE();
}
// The property wasn't found on {map}. Look on the prototype if appropriate.
// Don't search on the prototype chain for special indices in case of
// integer indexed exotic objects (see ES6 section 9.4.5).
if (map->IsJSTypedArrayMap() && name->IsString() &&
IsSpecialIndex(String::cast(*name))) {
return false;
}
// Don't search on the prototype when storing in literals.
if (access_mode == AccessMode::kStoreInLiteral) {
return LookupTransition(receiver_map, name, holder, access_info);
}
// Don't lookup private symbols on the prototype chain.
if (name->IsPrivate()) return false;
// Walk up the prototype chain.
if (!map->prototype()->IsJSObject()) {
// Perform the implicit ToObject for primitives here.
// Implemented according to ES6 section 7.3.2 GetV (V, P).
Handle<JSFunction> constructor;
if (Map::GetConstructorFunction(map, broker()->native_context().object())
.ToHandle(&constructor)) {
map = handle(constructor->initial_map(), isolate());
DCHECK(map->prototype()->IsJSObject());
} else if (map->prototype()->IsNull(isolate())) {
// Store to property not found on the receiver or any prototype, we need
// to transition to a new data property.
// Implemented according to ES6 section 9.1.9 [[Set]] (P, V, Receiver)
if (access_mode == AccessMode::kStore) {
return LookupTransition(receiver_map, name, holder, access_info);
}
// The property was not found, return undefined or throw depending
// on the language mode of the load operation.
// Implemented according to ES6 section 9.1.8 [[Get]] (P, Receiver)
*access_info =
PropertyAccessInfo::NotFound(MapHandles{receiver_map}, holder);
return true;
} else {
return false;
}
}
Handle<JSObject> map_prototype(JSObject::cast(map->prototype()), isolate());
if (map_prototype->map()->is_deprecated()) {
// Try to migrate the prototype object so we don't embed the deprecated
// map into the optimized code.
JSObject::TryMigrateInstance(map_prototype);
}
map = handle(map_prototype->map(), isolate());
holder = map_prototype;
} while (CanInlinePropertyAccess(map));
return false;
}
bool AccessInfoFactory::ComputePropertyAccessInfo(
MapHandles const& maps, Handle<Name> name, AccessMode access_mode,
PropertyAccessInfo* access_info) const {
ZoneVector<PropertyAccessInfo> access_infos(zone());
if (ComputePropertyAccessInfos(maps, name, access_mode, &access_infos) &&
access_infos.size() == 1) {
*access_info = access_infos.front();
return true;
}
return false;
}
bool AccessInfoFactory::ComputePropertyAccessInfos(
MapHandles const& maps, Handle<Name> name, AccessMode access_mode,
ZoneVector<PropertyAccessInfo>* access_infos) const {
ZoneVector<PropertyAccessInfo> infos(zone());
infos.reserve(maps.size());
for (Handle<Map> map : maps) {
PropertyAccessInfo access_info;
if (!ComputePropertyAccessInfo(map, name, access_mode, &access_info)) {
return false;
}
infos.push_back(access_info);
}
// Merge as many as possible and push into {access_infos}.
for (auto it = infos.begin(), end = infos.end(); it != end; ++it) {
bool merged = false;
for (auto ot = it + 1; ot != end; ++ot) {
if (ot->Merge(&(*it), access_mode, zone())) {
merged = true;
break;
}
}
if (!merged) access_infos->push_back(*it);
}
return true;
}
namespace {
Maybe<ElementsKind> GeneralizeElementsKind(ElementsKind this_kind,
ElementsKind that_kind) {
if (IsHoleyElementsKind(this_kind)) {
that_kind = GetHoleyElementsKind(that_kind);
} else if (IsHoleyElementsKind(that_kind)) {
this_kind = GetHoleyElementsKind(this_kind);
}
if (this_kind == that_kind) return Just(this_kind);
if (IsDoubleElementsKind(that_kind) == IsDoubleElementsKind(this_kind)) {
if (IsMoreGeneralElementsKindTransition(that_kind, this_kind)) {
return Just(this_kind);
}
if (IsMoreGeneralElementsKindTransition(this_kind, that_kind)) {
return Just(that_kind);
}
}
return Nothing<ElementsKind>();
}
} // namespace
bool AccessInfoFactory::ConsolidateElementLoad(
ProcessedFeedback const& processed, ElementAccessInfo* access_info) const {
CHECK(!processed.receiver_maps.empty());
// We want to look at each map but the maps are split across
// {processed.receiver_maps} and {processed.transitions}.
InstanceType instance_type = processed.receiver_maps.front()->instance_type();
ElementsKind elements_kind = processed.receiver_maps.front()->elements_kind();
auto processMap = [&](Handle<Map> map) {
if (!CanInlineElementAccess(map) || map->instance_type() != instance_type) {
return false;
}
if (!GeneralizeElementsKind(elements_kind, map->elements_kind())
.To(&elements_kind)) {
return false;
}
return true;
};
for (Handle<Map> map : processed.receiver_maps) {
if (!processMap(map)) return false;
}
MapHandles maps(processed.receiver_maps.begin(),
processed.receiver_maps.end());
for (auto& pair : processed.transitions) {
if (!processMap(pair.first) || !processMap(pair.second)) return false;
maps.push_back(pair.first);
maps.push_back(pair.second);
}
// {maps} may now contain duplicate entries, but that shouldn't matter.
*access_info = ElementAccessInfo(maps, elements_kind);
return true;
}
bool AccessInfoFactory::LookupSpecialFieldAccessor(
Handle<Map> map, Handle<Name> name, PropertyAccessInfo* access_info) const {
// Check for String::length field accessor.
if (map->IsStringMap()) {
if (Name::Equals(isolate(), name, isolate()->factory()->length_string())) {
*access_info = PropertyAccessInfo::StringLength(MapHandles{map});
return true;
}
return false;
}
// Check for special JSObject field accessors.
FieldIndex field_index;
if (Accessors::IsJSObjectFieldAccessor(isolate(), map, name, &field_index)) {
Type field_type = Type::NonInternal();
MachineRepresentation field_representation = MachineRepresentation::kTagged;
if (map->IsJSArrayMap()) {
DCHECK(
Name::Equals(isolate(), isolate()->factory()->length_string(), name));
// The JSArray::length property is a smi in the range
// [0, FixedDoubleArray::kMaxLength] in case of fast double
// elements, a smi in the range [0, FixedArray::kMaxLength]
// in case of other fast elements, and [0, kMaxUInt32] in
// case of other arrays.
if (IsDoubleElementsKind(map->elements_kind())) {
field_type = type_cache_->kFixedDoubleArrayLengthType;
field_representation = MachineRepresentation::kTaggedSigned;
} else if (IsFastElementsKind(map->elements_kind())) {
field_type = type_cache_->kFixedArrayLengthType;
field_representation = MachineRepresentation::kTaggedSigned;
} else {
field_type = type_cache_->kJSArrayLengthType;
}
}
// Special fields are always mutable.
*access_info = PropertyAccessInfo::DataField(
PropertyConstness::kMutable, MapHandles{map}, field_index,
field_representation, field_type);
return true;
}
return false;
}
bool AccessInfoFactory::LookupTransition(
Handle<Map> map, Handle<Name> name, MaybeHandle<JSObject> holder,
PropertyAccessInfo* access_info) const {
// Check if the {map} has a data transition with the given {name}.
Map transition =
TransitionsAccessor(isolate(), map).SearchTransition(*name, kData, NONE);
if (transition.is_null()) return false;
Handle<Map> transition_map(transition, isolate());
int const number = transition_map->LastAdded();
PropertyDetails const details =
transition_map->instance_descriptors()->GetDetails(number);
// Don't bother optimizing stores to read-only properties.
if (details.IsReadOnly()) return false;
// TODO(bmeurer): Handle transition to data constant?
if (details.location() != kField) return false;
int const index = details.field_index();
Representation details_representation = details.representation();
FieldIndex field_index = FieldIndex::ForPropertyIndex(*transition_map, index,
details_representation);
Type field_type = Type::NonInternal();
MaybeHandle<Map> field_map;
MachineRepresentation field_representation = MachineRepresentation::kTagged;
if (details_representation.IsSmi()) {
field_type = Type::SignedSmall();
field_representation = MachineRepresentation::kTaggedSigned;
} else if (details_representation.IsDouble()) {
field_type = type_cache_->kFloat64;
field_representation = MachineRepresentation::kFloat64;
} else if (details_representation.IsHeapObject()) {
// Extract the field type from the property details (make sure its
// representation is TaggedPointer to reflect the heap object case).
field_representation = MachineRepresentation::kTaggedPointer;
Handle<FieldType> descriptors_field_type(
transition_map->instance_descriptors()->GetFieldType(number),
isolate());
if (descriptors_field_type->IsNone()) {
// Store is not safe if the field type was cleared.
return false;
} else if (descriptors_field_type->IsClass()) {
MapRef transition_map_ref(broker(), transition_map);
transition_map_ref
.SerializeOwnDescriptors(); // TODO(neis): Remove later.
dependencies()->DependOnFieldType(transition_map_ref, number);
// Remember the field map, and try to infer a useful type.
Handle<Map> map(descriptors_field_type->AsClass(), isolate());
field_type = Type::For(MapRef(broker(), map));
field_map = MaybeHandle<Map>(map);
}
}
dependencies()->DependOnTransition(MapRef(broker(), transition_map));
// Transitioning stores are never stores to constant fields.
*access_info = PropertyAccessInfo::DataField(
PropertyConstness::kMutable, MapHandles{map}, field_index,
field_representation, field_type, field_map, holder, transition_map);
return true;
}
} // namespace compiler
} // namespace internal
} // namespace v8
| [
"ry@tinyclouds.org"
] | ry@tinyclouds.org |
187db7a4534338d6d82c695a2ced701060733fa0 | 0144bbc52060b3b1be83d40ef0fac66f600aba58 | /assignment_package/src/mygl.cpp | 35fe5467b218fb7dd36380b4eacbc767676faaa2 | [] | no_license | 19sweintraub/OpenGL | 98954d928c95eb1a5d5b0670a39c07073325544a | e832cfb7e46a5b0ba677bf1ec27c0364ce7ca696 | refs/heads/master | 2020-04-24T23:57:49.928766 | 2019-02-24T16:41:49 | 2019-02-24T16:41:49 | 172,362,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,209 | cpp | #include "mygl.h"
#include <la.h>
#include <QResizeEvent>
#include <iostream>
MyGL::MyGL(QWidget *parent)
: OpenGLContext(parent),
m_geomQuad(this), m_camera(640, 480, glm::vec3(0, 0, 12), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)),
m_surfaceShaders(), m_postprocessShaders(),
mp_progSurfaceCurrent(nullptr),
mp_progPostprocessCurrent(nullptr),
m_matcapTextures(), mp_matcapTexCurrent(nullptr),
m_frameBuffer(-1),
m_renderedTexture(-1),
m_depthRenderBuffer(-1),
m_time(0.f), m_mousePosPrev()
{
setFocusPolicy(Qt::StrongFocus);
}
MyGL::~MyGL()
{
makeCurrent();
glDeleteVertexArrays(1, &m_vao);
m_geomQuad.destroy();
}
void MyGL::initializeGL()
{
// Create an OpenGL context using Qt's QOpenGLFunctions_3_2_Core class
// If you were programming in a non-Qt context you might use GLEW (GL Extension Wrangler)instead
initializeOpenGLFunctions();
// Print out some information about the current OpenGL context
debugContextVersion();
// Set a few settings/modes in OpenGL rendering
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POLYGON_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
// Set the size with which points should be rendered
glPointSize(5);
// Set the color with which the screen is filled at the start of each render call.
glClearColor(0.5, 0.5, 0.5, 1);
printGLErrorLog();
// Create a Vertex Attribute Object
glGenVertexArrays(1, &m_vao);
createRenderBuffers();
m_geomQuad.create();
createShaders();
createMeshes();
createMatcapTextures();
// We have to have a VAO bound in OpenGL 3.2 Core. But if we're not
// using multiple VAOs, we can just bind one once.
glBindVertexArray(m_vao);
}
void MyGL::resizeGL(int w, int h)
{
mp_progSurfaceCurrent->setViewProjMatrix(m_camera.getView(), m_camera.getProj());
for(std::shared_ptr<PostProcessShader> p : m_postprocessShaders)
{
p->setDimensions(glm::ivec2(w, h));
}
printGLErrorLog();
}
//This function is called by Qt any time your GL window is supposed to update
//For example, when the function update() is called, paintGL is called implicitly.
void MyGL::paintGL()
{
render3DScene();
performPostprocessRenderPass();
mp_progSurfaceCurrent->setTime(m_time);
mp_progPostprocessCurrent->setTime(m_time);
m_time++;
}
void MyGL::render3DScene()
{
// Render the 3D scene to our frame buffer
// Render to our framebuffer rather than the viewport
glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer);
// Render on the whole framebuffer, complete from the lower left corner to the upper right
glViewport(0,0,this->width() * this->devicePixelRatio(), this->height() * this->devicePixelRatio());
// Clear the screen so that we only see newly drawn images
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Initialize camera vector
mp_progSurfaceCurrent->setCamVector(m_camera.eye);
// Draw the background texture first
mp_modelCurrent->bindBGTexture();
mp_progPostprocessNoOp->draw(m_geomQuad, 2);
// Set the surface shader's transformation matrices
mp_progSurfaceCurrent->setViewProjMatrix(m_camera.getView(), m_camera.getProj());
mp_progSurfaceCurrent->setModelMatrix(glm::mat4());
bindAppropriateTexture();
// Draw the model
mp_progSurfaceCurrent->draw(*mp_modelCurrent, 0);
}
void MyGL::performPostprocessRenderPass()
{
// Render the frame buffer as a texture on a screen-size quad
// Tell OpenGL to render to the viewport's frame buffer
glBindFramebuffer(GL_FRAMEBUFFER, this->defaultFramebufferObject());
// Render on the whole framebuffer, complete from the lower left corner to the upper right
glViewport(0,0,this->width() * this->devicePixelRatio(), this->height() * this->devicePixelRatio());
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Bind our texture in Texture Unit 0
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_renderedTexture);
mp_progPostprocessCurrent->draw(m_geomQuad, 0);
}
void MyGL::createRenderBuffers()
{
// Initialize the frame buffers and render textures
glGenFramebuffers(1, &m_frameBuffer);
glGenTextures(1, &m_renderedTexture);
glGenRenderbuffers(1, &m_depthRenderBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer);
// Bind our texture so that all functions that deal with textures will interact with this one
glBindTexture(GL_TEXTURE_2D, m_renderedTexture);
// Give an empty image to OpenGL ( the last "0" )
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->width() * this->devicePixelRatio(), this->height() * this->devicePixelRatio(), 0, GL_RGB, GL_UNSIGNED_BYTE, (void*)0);
// Set the render settings for the texture we've just created.
// Essentially zero filtering on the "texture" so it appears exactly as rendered
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// Clamp the colors at the edge of our texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Initialize our depth buffer
glBindRenderbuffer(GL_RENDERBUFFER, m_depthRenderBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, this->width() * this->devicePixelRatio(), this->height() * this->devicePixelRatio());
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthRenderBuffer);
// Set m_renderedTexture as the color output of our frame buffer
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_renderedTexture, 0);
// Sets the color output of the fragment shader to be stored in GL_COLOR_ATTACHMENT0, which we previously set to m_renderedTextures[i]
GLenum drawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, drawBuffers); // "1" is the size of drawBuffers
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
std::cout << "Frame buffer did not initialize correctly..." << std::endl;
printGLErrorLog();
}
}
void MyGL::createShaders()
{
// Surface shaders
std::shared_ptr<SurfaceShader> lambert = std::make_shared<SurfaceShader>(this);
lambert->create(":/glsl/surface/lambert.vert.glsl", ":/glsl/surface/lambert.frag.glsl");
m_surfaceShaders.push_back(lambert);
std::shared_ptr<SurfaceShader> blinnPhong = std::make_shared<SurfaceShader>(this);
blinnPhong->create(":/glsl/surface/blinnPhong.vert.glsl", ":/glsl/surface/blinnPhong.frag.glsl");
m_surfaceShaders.push_back(blinnPhong);
std::shared_ptr<SurfaceShader> matcap = std::make_shared<SurfaceShader>(this);
matcap->create(":/glsl/surface/matcap.vert.glsl", ":/glsl/surface/matcap.frag.glsl");
m_surfaceShaders.push_back(matcap);
std::shared_ptr<SurfaceShader> gradient = std::make_shared<SurfaceShader>(this);
gradient->create(":/glsl/surface/gradient.vert.glsl", ":/glsl/surface/gradient.frag.glsl");
m_surfaceShaders.push_back(gradient);
std::shared_ptr<SurfaceShader> deform = std::make_shared<SurfaceShader>(this);
deform->create(":/glsl/surface/deform.vert.glsl", ":/glsl/surface/deform.frag.glsl");
m_surfaceShaders.push_back(deform);
slot_setCurrentSurfaceShaderProgram(0);
// Post-process shaders
std::shared_ptr<PostProcessShader> noOp = std::make_shared<PostProcessShader>(this);
noOp->create(":/glsl/post/passthrough.vert.glsl", ":/glsl/post/noOp.frag.glsl");
m_postprocessShaders.push_back(noOp);
std::shared_ptr<PostProcessShader> greyscale = std::make_shared<PostProcessShader>(this);
greyscale->create(":/glsl/post/passthrough.vert.glsl", ":/glsl/post/greyscale.frag.glsl");
m_postprocessShaders.push_back(greyscale);
std::shared_ptr<PostProcessShader> gaussian = std::make_shared<PostProcessShader>(this);
gaussian->create(":/glsl/post/passthrough.vert.glsl", ":/glsl/post/gaussian.frag.glsl");
m_postprocessShaders.push_back(gaussian);
std::shared_ptr<PostProcessShader> sobel = std::make_shared<PostProcessShader>(this);
sobel->create(":/glsl/post/passthrough.vert.glsl", ":/glsl/post/sobel.frag.glsl");
m_postprocessShaders.push_back(sobel);
std::shared_ptr<PostProcessShader> bloom = std::make_shared<PostProcessShader>(this);
bloom->create(":/glsl/post/passthrough.vert.glsl", ":/glsl/post/bloom.frag.glsl");
m_postprocessShaders.push_back(bloom);
std::shared_ptr<PostProcessShader> worley = std::make_shared<PostProcessShader>(this);
worley->create(":/glsl/post/passthrough.vert.glsl", ":/glsl/post/worleywarp.frag.glsl");
m_postprocessShaders.push_back(worley);
std::shared_ptr<PostProcessShader> mouse = std::make_shared<PostProcessShader>(this);
mouse->create(":/glsl/post/passthrough.vert.glsl", ":/glsl/post/worleywarp_copy.frag.glsl");
m_postprocessShaders.push_back(mouse);
slot_setCurrentPostprocessShaderProgram(0);
mp_progPostprocessNoOp = m_postprocessShaders[0].get();
}
void MyGL::createMeshes()
{
std::shared_ptr<Mesh> wahoo = std::make_shared<Mesh>(this);
wahoo->createFromOBJ(":/objs/wahoo.obj", ":/textures/wahoo.bmp", ":/textures/smb.jpg");
wahoo->loadTexture();
wahoo->loadBGTexture();
m_models.push_back(wahoo);
std::shared_ptr<Mesh> cow = std::make_shared<Mesh>(this);
cow->createFromOBJ(":/objs/cow.obj", ":/textures/uvTest.jpg", ":/textures/winxp.jpg");
cow->loadTexture();
cow->loadBGTexture();
m_models.push_back(cow);
std::shared_ptr<Mesh> cube = std::make_shared<Mesh>(this);
cube->createCube(":/textures/fractal.jpg", ":/textures/mengersponge.jpg");
cube->loadTexture();
cube->loadBGTexture();
m_models.push_back(cube);
slot_setCurrentModel(0);
}
void MyGL::createMatcapTextures()
{
std::shared_ptr<Texture> zbrush = std::make_shared<Texture>(this);
zbrush->create(":/textures/matcaps/00ZBrush_RedWax.png");
m_matcapTextures.push_back(zbrush);
std::shared_ptr<Texture> redPlastic = std::make_shared<Texture>(this);
redPlastic->create(":/textures/matcaps/JG_Red.png");
m_matcapTextures.push_back(redPlastic);
std::shared_ptr<Texture> chrome = std::make_shared<Texture>(this);
chrome->create(":/textures/matcaps/silver.jpg");
m_matcapTextures.push_back(chrome);
std::shared_ptr<Texture> pearl = std::make_shared<Texture>(this);
pearl->create(":/textures/matcaps/pearl.jpg");
m_matcapTextures.push_back(pearl);
std::shared_ptr<Texture> orangeGreen = std::make_shared<Texture>(this);
orangeGreen->create(":/textures/matcaps/JGSpecial_01.png");
m_matcapTextures.push_back(orangeGreen);
std::shared_ptr<Texture> blurple = std::make_shared<Texture>(this);
blurple->create(":/textures/matcaps/Shiny_Fire_1c.png");
m_matcapTextures.push_back(blurple);
std::shared_ptr<Texture> outline = std::make_shared<Texture>(this);
outline->create(":/textures/matcaps/Outline.png");
m_matcapTextures.push_back(outline);
std::shared_ptr<Texture> normals = std::make_shared<Texture>(this);
normals->create(":/textures/matcaps/normals.jpg");
m_matcapTextures.push_back(normals);
// If this vector of textures were to be altered
// while the program was running, storing a pointer
// to an element within it would be bad news, since
// the elements inside would not be guaranteed to be
// in the same memory as before.
// However, this vector's contents are only ever modified
// in this function, which is called exactly once in the
// program's lifetime.
slot_setCurrentMatcapTexture(0);
}
void MyGL::bindAppropriateTexture()
{
// Matcap
if(mp_progSurfaceCurrent == m_surfaceShaders[2].get())
{
mp_matcapTexCurrent->bind(0);
}
// Default case, use the texture provided by the model to be rendered
else
{
mp_modelCurrent->bindTexture();
}
}
| [
"sweint@seas.upenn.edu"
] | sweint@seas.upenn.edu |
457a0020c70107b42ac4c53d01f9de7a8453350f | 737b61c84095b8e8a65597a228c8b74b1d9edc9c | /main.cpp | 032679258c53a4ec0efdedfabe0fcbb8e46c9abd | [] | no_license | yeojinia/feature_selection_project1 | 5670f90c3f0b065fcc9e6b3f8e111b424d571768 | e50a2b787b6ed8d6515e70d8b15a61d68ffe8e2d | refs/heads/master | 2021-07-06T07:48:35.330138 | 2020-12-01T18:48:08 | 2020-12-01T18:48:08 | 211,745,180 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | cpp | #include "utils.h"
int main()
{
const char* filename = "lpga2009.txt";
Dataset data = read_data(filename);
int max_iteration = 10000;
float learning_rate = 0.001;
LinearRegressionModel* linear_reg = LinearRegressionModel::getInstance(data);
std::cout << "Training Started." << std::endl ;
linear_reg->train(max_iteration, learning_rate);
linear_reg->print_best_model();
linear_reg->select_features();
Sleep(50000);
return 0;
} | [
"kimyea@flip1.engr.oregonstate.edu"
] | kimyea@flip1.engr.oregonstate.edu |
ae6f0a10d560c97e17d4449204c9cec09dc8450f | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/webrtc/modules/audio_processing/logging/apm_data_dumper.cc | 65d2167d375e9c9e6ec43d13a5488bfc2a3a34ff | [
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 2,873 | cc | /*
* Copyright (c) 2016 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.
*/
#include "modules/audio_processing/logging/apm_data_dumper.h"
#include "absl/strings/string_view.h"
#include "rtc_base/strings/string_builder.h"
// Check to verify that the define is properly set.
#if !defined(WEBRTC_APM_DEBUG_DUMP) || \
(WEBRTC_APM_DEBUG_DUMP != 0 && WEBRTC_APM_DEBUG_DUMP != 1)
#error "Set WEBRTC_APM_DEBUG_DUMP to either 0 or 1"
#endif
namespace webrtc {
namespace {
#if WEBRTC_APM_DEBUG_DUMP == 1
#if defined(WEBRTC_WIN)
constexpr char kPathDelimiter = '\\';
#else
constexpr char kPathDelimiter = '/';
#endif
std::string FormFileName(absl::string_view output_dir,
absl::string_view name,
int instance_index,
int reinit_index,
absl::string_view suffix) {
char buf[1024];
rtc::SimpleStringBuilder ss(buf);
if (!output_dir.empty()) {
ss << output_dir;
if (output_dir.back() != kPathDelimiter) {
ss << kPathDelimiter;
}
}
ss << name << "_" << instance_index << "-" << reinit_index << suffix;
return ss.str();
}
#endif
} // namespace
#if WEBRTC_APM_DEBUG_DUMP == 1
ApmDataDumper::ApmDataDumper(int instance_index)
: instance_index_(instance_index) {}
#else
ApmDataDumper::ApmDataDumper(int instance_index) {}
#endif
ApmDataDumper::~ApmDataDumper() = default;
#if WEBRTC_APM_DEBUG_DUMP == 1
bool ApmDataDumper::recording_activated_ = false;
absl::optional<int> ApmDataDumper::dump_set_to_use_;
char ApmDataDumper::output_dir_[] = "";
FILE* ApmDataDumper::GetRawFile(absl::string_view name) {
std::string filename = FormFileName(output_dir_, name, instance_index_,
recording_set_index_, ".dat");
auto& f = raw_files_[filename];
if (!f) {
f.reset(fopen(filename.c_str(), "wb"));
RTC_CHECK(f.get()) << "Cannot write to " << filename << ".";
}
return f.get();
}
WavWriter* ApmDataDumper::GetWavFile(absl::string_view name,
int sample_rate_hz,
int num_channels,
WavFile::SampleFormat format) {
std::string filename = FormFileName(output_dir_, name, instance_index_,
recording_set_index_, ".wav");
auto& f = wav_files_[filename];
if (!f) {
f.reset(
new WavWriter(filename.c_str(), sample_rate_hz, num_channels, format));
}
return f.get();
}
#endif
} // namespace webrtc
| [
"jengelh@inai.de"
] | jengelh@inai.de |
a8f2d659d6e38da87bbd4557dc6c7b84b857998a | 47f9c8c46cb7a43bc2d390c7f1039ad8ffbc339f | /src_mod/game_shared/physics_main_shared.cpp | 1c7ea677be8cb98f537c193ca3f53260c8ec60f9 | [] | no_license | SourceEnginePlayground/source-sdk-2004 | 4135e00b06d8491baf174d19897950c40ef6112c | 962ba835716d3e6d778054ab3fb4534bf3b35e1a | refs/heads/master | 2023-03-27T15:04:00.381752 | 2021-03-24T06:42:27 | 2021-03-24T06:42:27 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 54,390 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "engine/IEngineSound.h"
#include "mempool.h"
#include "movevars_shared.h"
#include "utlrbtree.h"
#include "tier0/vprof.h"
#include "entitydatainstantiator.h"
#include "positionwatcher.h"
#include "movetype_push.h"
#include "igamesystem.h"
#include "utlmultilist.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// memory pool for storing links between entities
static CMemoryPool g_EdictTouchLinks( sizeof(touchlink_t), 512, CMemoryPool::GROW_NONE, "g_EdictTouchLinks");
static CMemoryPool g_EntityGroundLinks( sizeof( groundlink_t ), MAX_EDICTS, CMemoryPool::GROW_NONE, "g_EntityGroundLinks");
static CUtlMultiList<positionwatcher_t, unsigned short> g_PositionWatcherList;
int linksallocated = 0;
int groundlinksallocated = 0;
// Prints warnings if any entity think functions take longer than this many milliseconds
#ifdef _DEBUG
#define DEF_THINK_LIMIT "20"
#else
#define DEF_THINK_LIMIT "10"
#endif
ConVar think_limit( "think_limit", DEF_THINK_LIMIT, FCVAR_REPLICATED, "Maximum think time in milliseconds, warning is printed if this is exceeded." );
//-----------------------------------------------------------------------------
// Purpose: System for hanging objects off of CBaseEntity, etc.
// Externalized data objects ( see sharreddefs.h for enum )
//-----------------------------------------------------------------------------
class CDataObjectAccessSystem : public CAutoGameSystem
{
public:
enum
{
MAX_ACCESSORS = 32,
};
CDataObjectAccessSystem()
{
COMPILE_TIME_ASSERT( NUM_DATAOBJECT_TYPES <= MAX_ACCESSORS );
Q_memset( m_Accessors, 0, sizeof( m_Accessors ) );
}
virtual bool Init()
{
AddDataAccessor( TOUCHLINK, new CEntityDataInstantiator< touchlink_t > );
AddDataAccessor( GROUNDLINK, new CEntityDataInstantiator< groundlink_t > );
AddDataAccessor( STEPSIMULATION, new CEntityDataInstantiator< StepSimulationData > );
AddDataAccessor( MODELWIDTHSCALE, new CEntityDataInstantiator< ModelWidthScale > );
AddDataAccessor( POSITIONWATCHER, new CEntityDataInstantiator< CPositionWatcherList > );
AddDataAccessor( PHYSICSPUSHLIST, new CEntityDataInstantiator< physicspushlist_t > );
return true;
}
virtual void Shutdown()
{
for ( int i = 0; i < MAX_ACCESSORS; i++ )
{
delete m_Accessors[ i ];
m_Accessors[ i ] = 0;
}
}
void *GetDataObject( int type, const CBaseEntity *instance )
{
if ( !IsValidType( type ) )
{
Assert( !"Bogus type" );
return NULL;
}
return m_Accessors[ type ]->GetDataObject( instance );
}
void *CreateDataObject( int type, CBaseEntity *instance )
{
if ( !IsValidType( type ) )
{
Assert( !"Bogus type" );
return NULL;
}
return m_Accessors[ type ]->CreateDataObject( instance );
}
void DestroyDataObject( int type, CBaseEntity *instance )
{
if ( !IsValidType( type ) )
{
Assert( !"Bogus type" );
return;
}
m_Accessors[ type ]->DestroyDataObject( instance );
}
private:
bool IsValidType( int type ) const
{
if ( type < 0 || type >= MAX_ACCESSORS )
return false;
if ( m_Accessors[ type ] == NULL )
return false;
return true;
}
void AddDataAccessor( int type, IEntityDataInstantiator *instantiator )
{
if ( type < 0 || type >= MAX_ACCESSORS )
{
Assert( !"AddDataAccessor with out of range type!!!\n" );
return;
}
Assert( instantiator );
if ( m_Accessors[ type ] != NULL )
{
Assert( !"AddDataAccessor, duplicate adds!!!\n" );
return;
}
m_Accessors[ type ] = instantiator;
}
IEntityDataInstantiator *m_Accessors[ MAX_ACCESSORS ];
};
static CDataObjectAccessSystem g_DataObjectAccessSystem;
bool CBaseEntity::HasDataObjectType( int type ) const
{
Assert( type >= 0 && type < NUM_DATAOBJECT_TYPES );
return ( m_fDataObjectTypes & (1<<type) ) ? true : false;
}
void CBaseEntity::AddDataObjectType( int type )
{
Assert( type >= 0 && type < NUM_DATAOBJECT_TYPES );
m_fDataObjectTypes |= (1<<type);
}
void CBaseEntity::RemoveDataObjectType( int type )
{
Assert( type >= 0 && type < NUM_DATAOBJECT_TYPES );
m_fDataObjectTypes &= ~(1<<type);
}
void *CBaseEntity::GetDataObject( int type )
{
Assert( type >= 0 && type < NUM_DATAOBJECT_TYPES );
if ( !HasDataObjectType( type ) )
return NULL;
return g_DataObjectAccessSystem.GetDataObject( type, this );
}
void *CBaseEntity::CreateDataObject( int type )
{
Assert( type >= 0 && type < NUM_DATAOBJECT_TYPES );
AddDataObjectType( type );
return g_DataObjectAccessSystem.CreateDataObject( type, this );
}
void CBaseEntity::DestroyDataObject( int type )
{
Assert( type >= 0 && type < NUM_DATAOBJECT_TYPES );
if ( !HasDataObjectType( type ) )
return;
g_DataObjectAccessSystem.DestroyDataObject( type, this );
RemoveDataObjectType( type );
}
void CPositionWatcherList::Init()
{
m_list = g_PositionWatcherList.CreateList();
}
CPositionWatcherList::~CPositionWatcherList()
{
g_PositionWatcherList.DestroyList( m_list );
}
void CPositionWatcherList::NotifyWatchers( CBaseEntity *pEntity )
{
unsigned short next = g_PositionWatcherList.InvalidIndex();
for ( unsigned short node = g_PositionWatcherList.Head( m_list ); node != g_PositionWatcherList.InvalidIndex(); node = next )
{
next = g_PositionWatcherList.Next( node );
positionwatcher_t *pNode = &g_PositionWatcherList.Element(node);
IPositionWatcher *pWatcherCallback = pNode->hWatcher.Get() ? pNode->pWatcherCallback : NULL;
if ( pWatcherCallback )
{
pWatcherCallback->NotifyPositionChanged( pEntity );
}
else
{
g_PositionWatcherList.Remove( m_list, node );
}
}
}
unsigned short CPositionWatcherList::Find( CBaseEntity *pEntity )
{
unsigned short next = g_PositionWatcherList.InvalidIndex();
for ( unsigned short node = g_PositionWatcherList.Head( m_list ); node != g_PositionWatcherList.InvalidIndex(); node = next )
{
next = g_PositionWatcherList.Next( node );
positionwatcher_t *pNode = &g_PositionWatcherList.Element(node);
if ( pNode->hWatcher.Get() == pEntity )
{
return node;
}
}
return g_PositionWatcherList.InvalidIndex();
}
void CPositionWatcherList::RemoveWatcher( CBaseEntity *pEntity )
{
unsigned short node = Find( pEntity );
if ( node != g_PositionWatcherList.InvalidIndex() )
{
g_PositionWatcherList.Remove( m_list, node );
}
}
void CPositionWatcherList::AddToList( CBaseEntity *pWatcher )
{
unsigned short node = Find( pWatcher );
if ( node == g_PositionWatcherList.InvalidIndex() )
{
positionwatcher_t watcher;
watcher.hWatcher = pWatcher;
// save this separately so we can use the EHANDLE to test for deletion
watcher.pWatcherCallback = dynamic_cast<IPositionWatcher *> (pWatcher);
if ( watcher.pWatcherCallback )
{
g_PositionWatcherList.AddToTail( m_list, watcher );
}
}
}
void ReportPositionChanged( CBaseEntity *pMovedEntity )
{
CPositionWatcherList *pList = (CPositionWatcherList *)pMovedEntity->GetDataObject(POSITIONWATCHER);
if ( pList )
{
pList->NotifyWatchers( pMovedEntity );
}
}
void WatchPositionChanges( CBaseEntity *pWatcher, CBaseEntity *pMovingEntity )
{
CPositionWatcherList *pList = (CPositionWatcherList *)pMovingEntity->GetDataObject(POSITIONWATCHER);
if ( !pList )
{
pList = ( CPositionWatcherList * )pMovingEntity->CreateDataObject( POSITIONWATCHER );
pList->Init();
}
pList->AddToList( pWatcher );
}
void RemovePositionWatcher( CBaseEntity *pWatcher, CBaseEntity *pMovingEntity )
{
CPositionWatcherList *pList = (CPositionWatcherList *)pMovingEntity->GetDataObject(POSITIONWATCHER);
if ( pList )
{
pList->RemoveWatcher( pWatcher );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseEntity::DestroyAllDataObjects( void )
{
int i;
for ( i = 0; i < NUM_DATAOBJECT_TYPES; i++ )
{
if ( HasDataObjectType( i ) )
{
DestroyDataObject( i );
}
}
}
//-----------------------------------------------------------------------------
// For debugging
//-----------------------------------------------------------------------------
#ifdef GAME_DLL
void SpewLinks()
{
int nCount = 0;
for ( CBaseEntity *pClass = gEntList.FirstEnt(); pClass != NULL; pClass = gEntList.NextEnt(pClass) )
{
if ( pClass /*&& !pClass->IsDormant()*/ )
{
touchlink_t *root = ( touchlink_t * )pClass->GetDataObject( TOUCHLINK );
if ( root )
{
// check if the edict is already in the list
for ( touchlink_t *link = root->nextLink; link != root; link = link->nextLink )
{
++nCount;
Msg("[%d] (%d) Link %d (%s) -> %d (%s)\n", nCount, pClass->IsDormant(),
pClass->entindex(), pClass->GetClassname(),
link->entityTouched->entindex(), link->entityTouched->GetClassname() );
}
}
}
}
}
#endif
//-----------------------------------------------------------------------------
// Returns the actual gravity
//-----------------------------------------------------------------------------
static inline float GetActualGravity( CBaseEntity *pEnt )
{
float ent_gravity = pEnt->GetGravity();
if ( ent_gravity == 0.0f )
{
ent_gravity = 1.0f;
}
return ent_gravity * sv_gravity.GetFloat();
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : inline touchlink_t
//-----------------------------------------------------------------------------
inline touchlink_t *AllocTouchLink( void )
{
touchlink_t *link = (touchlink_t*)g_EdictTouchLinks.Alloc( sizeof(touchlink_t) );
if ( link )
{
++linksallocated;
}
else
{
DevMsg( "AllocTouchLink: failed to allocate touchlink_t.\n" );
}
return link;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *link -
// Output : inline void
//-----------------------------------------------------------------------------
inline void FreeTouchLink( touchlink_t *link )
{
if ( link )
{
--linksallocated;
}
g_EdictTouchLinks.Free( link );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : inline groundlink_t
//-----------------------------------------------------------------------------
inline groundlink_t *AllocGroundLink( void )
{
groundlink_t *link = (groundlink_t*)g_EntityGroundLinks.Alloc( sizeof(groundlink_t) );
if ( link )
{
++groundlinksallocated;
}
else
{
DevMsg( "AllocGroundLink: failed to allocate groundlink_t.!!!\n" );
}
return link;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *link -
// Output : inline void
//-----------------------------------------------------------------------------
inline void FreeGroundLink( groundlink_t *link )
{
if ( link )
{
--groundlinksallocated;
}
g_EntityGroundLinks.Free( link );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseEntity::IsCurrentlyTouching( void ) const
{
if ( HasDataObjectType( TOUCHLINK ) )
{
return true;
}
return false;
}
static bool g_bCleanupDatObject = true;
//-----------------------------------------------------------------------------
// Purpose: Checks to see if any entities that have been touching this one
// have stopped touching it, and notify the entity if so.
// Called at the end of a frame, after all the entities have run
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsCheckForEntityUntouch( void )
{
touchlink_t *link, *nextLink;
touchlink_t *root = ( touchlink_t * )GetDataObject( TOUCHLINK );
if ( root )
{
bool saveCleanup = g_bCleanupDatObject;
g_bCleanupDatObject = false;
link = root->nextLink;
while ( link != root )
{
nextLink = link->nextLink;
// these touchlinks are not polled. The ents are touching due to an outside
// system that will add/delete them as necessary (vphysics in this case)
if ( link->touchStamp == TOUCHSTAMP_EVENT_DRIVEN )
{
// refresh the touch call
PhysicsTouch( link->entityTouched );
}
else
{
// check to see if the touch stamp is up to date
if ( link->touchStamp != touchStamp )
{
// stamp is out of data, so entities are no longer touching
// remove self from other entities touch list
PhysicsNotifyOtherOfUntouch( this, link->entityTouched );
// remove other entity from this list
PhysicsRemoveToucher( this, link );
}
}
link = nextLink;
}
g_bCleanupDatObject = saveCleanup;
// Nothing left in list, destroy root
if ( root->nextLink == root &&
root->prevLink == root )
{
DestroyDataObject( TOUCHLINK );
}
}
SetCheckUntouch( false );
}
//-----------------------------------------------------------------------------
// Purpose: notifies an entity than another touching entity has moved out of contact.
// Input : *other - the entity to be acted upon
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsNotifyOtherOfUntouch( CBaseEntity *ent, CBaseEntity *other )
{
if ( !other )
return;
// loop through ed's touch list, looking for the notifier
// remove and call untouch if found
touchlink_t *root = ( touchlink_t * )other->GetDataObject( TOUCHLINK );
if ( root )
{
touchlink_t *link = root->nextLink;
while ( link != root )
{
if ( link->entityTouched == ent )
{
PhysicsRemoveToucher( other, link );
// Check for complete removal
if ( g_bCleanupDatObject &&
root->nextLink == root &&
root->prevLink == root )
{
other->DestroyDataObject( TOUCHLINK );
}
return;
}
link = link->nextLink;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: removes a toucher from the list
// Input : *link - the link to remove
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsRemoveToucher( CBaseEntity *otherEntity, touchlink_t *link )
{
// Every start Touch gets a corresponding end touch
if ( (link->flags & FTOUCHLINK_START_TOUCH) &&
link->entityTouched != NULL &&
otherEntity != NULL )
{
otherEntity->EndTouch( link->entityTouched );
}
link->nextLink->prevLink = link->prevLink;
link->prevLink->nextLink = link->nextLink;
FreeTouchLink( link );
}
//-----------------------------------------------------------------------------
// Purpose: Clears all touches from the list
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsRemoveTouchedList( CBaseEntity *ent )
{
touchlink_t *link, *nextLink;
touchlink_t *root = ( touchlink_t * )ent->GetDataObject( TOUCHLINK );
if ( root )
{
link = root->nextLink;
bool saveCleanup = g_bCleanupDatObject;
g_bCleanupDatObject = false;
while ( link && link != root )
{
nextLink = link->nextLink;
// notify the other entity that this ent has gone away
PhysicsNotifyOtherOfUntouch( ent, link->entityTouched );
// kill it
FreeTouchLink( link );
link = nextLink;
}
g_bCleanupDatObject = saveCleanup;
ent->DestroyDataObject( TOUCHLINK );
}
ent->touchStamp = 0;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *other -
// Output : groundlink_t
//-----------------------------------------------------------------------------
groundlink_t *CBaseEntity::AddEntityToGroundList( CBaseEntity *other )
{
groundlink_t *link;
if ( this == other )
return NULL;
// check if the edict is already in the list
groundlink_t *root = ( groundlink_t * )GetDataObject( GROUNDLINK );
if ( root )
{
for ( link = root->nextLink; link != root; link = link->nextLink )
{
if ( link->entity == other )
{
// no more to do
return link;
}
}
}
else
{
root = ( groundlink_t * )CreateDataObject( GROUNDLINK );
root->prevLink = root->nextLink = root;
}
// entity is not in list, so it's a new touch
// add it to the touched list and then call the touch function
// build new link
link = AllocGroundLink();
if ( !link )
return NULL;
link->entity = other;
// add it to the list
link->nextLink = root->nextLink;
link->prevLink = root;
link->prevLink->nextLink = link;
link->nextLink->prevLink = link;
PhysicsStartGroundContact( other );
return link;
}
//-----------------------------------------------------------------------------
// Purpose: Called whenever two entities come in contact
// Input : *pentOther - the entity who it has touched
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsStartGroundContact( CBaseEntity *pentOther )
{
if ( !pentOther )
return;
if ( !(IsMarkedForDeletion() || pentOther->IsMarkedForDeletion()) )
{
pentOther->StartGroundContact( this );
}
}
//-----------------------------------------------------------------------------
// Purpose: notifies an entity than another touching entity has moved out of contact.
// Input : *other - the entity to be acted upon
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsNotifyOtherOfGroundRemoval( CBaseEntity *ent, CBaseEntity *other )
{
if ( !other )
return;
// loop through ed's touch list, looking for the notifier
// remove and call untouch if found
groundlink_t *root = ( groundlink_t * )other->GetDataObject( GROUNDLINK );
if ( root )
{
groundlink_t *link = root->nextLink;
while ( link != root )
{
if ( link->entity == ent )
{
PhysicsRemoveGround( other, link );
if ( root->nextLink == root &&
root->prevLink == root )
{
other->DestroyDataObject( GROUNDLINK );
}
return;
}
link = link->nextLink;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: removes a toucher from the list
// Input : *link - the link to remove
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsRemoveGround( CBaseEntity *other, groundlink_t *link )
{
// Every start Touch gets a corresponding end touch
if ( link->entity != NULL )
{
CBaseEntity *linkEntity = link->entity;
CBaseEntity *otherEntity = other;
if ( linkEntity && otherEntity )
{
linkEntity->EndGroundContact( otherEntity );
}
}
link->nextLink->prevLink = link->prevLink;
link->prevLink->nextLink = link->nextLink;
FreeGroundLink( link );
}
//-----------------------------------------------------------------------------
// Purpose: static method to remove ground list for an entity
// Input : *ent -
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsRemoveGroundList( CBaseEntity *ent )
{
groundlink_t *link, *nextLink;
groundlink_t *root = ( groundlink_t * )ent->GetDataObject( GROUNDLINK );
if ( root )
{
link = root->nextLink;
while ( link && link != root )
{
nextLink = link->nextLink;
// notify the other entity that this ent has gone away
PhysicsNotifyOtherOfGroundRemoval( ent, link->entity );
// kill it
FreeGroundLink( link );
link = nextLink;
}
ent->DestroyDataObject( GROUNDLINK );
}
}
//-----------------------------------------------------------------------------
// Purpose: Called every frame that two entities are touching
// Input : *pentOther - the entity who it has touched
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsTouch( CBaseEntity *pentOther )
{
if ( pentOther )
{
if ( !(IsMarkedForDeletion() || pentOther->IsMarkedForDeletion()) )
{
Touch( pentOther );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Called whenever two entities come in contact
// Input : *pentOther - the entity who it has touched
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsStartTouch( CBaseEntity *pentOther )
{
if ( pentOther )
{
if ( !(IsMarkedForDeletion() || pentOther->IsMarkedForDeletion()) )
{
StartTouch( pentOther );
Touch( pentOther );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Marks in an entity that it is touching another entity, and calls
// it's Touch() function if it is a new touch.
// Stamps the touch link with the new time so that when we check for
// untouch we know things haven't changed.
// Input : *other - entity that it is in contact with
//-----------------------------------------------------------------------------
touchlink_t *CBaseEntity::PhysicsMarkEntityAsTouched( CBaseEntity *other )
{
touchlink_t *link;
if ( this == other )
return NULL;
// Entities in hierarchy should not interact
if ( (this->GetMoveParent() == other) || (this == other->GetMoveParent()) )
return NULL;
// check if either entity doesn't generate touch functions
if ( (GetFlags() | other->GetFlags()) & FL_DONTTOUCH )
return NULL;
// Pure triggers should not touch each other
if ( IsSolidFlagSet( FSOLID_TRIGGER ) && other->IsSolidFlagSet( FSOLID_TRIGGER ) )
{
if (!IsSolid() && !other->IsSolid())
return NULL;
}
// Don't do touching if marked for deletion
if ( other->IsMarkedForDeletion() )
{
return NULL;
}
if ( IsMarkedForDeletion() )
{
return NULL;
}
// check if the edict is already in the list
touchlink_t *root = ( touchlink_t * )GetDataObject( TOUCHLINK );
if ( root )
{
for ( link = root->nextLink; link != root; link = link->nextLink )
{
if ( link->entityTouched == other )
{
// update stamp
link->touchStamp = touchStamp;
PhysicsTouch( other );
// no more to do
return link;
}
}
}
else
{
// Allocate the root object
root = ( touchlink_t * )CreateDataObject( TOUCHLINK );
root->nextLink = root->prevLink = root;
}
// entity is not in list, so it's a new touch
// add it to the touched list and then call the touch function
// build new link
link = AllocTouchLink();
if ( !link )
return NULL;
link->touchStamp = touchStamp;
link->entityTouched = other;
link->flags = 0;
// add it to the list
link->nextLink = root->nextLink;
link->prevLink = root;
link->prevLink->nextLink = link;
link->nextLink->prevLink = link;
// non-solid entities don't get touched
bool bShouldTouch = (IsSolid() && !IsSolidFlagSet(FSOLID_VOLUME_CONTENTS)) || IsSolidFlagSet(FSOLID_TRIGGER);
if ( bShouldTouch && !other->IsSolidFlagSet(FSOLID_TRIGGER) )
{
link->flags |= FTOUCHLINK_START_TOUCH;
PhysicsStartTouch( other );
}
return link;
}
static trace_t g_TouchTrace;
const trace_t &CBaseEntity::GetTouchTrace( void )
{
return g_TouchTrace;
}
//-----------------------------------------------------------------------------
// Purpose: Marks the fact that two edicts are in contact
// Input : *other - other entity
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsMarkEntitiesAsTouching( CBaseEntity *other, trace_t &trace )
{
g_TouchTrace = trace;
PhysicsMarkEntityAsTouched( other );
other->PhysicsMarkEntityAsTouched( this );
}
void CBaseEntity::PhysicsMarkEntitiesAsTouchingEventDriven( CBaseEntity *other, trace_t &trace )
{
g_TouchTrace = trace;
touchlink_t *link;
link = this->PhysicsMarkEntityAsTouched( other );
if ( link )
{
// mark these links as event driven so they aren't untouched the next frame
// when the physics doesn't refresh them
link->touchStamp = TOUCHSTAMP_EVENT_DRIVEN;
}
link = other->PhysicsMarkEntityAsTouched( this );
if ( link )
{
link->touchStamp = TOUCHSTAMP_EVENT_DRIVEN;
}
}
//-----------------------------------------------------------------------------
// Purpose: Two entities have touched, so run their touch functions
// Input : *other -
// *ptrace -
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsImpact( CBaseEntity *other, trace_t &trace )
{
if ( !other )
{
return;
}
// If either of the entities is flagged to be deleted,
// don't call the touch functions
if ( ( GetFlags() | other->GetFlags() ) & FL_KILLME )
{
return;
}
PhysicsMarkEntitiesAsTouching( other, trace );
}
//-----------------------------------------------------------------------------
// Purpose: Returns the mask of what is solid for the given entity
// Output : unsigned int
//-----------------------------------------------------------------------------
unsigned int CBaseEntity::PhysicsSolidMaskForEntity( void ) const
{
return MASK_SOLID;
}
//-----------------------------------------------------------------------------
// Computes the water level + type
//-----------------------------------------------------------------------------
void CBaseEntity::UpdateWaterState()
{
// FIXME: This computation is nonsensical for rigid child attachments
// Should we just grab the type + level of the parent?
// Probably for rigid children anyways...
// Compute the point to check for water state
Vector point;
CollisionProp()->NormalizedToWorldSpace( Vector( 0.5f, 0.5f, 0.0f ), &point );
SetWaterLevel( 0 );
SetWaterType( CONTENTS_EMPTY );
int cont = UTIL_PointContents (point);
if (( cont & MASK_WATER ) == 0)
return;
SetWaterType( cont );
SetWaterLevel( 1 );
// point sized entities are always fully submerged
if ( IsPointSized() )
{
SetWaterLevel( 3 );
}
else
{
// Check the exact center of the box
point[2] = WorldSpaceCenter().z;
int midcont = UTIL_PointContents (point);
if ( midcont & MASK_WATER )
{
// Now check where the eyes are...
SetWaterLevel( 2 );
point[2] = EyePosition().z;
int eyecont = UTIL_PointContents (point);
if ( eyecont & MASK_WATER )
{
SetWaterLevel( 3 );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Check if entity is in the water and applies any current to velocity
// and sets appropriate water flags
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseEntity::PhysicsCheckWater( void )
{
if (GetMoveParent())
return GetWaterLevel() > 1;
int cont = GetWaterType();
// If we're not in water + don't have a current, we're done
if ( ( cont & (MASK_WATER | MASK_CURRENT) ) != (MASK_WATER | MASK_CURRENT) )
return GetWaterLevel() > 1;
// Compute current direction
Vector v( 0, 0, 0 );
if ( cont & CONTENTS_CURRENT_0 )
{
v[0] += 1;
}
if ( cont & CONTENTS_CURRENT_90 )
{
v[1] += 1;
}
if ( cont & CONTENTS_CURRENT_180 )
{
v[0] -= 1;
}
if ( cont & CONTENTS_CURRENT_270 )
{
v[1] -= 1;
}
if ( cont & CONTENTS_CURRENT_UP )
{
v[2] += 1;
}
if ( cont & CONTENTS_CURRENT_DOWN )
{
v[2] -= 1;
}
// The deeper we are, the stronger the current.
Vector newBaseVelocity;
VectorMA (GetBaseVelocity(), 50.0*GetWaterLevel(), v, newBaseVelocity);
SetBaseVelocity( newBaseVelocity );
return GetWaterLevel() > 1;
}
//-----------------------------------------------------------------------------
// Purpose: Bounds velocity
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsCheckVelocity( void )
{
Vector origin = GetAbsOrigin();
Vector vecAbsVelocity = GetAbsVelocity();
bool bReset = false;
for ( int i=0 ; i<3 ; i++ )
{
if ( IS_NAN(vecAbsVelocity[i]) )
{
Msg( "Got a NaN velocity on %s\n", GetClassname() );
vecAbsVelocity[i] = 0;
bReset = true;
}
if ( IS_NAN(origin[i]) )
{
Msg( "Got a NaN origin on %s\n", GetClassname() );
origin[i] = 0;
bReset = true;
}
if ( vecAbsVelocity[i] > sv_maxvelocity.GetFloat() )
{
#ifdef _DEBUG
DevWarning( 2, "Got a velocity too high on %s\n", GetClassname() );
#endif
vecAbsVelocity[i] = sv_maxvelocity.GetFloat();
bReset = true;
}
else if ( vecAbsVelocity[i] < -sv_maxvelocity.GetFloat() )
{
#ifdef _DEBUG
DevWarning( 2, "Got a velocity too low on %s\n", GetClassname() );
#endif
vecAbsVelocity[i] = -sv_maxvelocity.GetFloat();
bReset = true;
}
}
if (bReset)
{
SetAbsOrigin( origin );
SetAbsVelocity( vecAbsVelocity );
}
}
//-----------------------------------------------------------------------------
// Purpose: Applies gravity to falling objects
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsAddGravityMove( Vector &move )
{
Vector vecAbsVelocity = GetAbsVelocity();
move.x = (vecAbsVelocity.x + GetBaseVelocity().x ) * gpGlobals->frametime;
move.y = (vecAbsVelocity.y + GetBaseVelocity().y ) * gpGlobals->frametime;
if ( GetFlags() & FL_ONGROUND )
{
move.z = GetBaseVelocity().z * gpGlobals->frametime;
return;
}
// linear acceleration due to gravity
float newZVelocity = vecAbsVelocity.z - GetActualGravity( this ) * gpGlobals->frametime;
move.z = ((vecAbsVelocity.z + newZVelocity) / 2.0 + GetBaseVelocity().z ) * gpGlobals->frametime;
Vector vecBaseVelocity = GetBaseVelocity();
vecBaseVelocity.z = 0.0f;
SetBaseVelocity( vecBaseVelocity );
vecAbsVelocity.z = newZVelocity;
SetAbsVelocity( vecAbsVelocity );
// Bound velocity
PhysicsCheckVelocity();
}
#define STOP_EPSILON 0.1
//-----------------------------------------------------------------------------
// Purpose: Slide off of the impacting object. Returns the blocked flags (1 = floor, 2 = step / wall)
// Input : in -
// normal -
// out -
// overbounce -
// Output : int
//-----------------------------------------------------------------------------
int CBaseEntity::PhysicsClipVelocity( const Vector& in, const Vector& normal, Vector& out, float overbounce )
{
float backoff;
float change;
float angle;
int i, blocked;
blocked = 0;
angle = normal[ 2 ];
if ( angle > 0 )
{
blocked |= 1; // floor
}
if ( !angle )
{
blocked |= 2; // step
}
backoff = DotProduct (in, normal) * overbounce;
for ( i=0 ; i<3 ; i++ )
{
change = normal[i]*backoff;
out[i] = in[i] - change;
if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON)
{
out[i] = 0;
}
}
return blocked;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseEntity::ResolveFlyCollisionBounce( trace_t &trace, Vector &vecVelocity, float flMinTotalElasticity )
{
#ifdef HL1_DLL
flMinTotalElasticity = 0.3f;
#endif//HL1_DLL
// Get the impact surface's elasticity.
float flSurfaceElasticity;
physprops->GetPhysicsProperties( trace.surface.surfaceProps, NULL, NULL, NULL, &flSurfaceElasticity );
float flTotalElasticity = GetElasticity() * flSurfaceElasticity;
if ( flMinTotalElasticity > 0.9f )
{
flMinTotalElasticity = 0.9f;
}
flTotalElasticity = clamp( flTotalElasticity, flMinTotalElasticity, 0.9f );
// NOTE: A backoff of 2.0f is a reflection
Vector vecAbsVelocity;
PhysicsClipVelocity( GetAbsVelocity(), trace.plane.normal, vecAbsVelocity, 2.0f );
vecAbsVelocity *= flTotalElasticity;
// Get the total velocity (player + conveyors, etc.)
VectorAdd( vecAbsVelocity, GetBaseVelocity(), vecVelocity );
float flSpeedSqr = DotProduct( vecVelocity, vecVelocity );
// Stop if on ground.
if ( trace.plane.normal.z > 0.7f ) // Floor
{
// Verify that we have an entity.
CBaseEntity *pEntity = trace.m_pEnt;
Assert( pEntity );
// Are we on the ground?
if ( vecVelocity.z < ( GetActualGravity( this ) * gpGlobals->frametime ) )
{
vecAbsVelocity.z = 0.0f;
// Recompute speedsqr based on the new absvel
VectorAdd( vecAbsVelocity, GetBaseVelocity(), vecVelocity );
flSpeedSqr = DotProduct( vecVelocity, vecVelocity );
}
SetAbsVelocity( vecAbsVelocity );
if ( flSpeedSqr < ( 30 * 30 ) )
{
if ( pEntity->IsStandable() )
{
SetGroundEntity( pEntity );
}
// Reset velocities.
SetAbsVelocity( vec3_origin );
SetLocalAngularVelocity( vec3_angle );
}
else
{
Vector vecDelta = GetBaseVelocity() - vecAbsVelocity;
Vector vecBaseDir = GetBaseVelocity();
VectorNormalize( vecBaseDir );
float flScale = vecDelta.Dot( vecBaseDir );
VectorScale( vecAbsVelocity, ( 1.0f - trace.fraction ) * gpGlobals->frametime, vecVelocity );
VectorMA( vecVelocity, ( 1.0f - trace.fraction ) * gpGlobals->frametime, GetBaseVelocity() * flScale, vecVelocity );
PhysicsPushEntity( vecVelocity, &trace );
}
}
else
{
// If we get *too* slow, we'll stick without ever coming to rest because
// we'll get pushed down by gravity faster than we can escape from the wall.
if ( flSpeedSqr < ( 30 * 30 ) )
{
// Reset velocities.
SetAbsVelocity( vec3_origin );
SetLocalAngularVelocity( vec3_angle );
}
else
{
SetAbsVelocity( vecAbsVelocity );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseEntity::ResolveFlyCollisionSlide( trace_t &trace, Vector &vecVelocity )
{
// Get the impact surface's friction.
float flSurfaceFriction;
physprops->GetPhysicsProperties( trace.surface.surfaceProps, NULL, NULL, &flSurfaceFriction, NULL );
// A backoff of 1.0 is a slide.
float flBackOff = 1.0f;
Vector vecAbsVelocity;
PhysicsClipVelocity( GetAbsVelocity(), trace.plane.normal, vecAbsVelocity, flBackOff );
if ( trace.plane.normal.z <= 0.7 ) // Floor
{
SetAbsVelocity( vecAbsVelocity );
return;
}
// Stop if on ground.
// Get the total velocity (player + conveyors, etc.)
VectorAdd( vecAbsVelocity, GetBaseVelocity(), vecVelocity );
float flSpeedSqr = DotProduct( vecVelocity, vecVelocity );
// Verify that we have an entity.
CBaseEntity *pEntity = trace.m_pEnt;
Assert( pEntity );
// Are we on the ground?
if ( vecVelocity.z < ( GetActualGravity( this ) * gpGlobals->frametime ) )
{
vecAbsVelocity.z = 0.0f;
// Recompute speedsqr based on the new absvel
VectorAdd( vecAbsVelocity, GetBaseVelocity(), vecVelocity );
flSpeedSqr = DotProduct( vecVelocity, vecVelocity );
}
SetAbsVelocity( vecAbsVelocity );
if ( flSpeedSqr < ( 30 * 30 ) )
{
if ( pEntity->IsStandable() )
{
SetGroundEntity( pEntity );
}
// Reset velocities.
SetAbsVelocity( vec3_origin );
SetLocalAngularVelocity( vec3_angle );
}
else
{
vecAbsVelocity += GetBaseVelocity();
vecAbsVelocity *= ( 1.0f - trace.fraction ) * gpGlobals->frametime * flSurfaceFriction;
PhysicsPushEntity( vecAbsVelocity, &trace );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseEntity::ResolveFlyCollisionCustom( trace_t &trace, Vector &vecVelocity )
{
// Stop if on ground.
if ( trace.plane.normal.z > 0.7 ) // Floor
{
// Get the total velocity (player + conveyors, etc.)
VectorAdd( GetAbsVelocity(), GetBaseVelocity(), vecVelocity );
// Verify that we have an entity.
CBaseEntity *pEntity = trace.m_pEnt;
Assert( pEntity );
// Are we on the ground?
if ( vecVelocity.z < ( GetActualGravity( this ) * gpGlobals->frametime ) )
{
Vector vecAbsVelocity = GetAbsVelocity();
vecAbsVelocity.z = 0.0f;
SetAbsVelocity( vecAbsVelocity );
}
if ( pEntity->IsStandable() )
{
SetGroundEntity( pEntity );
}
}
}
//-----------------------------------------------------------------------------
// Performs the collision resolution for fliers.
//-----------------------------------------------------------------------------
void CBaseEntity::PerformFlyCollisionResolution( trace_t &trace, Vector &move )
{
switch( GetMoveCollide() )
{
case MOVECOLLIDE_FLY_CUSTOM:
{
ResolveFlyCollisionCustom( trace, move );
break;
}
case MOVECOLLIDE_FLY_BOUNCE:
{
ResolveFlyCollisionBounce( trace, move );
break;
}
case MOVECOLLIDE_FLY_SLIDE:
case MOVECOLLIDE_DEFAULT:
// NOTE: The default fly collision state is the same as a slide (for backward capatability).
{
ResolveFlyCollisionSlide( trace, move );
break;
}
default:
{
// Invalid MOVECOLLIDE_<type>
Assert( 0 );
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Checks if an object has passed into or out of water and sets water info, alters velocity, plays splash sounds, etc.
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsCheckWaterTransition( void )
{
int oldcont = GetWaterType();
UpdateWaterState();
int cont = GetWaterType();
// We can exit right out if we're a child... don't bother with this...
if (GetMoveParent())
return;
if ( cont & MASK_WATER )
{
if (oldcont == CONTENTS_EMPTY)
{
// just crossed into water
EmitSound( "BaseEntity.EnterWater" );
Vector vecAbsVelocity = GetAbsVelocity();
vecAbsVelocity[2] *= 0.5;
SetAbsVelocity( vecAbsVelocity );
}
}
else
{
if ( oldcont != CONTENTS_EMPTY )
{
// just crossed out of water
EmitSound( "BaseEntity.ExitWater" );
}
}
}
//-----------------------------------------------------------------------------
// Computes new angles based on the angular velocity
//-----------------------------------------------------------------------------
void CBaseEntity::SimulateAngles( float flFrameTime )
{
// move angles
QAngle angles;
VectorMA ( GetLocalAngles(), flFrameTime, GetLocalAngularVelocity(), angles );
SetLocalAngles( angles );
}
//-----------------------------------------------------------------------------
// Purpose: Toss, bounce, and fly movement. When onground, do nothing.
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsToss( void )
{
trace_t trace;
Vector move;
PhysicsCheckWater();
// regular thinking
if ( !PhysicsRunThink() )
return;
// Moving upward, off the ground, or resting on a client/monster, remove FL_ONGROUND
if ( GetAbsVelocity()[2] > 0 || !GetGroundEntity() || !GetGroundEntity()->IsStandable() )
{
SetGroundEntity( NULL );
}
// Check to see if entity is on the ground at rest
if ( GetFlags() & FL_ONGROUND )
{
if ( VectorCompare( GetAbsVelocity(), vec3_origin ) )
{
// Clear rotation if not moving (even if on a conveyor)
SetLocalAngularVelocity( vec3_angle );
if ( VectorCompare( GetBaseVelocity(), vec3_origin ) )
return;
}
}
PhysicsCheckVelocity();
// add gravity
if ( GetMoveType() == MOVETYPE_FLYGRAVITY && !(GetFlags() & FL_FLY) )
{
PhysicsAddGravityMove( move );
}
else
{
// Base velocity is not properly accounted for since this entity will move again after the bounce without
// taking it into account
Vector vecAbsVelocity = GetAbsVelocity();
vecAbsVelocity += GetBaseVelocity();
VectorScale(vecAbsVelocity, gpGlobals->frametime, move);
PhysicsCheckVelocity( );
}
// move angles
SimulateAngles( gpGlobals->frametime );
// move origin
PhysicsPushEntity( move, &trace );
#if !defined( CLIENT_DLL )
if ( VPhysicsGetObject() )
{
VPhysicsGetObject()->UpdateShadow( GetAbsOrigin(), vec3_angle, true, gpGlobals->frametime );
}
#endif
PhysicsCheckVelocity();
if (trace.allsolid )
{
// entity is trapped in another solid
// UNDONE: does this entity needs to be removed?
SetAbsVelocity(vec3_origin);
SetLocalAngularVelocity(vec3_angle);
return;
}
#if !defined( CLIENT_DLL )
if (IsEdictFree())
return;
#endif
if (trace.fraction != 1.0f)
{
PerformFlyCollisionResolution( trace, move );
}
// check for in water
PhysicsCheckWaterTransition();
}
//-----------------------------------------------------------------------------
// Simulation in local space of rigid children
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsRigidChild( void )
{
VPROF("CBaseEntity::PhysicsRigidChild");
// NOTE: rigidly attached children do simulation in local space
// Collision impulses will be handled either not at all, or by
// forwarding the information to the highest move parent
Vector vecPrevOrigin = GetAbsOrigin();
// regular thinking
if ( !PhysicsRunThink() )
return;
VPROF_SCOPE_BEGIN("CBaseEntity::PhysicsRigidChild-2");
#if !defined( CLIENT_DLL )
// Cause touch functions to be called
PhysicsTouchTriggers( &vecPrevOrigin );
// We have to do this regardless owing to hierarchy
if ( VPhysicsGetObject() )
{
VPhysicsGetObject()->UpdateShadow( GetAbsOrigin(), vec3_angle, true, gpGlobals->frametime );
}
#endif
VPROF_SCOPE_END();
}
//-----------------------------------------------------------------------------
// Computes the base velocity
//-----------------------------------------------------------------------------
void CBaseEntity::UpdateBaseVelocity( void )
{
#if !defined( CLIENT_DLL )
if ( GetFlags() & FL_ONGROUND )
{
CBaseEntity *groundentity = GetGroundEntity();
if ( groundentity )
{
// On conveyor belt that's moving?
if ( groundentity->GetFlags() & FL_CONVEYOR )
{
Vector vecNewBaseVelocity;
groundentity->GetGroundVelocityToApply( vecNewBaseVelocity );
if ( GetFlags() & FL_BASEVELOCITY )
{
vecNewBaseVelocity += GetBaseVelocity();
}
AddFlag( FL_BASEVELOCITY );
SetBaseVelocity( vecNewBaseVelocity );
}
}
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: Runs a frame of physics for a specific edict (and all it's children)
// Input : *ent - the thinking edict
//-----------------------------------------------------------------------------
void CBaseEntity::PhysicsSimulate( void )
{
VPROF( "CBaseEntity::PhysicsSimulate" );
// NOTE: Players override PhysicsSimulate and drive through their CUserCmds at that point instead of
// processng through this function call!!! They shouldn't chain to here ever.
// Make sure not to simulate this guy twice per frame
if (m_nSimulationTick == gpGlobals->tickcount)
return;
m_nSimulationTick = gpGlobals->tickcount;
Assert( !IsPlayer() );
// If we've got a moveparent, we must simulate that first.
CBaseEntity *pMoveParent = GetMoveParent();
if ( (GetMoveType() == MOVETYPE_NONE && !pMoveParent) || (GetMoveType() == MOVETYPE_VPHYSICS ) )
{
PhysicsNone();
return;
}
// If ground entity goes away, make sure FL_ONGROUND is valid
if ( !GetGroundEntity() )
{
RemoveFlag( FL_ONGROUND );
}
if (pMoveParent)
{
VPROF( "CBaseEntity::PhysicsSimulate-MoveParent" );
pMoveParent->PhysicsSimulate();
}
else
{
VPROF( "CBaseEntity::PhysicsSimulate-BaseVelocity" );
UpdateBaseVelocity();
if ( ((GetFlags() & FL_BASEVELOCITY) == 0) && (GetBaseVelocity() != vec3_origin) )
{
// Apply momentum (add in half of the previous frame of velocity first)
// BUGBUG: This will break with PhysicsStep() because of the timestep difference
Vector vecAbsVelocity;
VectorMA( GetAbsVelocity(), 1.0 + (gpGlobals->frametime*0.5), GetBaseVelocity(), vecAbsVelocity );
SetAbsVelocity( vecAbsVelocity );
SetBaseVelocity( vec3_origin );
}
RemoveFlag( FL_BASEVELOCITY );
}
switch( GetMoveType() )
{
case MOVETYPE_PUSH:
{
VPROF( "CBaseEntity::PhysicsSimulate-MOVETYPE_PUSH" );
PhysicsPusher();
}
break;
case MOVETYPE_VPHYSICS:
{
}
break;
case MOVETYPE_NONE:
{
VPROF( "CBaseEntity::PhysicsSimulate-MOVETYPE_NONE" );
Assert(pMoveParent);
PhysicsRigidChild();
}
break;
case MOVETYPE_NOCLIP:
{
VPROF( "CBaseEntity::PhysicsSimulate-MOVETYPE_NOCLIP" );
PhysicsNoclip();
}
break;
case MOVETYPE_STEP:
{
VPROF( "CBaseEntity::PhysicsSimulate-MOVETYPE_STEP" );
PhysicsStep();
}
break;
case MOVETYPE_FLY:
case MOVETYPE_FLYGRAVITY:
{
VPROF( "CBaseEntity::PhysicsSimulate-MOVETYPE_FLY" );
PhysicsToss();
}
break;
case MOVETYPE_CUSTOM:
{
VPROF( "CBaseEntity::PhysicsSimulate-MOVETYPE_CUSTOM" );
PhysicsCustom();
}
break;
default:
Warning( "PhysicsSimulate: %s bad movetype %d", GetClassname(), GetMoveType() );
Assert(0);
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: Runs thinking code if time. There is some play in the exact time the think
// function will be called, because it is called before any movement is done
// in a frame. Not used for pushmove objects, because they must be exact.
// Returns false if the entity removed itself.
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CBaseEntity::PhysicsRunThink( thinkmethods_t thinkMethod )
{
if ( IsEFlagSet( EFL_NO_THINK_FUNCTION ) )
return true;
bool bAlive = true;
// Don't fire the base if we're avoiding it
if ( thinkMethod != THINK_FIRE_ALL_BUT_BASE )
{
bAlive = PhysicsRunSpecificThink( -1, &CBaseEntity::Think );
if ( !bAlive )
return false;
}
// Are we just firing the base think?
if ( thinkMethod == THINK_FIRE_BASE_ONLY )
return bAlive;
// Fire the rest of 'em
for ( int i = 0; i < m_aThinkFunctions.Count(); i++ )
{
#ifdef _DEBUG
// Set the context
m_iCurrentThinkContext = i;
#endif
bAlive = PhysicsRunSpecificThink( i, m_aThinkFunctions[i].m_pfnThink );
#ifdef _DEBUG
// Clear our context
m_iCurrentThinkContext = NO_THINK_CONTEXT;
#endif
if ( !bAlive )
return false;
}
return bAlive;
}
//-----------------------------------------------------------------------------
// Purpose: For testing if all thinks are occuring at the same time
//-----------------------------------------------------------------------------
struct ThinkSync
{
float thinktime;
int thinktick;
CUtlVector< EHANDLE > entities;
ThinkSync()
{
thinktime = 0;
}
ThinkSync( const ThinkSync& src )
{
thinktime = src.thinktime;
thinktick = src.thinktick;
int c = src.entities.Count();
for ( int i = 0; i < c; i++ )
{
entities.AddToTail( src.entities[ i ] );
}
}
};
#if !defined( CLIENT_DLL )
static ConVar sv_thinktimecheck( "sv_thinktimecheck", "0", 0, "Check for thinktimes all on same timestamp." );
#endif
//-----------------------------------------------------------------------------
// Purpose: For testing if all thinks are occuring at the same time
//-----------------------------------------------------------------------------
class CThinkSyncTester
{
public:
CThinkSyncTester() :
m_Thinkers( 0, 0, ThinkLessFunc )
{
m_nLastFrameCount = -1;
m_bShouldCheck = false;
}
void EntityThinking( int framecount, CBaseEntity *ent, float thinktime, int thinktick )
{
#if !defined( CLIENT_DLL )
if ( m_nLastFrameCount != framecount )
{
if ( m_bShouldCheck )
{
// Report
Report();
m_Thinkers.RemoveAll();
m_nLastFrameCount = framecount;
}
m_bShouldCheck = sv_thinktimecheck.GetBool();
}
if ( !m_bShouldCheck )
return;
ThinkSync *p = FindOrAddItem( ent, thinktime );
if ( !p )
{
Assert( 0 );
}
p->thinktime = thinktime;
p->thinktick = thinktick;
EHANDLE h;
h = ent;
p->entities.AddToTail( h );
#endif
}
private:
static bool ThinkLessFunc( const ThinkSync& item1, const ThinkSync& item2 )
{
return item1.thinktime < item2.thinktime;
}
ThinkSync *FindOrAddItem( CBaseEntity *ent, float thinktime )
{
ThinkSync item;
item.thinktime = thinktime;
int idx = m_Thinkers.Find( item );
if ( idx == m_Thinkers.InvalidIndex() )
{
idx = m_Thinkers.Insert( item );
}
return &m_Thinkers[ idx ];
}
void Report()
{
if ( m_Thinkers.Count() == 0 )
return;
Msg( "-----------------\nThink report frame %i\n", gpGlobals->tickcount );
for ( int i = m_Thinkers.FirstInorder();
i != m_Thinkers.InvalidIndex();
i = m_Thinkers.NextInorder( i ) )
{
ThinkSync *p = &m_Thinkers[ i ];
Assert( p );
if ( !p )
continue;
int ecount = p->entities.Count();
if ( !ecount )
{
continue;
}
Msg( "thinktime %f, %i entities\n", p->thinktime, ecount );
for ( int j =0; j < ecount; j++ )
{
EHANDLE h = p->entities[ j ];
int lastthinktick = 0;
int nextthinktick = 0;
CBaseEntity *e = h.Get();
if ( e )
{
lastthinktick = e->m_nLastThinkTick;
nextthinktick = e->m_nNextThinkTick;
}
Msg( " %p : %30s (last %5i/next %5i)\n", h.Get(), h.Get() ? h->GetClassname() : "NULL",
lastthinktick, nextthinktick );
}
}
}
CUtlRBTree< ThinkSync > m_Thinkers;
int m_nLastFrameCount;
bool m_bShouldCheck;
};
static CThinkSyncTester g_ThinkChecker;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CBaseEntity::PhysicsRunSpecificThink( int nContextIndex, BASEPTR thinkFunc )
{
int thinktick = GetNextThinkTick( nContextIndex );
if ( thinktick <= 0 || thinktick > gpGlobals->tickcount )
return true;
float thinktime = thinktick * TICK_INTERVAL;
// Don't let things stay in the past.
// it is possible to start that way
// by a trigger with a local time.
if ( thinktime < gpGlobals->curtime )
{
thinktime = gpGlobals->curtime;
}
// Only do this on the game server
#if !defined( CLIENT_DLL )
g_ThinkChecker.EntityThinking( gpGlobals->tickcount, this, thinktime, m_nNextThinkTick );
#endif
SetNextThink( nContextIndex, TICK_NEVER_THINK );
PhysicsDispatchThink( thinkFunc );
SetLastThink( nContextIndex, gpGlobals->curtime );
// Return whether entity is still valid
return ( !IsMarkedForDeletion() );
}
void CBaseEntity::SetGroundEntity( CBaseEntity *ground )
{
if ( m_hGroundEntity.Get() == ground )
return;
CBaseEntity *oldGround = m_hGroundEntity;
m_hGroundEntity = ground;
// Just starting to touch
if ( !oldGround && ground )
{
ground->AddEntityToGroundList( this );
}
// Just stopping touching
else if ( oldGround && !ground )
{
PhysicsNotifyOtherOfGroundRemoval( this, oldGround );
}
// Changing out to new ground entity
else
{
PhysicsNotifyOtherOfGroundRemoval( this, oldGround );
ground->AddEntityToGroundList( this );
}
// HACK/PARANOID: This is redundant with the code above, but in case we get out of sync groundlist entries ever,
// this will force the appropriate flags
if ( ground )
{
AddFlag( FL_ONGROUND );
}
else
{
RemoveFlag( FL_ONGROUND );
}
}
CBaseEntity *CBaseEntity::GetGroundEntity( void )
{
return m_hGroundEntity;
}
void CBaseEntity::StartGroundContact( CBaseEntity *ground )
{
AddFlag( FL_ONGROUND );
// Msg( "+++ %s starting contact with ground %s\n", GetClassname(), ground->GetClassname() );
}
void CBaseEntity::EndGroundContact( CBaseEntity *ground )
{
RemoveFlag( FL_ONGROUND );
// Msg( "--- %s ending contact with ground %s\n", GetClassname(), ground->GetClassname() );
}
void CBaseEntity::SetGroundChangeTime( float flTime )
{
m_flGroundChangeTime = flTime;
}
float CBaseEntity::GetGroundChangeTime( void )
{
return m_flGroundChangeTime;
}
// Remove this as ground entity for all object resting on this object
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseEntity::WakeRestingObjects()
{
// Unset this as ground entity for everything resting on this object
// This calls endgroundcontact for everything on the list
PhysicsRemoveGroundList( this );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *ent -
//-----------------------------------------------------------------------------
bool CBaseEntity::HasNPCsOnIt( void )
{
groundlink_t *link;
groundlink_t *root = ( groundlink_t * )GetDataObject( GROUNDLINK );
if ( root )
{
for ( link = root->nextLink; link != root; link = link->nextLink )
{
if ( link->entity && link->entity->MyNPCPointer() )
return true;
}
}
return false;
}
| [
"jeremy.lorelli.1337@gmail.com"
] | jeremy.lorelli.1337@gmail.com |
3bb585d038c01f1369b2c01f7141af8e0e5fbe8b | 36a4207b6f7aa99b9f2018b9b21ca220be66c026 | /cpp/236A.cpp | 648bd136648dd003ff2fc6e53fbb41815bd292a7 | [] | no_license | eneagoe/codeforces | 3753193db6db7b08c2ae731d83f2f8baa901c949 | 5ebdb681b9729bdf259a8d655fb46c8d0910c695 | refs/heads/master | 2023-08-16T23:48:27.499478 | 2023-07-26T14:33:42 | 2023-07-26T14:33:42 | 51,220,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string in;
cin >> in;
sort(in.begin(), in.end());
in.erase(unique(in.begin(), in.end()), in.end());
if (in.length() % 2)
cout << "IGNORE HIM!" << endl;
else
cout << "CHAT WITH HER!" << endl;
}
| [
"eneagoe@gmail.com"
] | eneagoe@gmail.com |
9e7ff435fea4883ae119878ed0de0ca58a0510b8 | f1ec6c536f53de395ddedc6c1cc86aadffe1387f | /QTimer/widget.cpp | e63b05b8b0808ac074cfc33b382997d16225c5ac | [] | no_license | ZhangFuchang/Qt5 | a07cc15d5ea75d24ab282115df0d331c217ff10a | d78613c570496653ca8a7ed7063e22a67b927826 | refs/heads/master | 2022-04-12T11:14:53.341148 | 2020-03-30T03:39:56 | 2020-03-30T03:39:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | cpp | #include "widget.h"
#include "ui_widget.h"
#include<QTimer>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
timer=new QTimer(this);
connect(timer,&QTimer::timeout,
[=](){
static int num=0;
ui->lcdNumber->display(++num);
});
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
//定时器一到时间就会抛出信号timeout
if(timer->isActive()==false){
timer->start(100);
}
}
void Widget::on_pushButton_2_clicked()
{
if(timer->isActive()==true){
timer->stop();
}
}
| [
"hanlulu1998@outlook.com"
] | hanlulu1998@outlook.com |
1173a0980f9c27cd66f9fb140b96e6b2d75e9901 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /third_party/node/linux/node-linux-x64/include/node/v8.h | a5aaf2d6842dde88ed66f48a5a6d9cac5ede6f35 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-openssl",
"Artistic-2.0",
"NAIST-2003",
"ICU",
"LicenseRef-scancode-unknown-license-reference",
"Zlib",
"ISC",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"NTP",
"BSD-2-Clause",
"LicenseRef-scan... | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 347,284 | h | // 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.
/** \mainpage V8 API Reference Guide
*
* V8 is Google's open source JavaScript engine.
*
* This set of documents provides reference material generated from the
* V8 header file, include/v8.h.
*
* For other documentation see http://code.google.com/apis/v8/
*/
#ifndef INCLUDE_V8_H_
#define INCLUDE_V8_H_
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <memory>
#include <utility>
#include <vector>
#include "v8-version.h" // NOLINT(build/include)
#include "v8config.h" // NOLINT(build/include)
// We reserve the V8_* prefix for macros defined in V8 public API and
// assume there are no name conflicts with the embedder's code.
#ifdef V8_OS_WIN
// Setup for Windows DLL export/import. When building the V8 DLL the
// BUILDING_V8_SHARED needs to be defined. When building a program which uses
// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
// static library or building a program which uses the V8 static library neither
// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
#ifdef BUILDING_V8_SHARED
# define V8_EXPORT __declspec(dllexport)
#elif USING_V8_SHARED
# define V8_EXPORT __declspec(dllimport)
#else
# define V8_EXPORT
#endif // BUILDING_V8_SHARED
#else // V8_OS_WIN
// Setup for Linux shared library export.
#if V8_HAS_ATTRIBUTE_VISIBILITY
# ifdef BUILDING_V8_SHARED
# define V8_EXPORT __attribute__ ((visibility("default")))
# else
# define V8_EXPORT
# endif
#else
# define V8_EXPORT
#endif
#endif // V8_OS_WIN
/**
* The v8 JavaScript engine.
*/
namespace v8 {
class AccessorSignature;
class Array;
class ArrayBuffer;
class BigInt;
class BigIntObject;
class Boolean;
class BooleanObject;
class Context;
class CpuProfiler;
class Data;
class Date;
class External;
class Function;
class FunctionTemplate;
class HeapProfiler;
class ImplementationUtilities;
class Int32;
class Integer;
class Isolate;
template <class T>
class Maybe;
class Name;
class Number;
class NumberObject;
class Object;
class ObjectOperationDescriptor;
class ObjectTemplate;
class Platform;
class Primitive;
class Promise;
class PropertyDescriptor;
class Proxy;
class RawOperationDescriptor;
class Script;
class SharedArrayBuffer;
class Signature;
class StartupData;
class StackFrame;
class StackTrace;
class String;
class StringObject;
class Symbol;
class SymbolObject;
class PrimitiveArray;
class Private;
class Uint32;
class Utils;
class Value;
class WasmCompiledModule;
template <class T> class Local;
template <class T>
class MaybeLocal;
template <class T> class Eternal;
template<class T> class NonCopyablePersistentTraits;
template<class T> class PersistentBase;
template <class T, class M = NonCopyablePersistentTraits<T> >
class Persistent;
template <class T>
class Global;
template<class K, class V, class T> class PersistentValueMap;
template <class K, class V, class T>
class PersistentValueMapBase;
template <class K, class V, class T>
class GlobalValueMap;
template<class V, class T> class PersistentValueVector;
template<class T, class P> class WeakCallbackObject;
class FunctionTemplate;
class ObjectTemplate;
template<typename T> class FunctionCallbackInfo;
template<typename T> class PropertyCallbackInfo;
class StackTrace;
class StackFrame;
class Isolate;
class CallHandlerHelper;
class EscapableHandleScope;
template<typename T> class ReturnValue;
namespace internal {
class Arguments;
class DeferredHandles;
class Heap;
class HeapObject;
class Isolate;
class Object;
struct ScriptStreamingData;
template<typename T> class CustomArguments;
class PropertyCallbackArguments;
class FunctionCallbackArguments;
class GlobalHandles;
namespace wasm {
class StreamingDecoder;
} // namespace wasm
} // namespace internal
namespace debug {
class ConsoleCallArguments;
} // namespace debug
// --- Handles ---
#define TYPE_CHECK(T, S) \
while (false) { \
*(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
}
/**
* An object reference managed by the v8 garbage collector.
*
* All objects returned from v8 have to be tracked by the garbage
* collector so that it knows that the objects are still alive. Also,
* because the garbage collector may move objects, it is unsafe to
* point directly to an object. Instead, all objects are stored in
* handles which are known by the garbage collector and updated
* whenever an object moves. Handles should always be passed by value
* (except in cases like out-parameters) and they should never be
* allocated on the heap.
*
* There are two types of handles: local and persistent handles.
*
* Local handles are light-weight and transient and typically used in
* local operations. They are managed by HandleScopes. That means that a
* HandleScope must exist on the stack when they are created and that they are
* only valid inside of the HandleScope active during their creation.
* For passing a local handle to an outer HandleScope, an EscapableHandleScope
* and its Escape() method must be used.
*
* Persistent handles can be used when storing objects across several
* independent operations and have to be explicitly deallocated when they're no
* longer used.
*
* It is safe to extract the object stored in the handle by
* dereferencing the handle (for instance, to extract the Object* from
* a Local<Object>); the value will still be governed by a handle
* behind the scenes and the same rules apply to these values as to
* their handles.
*/
template <class T>
class Local {
public:
V8_INLINE Local() : val_(0) {}
template <class S>
V8_INLINE Local(Local<S> that)
: val_(reinterpret_cast<T*>(*that)) {
/**
* This check fails when trying to convert between incompatible
* handles. For example, converting from a Local<String> to a
* Local<Number>.
*/
TYPE_CHECK(T, S);
}
/**
* Returns true if the handle is empty.
*/
V8_INLINE bool IsEmpty() const { return val_ == 0; }
/**
* Sets the handle to be empty. IsEmpty() will then return true.
*/
V8_INLINE void Clear() { val_ = 0; }
V8_INLINE T* operator->() const { return val_; }
V8_INLINE T* operator*() const { return val_; }
/**
* Checks whether two handles are the same.
* Returns true if both are empty, or if the objects
* to which they refer are identical.
* The handles' references are not checked.
*/
template <class S>
V8_INLINE bool operator==(const Local<S>& that) const {
internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
if (a == 0) return b == 0;
if (b == 0) return false;
return *a == *b;
}
template <class S> V8_INLINE bool operator==(
const PersistentBase<S>& that) const {
internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
if (a == 0) return b == 0;
if (b == 0) return false;
return *a == *b;
}
/**
* Checks whether two handles are different.
* Returns true if only one of the handles is empty, or if
* the objects to which they refer are different.
* The handles' references are not checked.
*/
template <class S>
V8_INLINE bool operator!=(const Local<S>& that) const {
return !operator==(that);
}
template <class S> V8_INLINE bool operator!=(
const Persistent<S>& that) const {
return !operator==(that);
}
/**
* Cast a handle to a subclass, e.g. Local<Value> to Local<Object>.
* This is only valid if the handle actually refers to a value of the
* target type.
*/
template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
#ifdef V8_ENABLE_CHECKS
// If we're going to perform the type check then we have to check
// that the handle isn't empty before doing the checked cast.
if (that.IsEmpty()) return Local<T>();
#endif
return Local<T>(T::Cast(*that));
}
/**
* Calling this is equivalent to Local<S>::Cast().
* In particular, this is only valid if the handle actually refers to a value
* of the target type.
*/
template <class S>
V8_INLINE Local<S> As() const {
return Local<S>::Cast(*this);
}
/**
* Create a local handle for the content of another handle.
* The referee is kept alive by the local handle even when
* the original handle is destroyed/disposed.
*/
V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
V8_INLINE static Local<T> New(Isolate* isolate,
const PersistentBase<T>& that);
private:
friend class Utils;
template<class F> friend class Eternal;
template<class F> friend class PersistentBase;
template<class F, class M> friend class Persistent;
template<class F> friend class Local;
template <class F>
friend class MaybeLocal;
template<class F> friend class FunctionCallbackInfo;
template<class F> friend class PropertyCallbackInfo;
friend class String;
friend class Object;
friend class Context;
friend class Isolate;
friend class Private;
template<class F> friend class internal::CustomArguments;
friend Local<Primitive> Undefined(Isolate* isolate);
friend Local<Primitive> Null(Isolate* isolate);
friend Local<Boolean> True(Isolate* isolate);
friend Local<Boolean> False(Isolate* isolate);
friend class HandleScope;
friend class EscapableHandleScope;
template <class F1, class F2, class F3>
friend class PersistentValueMapBase;
template<class F1, class F2> friend class PersistentValueVector;
template <class F>
friend class ReturnValue;
explicit V8_INLINE Local(T* that) : val_(that) {}
V8_INLINE static Local<T> New(Isolate* isolate, T* that);
T* val_;
};
#if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
// Handle is an alias for Local for historical reasons.
template <class T>
using Handle = Local<T>;
#endif
/**
* A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
* the Local<> is empty before it can be used.
*
* If an API method returns a MaybeLocal<>, the API method can potentially fail
* either because an exception is thrown, or because an exception is pending,
* e.g. because a previous API call threw an exception that hasn't been caught
* yet, or because a TerminateExecution exception was thrown. In that case, an
* empty MaybeLocal is returned.
*/
template <class T>
class MaybeLocal {
public:
V8_INLINE MaybeLocal() : val_(nullptr) {}
template <class S>
V8_INLINE MaybeLocal(Local<S> that)
: val_(reinterpret_cast<T*>(*that)) {
TYPE_CHECK(T, S);
}
V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
/**
* Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
* |false| is returned and |out| is left untouched.
*/
template <class S>
V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const {
out->val_ = IsEmpty() ? nullptr : this->val_;
return !IsEmpty();
}
/**
* Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
* V8 will crash the process.
*/
V8_INLINE Local<T> ToLocalChecked();
/**
* Converts this MaybeLocal<> to a Local<>, using a default value if this
* MaybeLocal<> is empty.
*/
template <class S>
V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
return IsEmpty() ? default_value : Local<S>(val_);
}
private:
T* val_;
};
/**
* Eternal handles are set-once handles that live for the lifetime of the
* isolate.
*/
template <class T> class Eternal {
public:
V8_INLINE Eternal() : val_(nullptr) {}
template <class S>
V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : val_(nullptr) {
Set(isolate, handle);
}
// Can only be safely called if already set.
V8_INLINE Local<T> Get(Isolate* isolate) const;
V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
private:
T* val_;
};
static const int kInternalFieldsInWeakCallback = 2;
static const int kEmbedderFieldsInWeakCallback = 2;
template <typename T>
class WeakCallbackInfo {
public:
typedef void (*Callback)(const WeakCallbackInfo<T>& data);
WeakCallbackInfo(Isolate* isolate, T* parameter,
void* embedder_fields[kEmbedderFieldsInWeakCallback],
Callback* callback)
: isolate_(isolate), parameter_(parameter), callback_(callback) {
for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
embedder_fields_[i] = embedder_fields[i];
}
}
V8_INLINE Isolate* GetIsolate() const { return isolate_; }
V8_INLINE T* GetParameter() const { return parameter_; }
V8_INLINE void* GetInternalField(int index) const;
// When first called, the embedder MUST Reset() the Global which triggered the
// callback. The Global itself is unusable for anything else. No v8 other api
// calls may be called in the first callback. Should additional work be
// required, the embedder must set a second pass callback, which will be
// called after all the initial callbacks are processed.
// Calling SetSecondPassCallback on the second pass will immediately crash.
void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
private:
Isolate* isolate_;
T* parameter_;
Callback* callback_;
void* embedder_fields_[kEmbedderFieldsInWeakCallback];
};
// kParameter will pass a void* parameter back to the callback, kInternalFields
// will pass the first two internal fields back to the callback, kFinalizer
// will pass a void* parameter back, but is invoked before the object is
// actually collected, so it can be resurrected. In the last case, it is not
// possible to request a second pass callback.
enum class WeakCallbackType { kParameter, kInternalFields, kFinalizer };
/**
* An object reference that is independent of any handle scope. Where
* a Local handle only lives as long as the HandleScope in which it was
* allocated, a PersistentBase handle remains valid until it is explicitly
* disposed using Reset().
*
* A persistent handle contains a reference to a storage cell within
* the V8 engine which holds an object value and which is updated by
* the garbage collector whenever the object is moved. A new storage
* cell can be created using the constructor or PersistentBase::Reset and
* existing handles can be disposed using PersistentBase::Reset.
*
*/
template <class T> class PersistentBase {
public:
/**
* If non-empty, destroy the underlying storage cell
* IsEmpty() will return true after this call.
*/
V8_INLINE void Reset();
/**
* If non-empty, destroy the underlying storage cell
* and create a new one with the contents of other if other is non empty
*/
template <class S>
V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
/**
* If non-empty, destroy the underlying storage cell
* and create a new one with the contents of other if other is non empty
*/
template <class S>
V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
V8_INLINE bool IsEmpty() const { return val_ == NULL; }
V8_INLINE void Empty() { val_ = 0; }
V8_INLINE Local<T> Get(Isolate* isolate) const {
return Local<T>::New(isolate, *this);
}
template <class S>
V8_INLINE bool operator==(const PersistentBase<S>& that) const {
internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
if (a == NULL) return b == NULL;
if (b == NULL) return false;
return *a == *b;
}
template <class S>
V8_INLINE bool operator==(const Local<S>& that) const {
internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
if (a == NULL) return b == NULL;
if (b == NULL) return false;
return *a == *b;
}
template <class S>
V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
return !operator==(that);
}
template <class S>
V8_INLINE bool operator!=(const Local<S>& that) const {
return !operator==(that);
}
/**
* Install a finalization callback on this object.
* NOTE: There is no guarantee as to *when* or even *if* the callback is
* invoked. The invocation is performed solely on a best effort basis.
* As always, GC-based finalization should *not* be relied upon for any
* critical form of resource management!
*/
template <typename P>
V8_INLINE void SetWeak(P* parameter,
typename WeakCallbackInfo<P>::Callback callback,
WeakCallbackType type);
/**
* Turns this handle into a weak phantom handle without finalization callback.
* The handle will be reset automatically when the garbage collector detects
* that the object is no longer reachable.
* A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall
* returns how many phantom handles were reset by the garbage collector.
*/
V8_INLINE void SetWeak();
template<typename P>
V8_INLINE P* ClearWeak();
// TODO(dcarney): remove this.
V8_INLINE void ClearWeak() { ClearWeak<void>(); }
/**
* Annotates the strong handle with the given label, which is then used by the
* heap snapshot generator as a name of the edge from the root to the handle.
* The function does not take ownership of the label and assumes that the
* label is valid as long as the handle is valid.
*/
V8_INLINE void AnnotateStrongRetainer(const char* label);
/**
* Allows the embedder to tell the v8 garbage collector that a certain object
* is alive. Only allowed when the embedder is asked to trace its heap by
* EmbedderHeapTracer.
*/
V8_INLINE void RegisterExternalReference(Isolate* isolate) const;
/**
* Marks the reference to this object independent. Garbage collector is free
* to ignore any object groups containing this object. Weak callback for an
* independent handle should not assume that it will be preceded by a global
* GC prologue callback or followed by a global GC epilogue callback.
*/
V8_DEPRECATE_SOON(
"Objects are always considered independent. "
"Use MarkActive to avoid collecting otherwise dead weak handles.",
V8_INLINE void MarkIndependent());
/**
* Marks the reference to this object as active. The scavenge garbage
* collection should not reclaim the objects marked as active, even if the
* object held by the handle is otherwise unreachable.
*
* This bit is cleared after the each garbage collection pass.
*/
V8_INLINE void MarkActive();
V8_DEPRECATE_SOON("See MarkIndependent.",
V8_INLINE bool IsIndependent() const);
/** Checks if the handle holds the only reference to an object. */
V8_INLINE bool IsNearDeath() const;
/** Returns true if the handle's reference is weak. */
V8_INLINE bool IsWeak() const;
/**
* Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
* description in v8-profiler.h for details.
*/
V8_INLINE void SetWrapperClassId(uint16_t class_id);
/**
* Returns the class ID previously assigned to this handle or 0 if no class ID
* was previously assigned.
*/
V8_INLINE uint16_t WrapperClassId() const;
PersistentBase(const PersistentBase& other) = delete; // NOLINT
void operator=(const PersistentBase&) = delete;
private:
friend class Isolate;
friend class Utils;
template<class F> friend class Local;
template<class F1, class F2> friend class Persistent;
template <class F>
friend class Global;
template<class F> friend class PersistentBase;
template<class F> friend class ReturnValue;
template <class F1, class F2, class F3>
friend class PersistentValueMapBase;
template<class F1, class F2> friend class PersistentValueVector;
friend class Object;
explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
V8_INLINE static T* New(Isolate* isolate, T* that);
T* val_;
};
/**
* Default traits for Persistent. This class does not allow
* use of the copy constructor or assignment operator.
* At present kResetInDestructor is not set, but that will change in a future
* version.
*/
template<class T>
class NonCopyablePersistentTraits {
public:
typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
static const bool kResetInDestructor = false;
template<class S, class M>
V8_INLINE static void Copy(const Persistent<S, M>& source,
NonCopyablePersistent* dest) {
Uncompilable<Object>();
}
// TODO(dcarney): come up with a good compile error here.
template<class O> V8_INLINE static void Uncompilable() {
TYPE_CHECK(O, Primitive);
}
};
/**
* Helper class traits to allow copying and assignment of Persistent.
* This will clone the contents of storage cell, but not any of the flags, etc.
*/
template<class T>
struct CopyablePersistentTraits {
typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
static const bool kResetInDestructor = true;
template<class S, class M>
static V8_INLINE void Copy(const Persistent<S, M>& source,
CopyablePersistent* dest) {
// do nothing, just allow copy
}
};
/**
* A PersistentBase which allows copy and assignment.
*
* Copy, assignment and destructor behavior is controlled by the traits
* class M.
*
* Note: Persistent class hierarchy is subject to future changes.
*/
template <class T, class M> class Persistent : public PersistentBase<T> {
public:
/**
* A Persistent with no storage cell.
*/
V8_INLINE Persistent() : PersistentBase<T>(0) { }
/**
* Construct a Persistent from a Local.
* When the Local is non-empty, a new storage cell is created
* pointing to the same object, and no flags are set.
*/
template <class S>
V8_INLINE Persistent(Isolate* isolate, Local<S> that)
: PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
TYPE_CHECK(T, S);
}
/**
* Construct a Persistent from a Persistent.
* When the Persistent is non-empty, a new storage cell is created
* pointing to the same object, and no flags are set.
*/
template <class S, class M2>
V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
: PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
TYPE_CHECK(T, S);
}
/**
* The copy constructors and assignment operator create a Persistent
* exactly as the Persistent constructor, but the Copy function from the
* traits class is called, allowing the setting of flags based on the
* copied Persistent.
*/
V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
Copy(that);
}
template <class S, class M2>
V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
Copy(that);
}
V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
Copy(that);
return *this;
}
template <class S, class M2>
V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
Copy(that);
return *this;
}
/**
* The destructor will dispose the Persistent based on the
* kResetInDestructor flags in the traits class. Since not calling dispose
* can result in a memory leak, it is recommended to always set this flag.
*/
V8_INLINE ~Persistent() {
if (M::kResetInDestructor) this->Reset();
}
// TODO(dcarney): this is pretty useless, fix or remove
template <class S>
V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) { // NOLINT
#ifdef V8_ENABLE_CHECKS
// If we're going to perform the type check then we have to check
// that the handle isn't empty before doing the checked cast.
if (!that.IsEmpty()) T::Cast(*that);
#endif
return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that));
}
// TODO(dcarney): this is pretty useless, fix or remove
template <class S>
V8_INLINE Persistent<S>& As() const { // NOLINT
return Persistent<S>::Cast(*this);
}
private:
friend class Isolate;
friend class Utils;
template<class F> friend class Local;
template<class F1, class F2> friend class Persistent;
template<class F> friend class ReturnValue;
explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {}
V8_INLINE T* operator*() const { return this->val_; }
template<class S, class M2>
V8_INLINE void Copy(const Persistent<S, M2>& that);
};
/**
* A PersistentBase which has move semantics.
*
* Note: Persistent class hierarchy is subject to future changes.
*/
template <class T>
class Global : public PersistentBase<T> {
public:
/**
* A Global with no storage cell.
*/
V8_INLINE Global() : PersistentBase<T>(nullptr) {}
/**
* Construct a Global from a Local.
* When the Local is non-empty, a new storage cell is created
* pointing to the same object, and no flags are set.
*/
template <class S>
V8_INLINE Global(Isolate* isolate, Local<S> that)
: PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
TYPE_CHECK(T, S);
}
/**
* Construct a Global from a PersistentBase.
* When the Persistent is non-empty, a new storage cell is created
* pointing to the same object, and no flags are set.
*/
template <class S>
V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
: PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
TYPE_CHECK(T, S);
}
/**
* Move constructor.
*/
V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) { // NOLINT
other.val_ = nullptr;
}
V8_INLINE ~Global() { this->Reset(); }
/**
* Move via assignment.
*/
template <class S>
V8_INLINE Global& operator=(Global<S>&& rhs) { // NOLINT
TYPE_CHECK(T, S);
if (this != &rhs) {
this->Reset();
this->val_ = rhs.val_;
rhs.val_ = nullptr;
}
return *this;
}
/**
* Pass allows returning uniques from functions, etc.
*/
Global Pass() { return static_cast<Global&&>(*this); } // NOLINT
/*
* For compatibility with Chromium's base::Bind (base::Passed).
*/
typedef void MoveOnlyTypeForCPP03;
Global(const Global&) = delete;
void operator=(const Global&) = delete;
private:
template <class F>
friend class ReturnValue;
V8_INLINE T* operator*() const { return this->val_; }
};
// UniquePersistent is an alias for Global for historical reason.
template <class T>
using UniquePersistent = Global<T>;
/**
* A stack-allocated class that governs a number of local handles.
* After a handle scope has been created, all local handles will be
* allocated within that handle scope until either the handle scope is
* deleted or another handle scope is created. If there is already a
* handle scope and a new one is created, all allocations will take
* place in the new handle scope until it is deleted. After that,
* new handles will again be allocated in the original handle scope.
*
* After the handle scope of a local handle has been deleted the
* garbage collector will no longer track the object stored in the
* handle and may deallocate it. The behavior of accessing a handle
* for which the handle scope has been deleted is undefined.
*/
class V8_EXPORT HandleScope {
public:
explicit HandleScope(Isolate* isolate);
~HandleScope();
/**
* Counts the number of allocated handles.
*/
static int NumberOfHandles(Isolate* isolate);
V8_INLINE Isolate* GetIsolate() const {
return reinterpret_cast<Isolate*>(isolate_);
}
HandleScope(const HandleScope&) = delete;
void operator=(const HandleScope&) = delete;
protected:
V8_INLINE HandleScope() {}
void Initialize(Isolate* isolate);
static internal::Object** CreateHandle(internal::Isolate* isolate,
internal::Object* value);
private:
// Declaring operator new and delete as deleted is not spec compliant.
// Therefore declare them private instead to disable dynamic alloc
void* operator new(size_t size);
void* operator new[](size_t size);
void operator delete(void*, size_t);
void operator delete[](void*, size_t);
// Uses heap_object to obtain the current Isolate.
static internal::Object** CreateHandle(internal::HeapObject* heap_object,
internal::Object* value);
internal::Isolate* isolate_;
internal::Object** prev_next_;
internal::Object** prev_limit_;
// Local::New uses CreateHandle with an Isolate* parameter.
template<class F> friend class Local;
// Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
// a HeapObject* in their shortcuts.
friend class Object;
friend class Context;
};
/**
* A HandleScope which first allocates a handle in the current scope
* which will be later filled with the escape value.
*/
class V8_EXPORT EscapableHandleScope : public HandleScope {
public:
explicit EscapableHandleScope(Isolate* isolate);
V8_INLINE ~EscapableHandleScope() {}
/**
* Pushes the value into the previous scope and returns a handle to it.
* Cannot be called twice.
*/
template <class T>
V8_INLINE Local<T> Escape(Local<T> value) {
internal::Object** slot =
Escape(reinterpret_cast<internal::Object**>(*value));
return Local<T>(reinterpret_cast<T*>(slot));
}
EscapableHandleScope(const EscapableHandleScope&) = delete;
void operator=(const EscapableHandleScope&) = delete;
private:
// Declaring operator new and delete as deleted is not spec compliant.
// Therefore declare them private instead to disable dynamic alloc
void* operator new(size_t size);
void* operator new[](size_t size);
void operator delete(void*, size_t);
void operator delete[](void*, size_t);
internal::Object** Escape(internal::Object** escape_value);
internal::Object** escape_slot_;
};
/**
* A SealHandleScope acts like a handle scope in which no handle allocations
* are allowed. It can be useful for debugging handle leaks.
* Handles can be allocated within inner normal HandleScopes.
*/
class V8_EXPORT SealHandleScope {
public:
explicit SealHandleScope(Isolate* isolate);
~SealHandleScope();
SealHandleScope(const SealHandleScope&) = delete;
void operator=(const SealHandleScope&) = delete;
private:
// Declaring operator new and delete as deleted is not spec compliant.
// Therefore declare them private instead to disable dynamic alloc
void* operator new(size_t size);
void* operator new[](size_t size);
void operator delete(void*, size_t);
void operator delete[](void*, size_t);
internal::Isolate* const isolate_;
internal::Object** prev_limit_;
int prev_sealed_level_;
};
// --- Special objects ---
/**
* The superclass of values and API object templates.
*/
class V8_EXPORT Data {
private:
Data();
};
/**
* A container type that holds relevant metadata for module loading.
*
* This is passed back to the embedder as part of
* HostImportModuleDynamicallyCallback for module loading.
*/
class V8_EXPORT ScriptOrModule {
public:
/**
* The name that was passed by the embedder as ResourceName to the
* ScriptOrigin. This can be either a v8::String or v8::Undefined.
*/
Local<Value> GetResourceName();
/**
* The options that were passed by the embedder as HostDefinedOptions to
* the ScriptOrigin.
*/
Local<PrimitiveArray> GetHostDefinedOptions();
};
/**
* An array to hold Primitive values. This is used by the embedder to
* pass host defined options to the ScriptOptions during compilation.
*
* This is passed back to the embedder as part of
* HostImportModuleDynamicallyCallback for module loading.
*
*/
class V8_EXPORT PrimitiveArray {
public:
static Local<PrimitiveArray> New(Isolate* isolate, int length);
int Length() const;
V8_DEPRECATE_SOON("Use Isolate* version",
void Set(int index, Local<Primitive> item));
V8_DEPRECATE_SOON("Use Isolate* version",
Local<Primitive> Get(int index));
void Set(Isolate* isolate, int index, Local<Primitive> item);
Local<Primitive> Get(Isolate* isolate, int index);
};
/**
* The optional attributes of ScriptOrigin.
*/
class ScriptOriginOptions {
public:
V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false,
bool is_opaque = false, bool is_wasm = false,
bool is_module = false)
: flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
(is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
(is_module ? kIsModule : 0)) {}
V8_INLINE ScriptOriginOptions(int flags)
: flags_(flags &
(kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
bool IsSharedCrossOrigin() const {
return (flags_ & kIsSharedCrossOrigin) != 0;
}
bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
bool IsModule() const { return (flags_ & kIsModule) != 0; }
int Flags() const { return flags_; }
private:
enum {
kIsSharedCrossOrigin = 1,
kIsOpaque = 1 << 1,
kIsWasm = 1 << 2,
kIsModule = 1 << 3
};
const int flags_;
};
/**
* The origin, within a file, of a script.
*/
class ScriptOrigin {
public:
V8_INLINE ScriptOrigin(
Local<Value> resource_name,
Local<Integer> resource_line_offset = Local<Integer>(),
Local<Integer> resource_column_offset = Local<Integer>(),
Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
Local<Integer> script_id = Local<Integer>(),
Local<Value> source_map_url = Local<Value>(),
Local<Boolean> resource_is_opaque = Local<Boolean>(),
Local<Boolean> is_wasm = Local<Boolean>(),
Local<Boolean> is_module = Local<Boolean>(),
Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
V8_INLINE Local<Value> ResourceName() const;
V8_INLINE Local<Integer> ResourceLineOffset() const;
V8_INLINE Local<Integer> ResourceColumnOffset() const;
V8_INLINE Local<Integer> ScriptID() const;
V8_INLINE Local<Value> SourceMapUrl() const;
V8_INLINE Local<PrimitiveArray> HostDefinedOptions() const;
V8_INLINE ScriptOriginOptions Options() const { return options_; }
private:
Local<Value> resource_name_;
Local<Integer> resource_line_offset_;
Local<Integer> resource_column_offset_;
ScriptOriginOptions options_;
Local<Integer> script_id_;
Local<Value> source_map_url_;
Local<PrimitiveArray> host_defined_options_;
};
/**
* A compiled JavaScript script, not yet tied to a Context.
*/
class V8_EXPORT UnboundScript {
public:
/**
* Binds the script to the currently entered context.
*/
Local<Script> BindToCurrentContext();
int GetId();
Local<Value> GetScriptName();
/**
* Data read from magic sourceURL comments.
*/
Local<Value> GetSourceURL();
/**
* Data read from magic sourceMappingURL comments.
*/
Local<Value> GetSourceMappingURL();
/**
* Returns zero based line number of the code_pos location in the script.
* -1 will be returned if no information available.
*/
int GetLineNumber(int code_pos);
static const int kNoScriptId = 0;
};
/**
* A compiled JavaScript module, not yet tied to a Context.
*/
class V8_EXPORT UnboundModuleScript {
// Only used as a container for code caching.
};
/**
* A location in JavaScript source.
*/
class V8_EXPORT Location {
public:
int GetLineNumber() { return line_number_; }
int GetColumnNumber() { return column_number_; }
Location(int line_number, int column_number)
: line_number_(line_number), column_number_(column_number) {}
private:
int line_number_;
int column_number_;
};
/**
* A compiled JavaScript module.
*/
class V8_EXPORT Module {
public:
/**
* The different states a module can be in.
*
* This corresponds to the states used in ECMAScript except that "evaluated"
* is split into kEvaluated and kErrored, indicating success and failure,
* respectively.
*/
enum Status {
kUninstantiated,
kInstantiating,
kInstantiated,
kEvaluating,
kEvaluated,
kErrored
};
/**
* Returns the module's current status.
*/
Status GetStatus() const;
/**
* For a module in kErrored status, this returns the corresponding exception.
*/
Local<Value> GetException() const;
/**
* Returns the number of modules requested by this module.
*/
int GetModuleRequestsLength() const;
/**
* Returns the ith module specifier in this module.
* i must be < GetModuleRequestsLength() and >= 0.
*/
Local<String> GetModuleRequest(int i) const;
/**
* Returns the source location (line number and column number) of the ith
* module specifier's first occurrence in this module.
*/
Location GetModuleRequestLocation(int i) const;
/**
* Returns the identity hash for this object.
*/
int GetIdentityHash() const;
typedef MaybeLocal<Module> (*ResolveCallback)(Local<Context> context,
Local<String> specifier,
Local<Module> referrer);
/**
* Instantiates the module and its dependencies.
*
* Returns an empty Maybe<bool> if an exception occurred during
* instantiation. (In the case where the callback throws an exception, that
* exception is propagated.)
*/
V8_WARN_UNUSED_RESULT Maybe<bool> InstantiateModule(Local<Context> context,
ResolveCallback callback);
/**
* Evaluates the module and its dependencies.
*
* If status is kInstantiated, run the module's code. On success, set status
* to kEvaluated and return the completion value; on failure, set status to
* kErrored and propagate the thrown exception (which is then also available
* via |GetException|).
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Evaluate(Local<Context> context);
/**
* Returns the namespace object of this module.
*
* The module's status must be at least kInstantiated.
*/
Local<Value> GetModuleNamespace();
/**
* Returns the corresponding context-unbound module script.
*
* The module must be unevaluated, i.e. its status must not be kEvaluating,
* kEvaluated or kErrored.
*/
Local<UnboundModuleScript> GetUnboundModuleScript();
};
/**
* A compiled JavaScript script, tied to a Context which was active when the
* script was compiled.
*/
class V8_EXPORT Script {
public:
/**
* A shorthand for ScriptCompiler::Compile().
*/
static V8_DEPRECATED("Use maybe version",
Local<Script> Compile(Local<String> source,
ScriptOrigin* origin = nullptr));
static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
Local<Context> context, Local<String> source,
ScriptOrigin* origin = nullptr);
static Local<Script> V8_DEPRECATED("Use maybe version",
Compile(Local<String> source,
Local<String> file_name));
/**
* Runs the script returning the resulting value. It will be run in the
* context in which it was created (ScriptCompiler::CompileBound or
* UnboundScript::BindToCurrentContext()).
*/
V8_DEPRECATED("Use maybe version", Local<Value> Run());
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context);
/**
* Returns the corresponding context-unbound script.
*/
Local<UnboundScript> GetUnboundScript();
};
/**
* For compiling scripts.
*/
class V8_EXPORT ScriptCompiler {
public:
/**
* Compilation data that the embedder can cache and pass back to speed up
* future compilations. The data is produced if the CompilerOptions passed to
* the compilation functions in ScriptCompiler contains produce_data_to_cache
* = true. The data to cache can then can be retrieved from
* UnboundScript.
*/
struct V8_EXPORT CachedData {
enum BufferPolicy {
BufferNotOwned,
BufferOwned
};
CachedData()
: data(NULL),
length(0),
rejected(false),
buffer_policy(BufferNotOwned) {}
// If buffer_policy is BufferNotOwned, the caller keeps the ownership of
// data and guarantees that it stays alive until the CachedData object is
// destroyed. If the policy is BufferOwned, the given data will be deleted
// (with delete[]) when the CachedData object is destroyed.
CachedData(const uint8_t* data, int length,
BufferPolicy buffer_policy = BufferNotOwned);
~CachedData();
// TODO(marja): Async compilation; add constructors which take a callback
// which will be called when V8 no longer needs the data.
const uint8_t* data;
int length;
bool rejected;
BufferPolicy buffer_policy;
// Prevent copying.
CachedData(const CachedData&) = delete;
CachedData& operator=(const CachedData&) = delete;
};
/**
* Source code which can be then compiled to a UnboundScript or Script.
*/
class Source {
public:
// Source takes ownership of CachedData.
V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
CachedData* cached_data = NULL);
V8_INLINE Source(Local<String> source_string,
CachedData* cached_data = NULL);
V8_INLINE ~Source();
// Ownership of the CachedData or its buffers is *not* transferred to the
// caller. The CachedData object is alive as long as the Source object is
// alive.
V8_INLINE const CachedData* GetCachedData() const;
V8_INLINE const ScriptOriginOptions& GetResourceOptions() const;
// Prevent copying.
Source(const Source&) = delete;
Source& operator=(const Source&) = delete;
private:
friend class ScriptCompiler;
Local<String> source_string;
// Origin information
Local<Value> resource_name;
Local<Integer> resource_line_offset;
Local<Integer> resource_column_offset;
ScriptOriginOptions resource_options;
Local<Value> source_map_url;
Local<PrimitiveArray> host_defined_options;
// Cached data from previous compilation (if a kConsume*Cache flag is
// set), or hold newly generated cache data (kProduce*Cache flags) are
// set when calling a compile method.
CachedData* cached_data;
};
/**
* For streaming incomplete script data to V8. The embedder should implement a
* subclass of this class.
*/
class V8_EXPORT ExternalSourceStream {
public:
virtual ~ExternalSourceStream() {}
/**
* V8 calls this to request the next chunk of data from the embedder. This
* function will be called on a background thread, so it's OK to block and
* wait for the data, if the embedder doesn't have data yet. Returns the
* length of the data returned. When the data ends, GetMoreData should
* return 0. Caller takes ownership of the data.
*
* When streaming UTF-8 data, V8 handles multi-byte characters split between
* two data chunks, but doesn't handle multi-byte characters split between
* more than two data chunks. The embedder can avoid this problem by always
* returning at least 2 bytes of data.
*
* If the embedder wants to cancel the streaming, they should make the next
* GetMoreData call return 0. V8 will interpret it as end of data (and most
* probably, parsing will fail). The streaming task will return as soon as
* V8 has parsed the data it received so far.
*/
virtual size_t GetMoreData(const uint8_t** src) = 0;
/**
* V8 calls this method to set a 'bookmark' at the current position in
* the source stream, for the purpose of (maybe) later calling
* ResetToBookmark. If ResetToBookmark is called later, then subsequent
* calls to GetMoreData should return the same data as they did when
* SetBookmark was called earlier.
*
* The embedder may return 'false' to indicate it cannot provide this
* functionality.
*/
virtual bool SetBookmark();
/**
* V8 calls this to return to a previously set bookmark.
*/
virtual void ResetToBookmark();
};
/**
* Source code which can be streamed into V8 in pieces. It will be parsed
* while streaming. It can be compiled after the streaming is complete.
* StreamedSource must be kept alive while the streaming task is ran (see
* ScriptStreamingTask below).
*/
class V8_EXPORT StreamedSource {
public:
enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
~StreamedSource();
// Ownership of the CachedData or its buffers is *not* transferred to the
// caller. The CachedData object is alive as long as the StreamedSource
// object is alive.
const CachedData* GetCachedData() const;
internal::ScriptStreamingData* impl() const { return impl_; }
// Prevent copying.
StreamedSource(const StreamedSource&) = delete;
StreamedSource& operator=(const StreamedSource&) = delete;
private:
internal::ScriptStreamingData* impl_;
};
/**
* A streaming task which the embedder must run on a background thread to
* stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
*/
class ScriptStreamingTask {
public:
virtual ~ScriptStreamingTask() {}
virtual void Run() = 0;
};
enum CompileOptions {
kNoCompileOptions = 0,
kProduceParserCache,
kConsumeParserCache,
kProduceCodeCache,
kProduceFullCodeCache,
kConsumeCodeCache,
kEagerCompile
};
/**
* The reason for which we are not requesting or providing a code cache.
*/
enum NoCacheReason {
kNoCacheNoReason = 0,
kNoCacheBecauseCachingDisabled,
kNoCacheBecauseNoResource,
kNoCacheBecauseInlineScript,
kNoCacheBecauseModule,
kNoCacheBecauseStreamingSource,
kNoCacheBecauseInspector,
kNoCacheBecauseScriptTooSmall,
kNoCacheBecauseCacheTooCold,
kNoCacheBecauseV8Extension,
kNoCacheBecauseExtensionModule,
kNoCacheBecausePacScript,
kNoCacheBecauseInDocumentWrite,
kNoCacheBecauseResourceWithNoCacheHandler,
kNoCacheBecauseDeferredProduceCodeCache
};
/**
* Compiles the specified script (context-independent).
* Cached data as part of the source object can be optionally produced to be
* consumed later to speed up compilation of identical source scripts.
*
* Note that when producing cached data, the source must point to NULL for
* cached data. When consuming cached data, the cached data must have been
* produced by the same version of V8.
*
* \param source Script source code.
* \return Compiled script object (context independent; for running it must be
* bound to a context).
*/
static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript(
Isolate* isolate, Source* source,
CompileOptions options = kNoCompileOptions,
NoCacheReason no_cache_reason = kNoCacheNoReason);
/**
* Compiles the specified script (bound to current context).
*
* \param source Script source code.
* \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
* using pre_data speeds compilation if it's done multiple times.
* Owned by caller, no references are kept when this function returns.
* \return Compiled script object, bound to the context that was active
* when this function was called. When run it will always use this
* context.
*/
static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
Local<Context> context, Source* source,
CompileOptions options = kNoCompileOptions,
NoCacheReason no_cache_reason = kNoCacheNoReason);
/**
* Returns a task which streams script data into V8, or NULL if the script
* cannot be streamed. The user is responsible for running the task on a
* background thread and deleting it. When ran, the task starts parsing the
* script, and it will request data from the StreamedSource as needed. When
* ScriptStreamingTask::Run exits, all data has been streamed and the script
* can be compiled (see Compile below).
*
* This API allows to start the streaming with as little data as possible, and
* the remaining data (for example, the ScriptOrigin) is passed to Compile.
*/
static ScriptStreamingTask* StartStreamingScript(
Isolate* isolate, StreamedSource* source,
CompileOptions options = kNoCompileOptions);
/**
* Compiles a streamed script (bound to current context).
*
* This can only be called after the streaming has finished
* (ScriptStreamingTask has been run). V8 doesn't construct the source string
* during streaming, so the embedder needs to pass the full source here.
*/
static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
Local<Context> context, StreamedSource* source,
Local<String> full_source_string, const ScriptOrigin& origin);
/**
* Return a version tag for CachedData for the current V8 version & flags.
*
* This value is meant only for determining whether a previously generated
* CachedData instance is still valid; the tag has no other meaing.
*
* Background: The data carried by CachedData may depend on the exact
* V8 version number or current compiler flags. This means that when
* persisting CachedData, the embedder must take care to not pass in
* data from another V8 version, or the same version with different
* features enabled.
*
* The easiest way to do so is to clear the embedder's cache on any
* such change.
*
* Alternatively, this tag can be stored alongside the cached data and
* compared when it is being used.
*/
static uint32_t CachedDataVersionTag();
/**
* Compile an ES module, returning a Module that encapsulates
* the compiled code.
*
* Corresponds to the ParseModule abstract operation in the
* ECMAScript specification.
*/
static V8_WARN_UNUSED_RESULT MaybeLocal<Module> CompileModule(
Isolate* isolate, Source* source);
/**
* Compile a function for a given context. This is equivalent to running
*
* with (obj) {
* return function(args) { ... }
* }
*
* It is possible to specify multiple context extensions (obj in the above
* example).
*/
static V8_DEPRECATED("Use maybe version",
Local<Function> CompileFunctionInContext(
Isolate* isolate, Source* source,
Local<Context> context, size_t arguments_count,
Local<String> arguments[],
size_t context_extension_count,
Local<Object> context_extensions[]));
static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext(
Local<Context> context, Source* source, size_t arguments_count,
Local<String> arguments[], size_t context_extension_count,
Local<Object> context_extensions[],
CompileOptions options = kNoCompileOptions,
NoCacheReason no_cache_reason = kNoCacheNoReason);
/**
* Creates and returns code cache for the specified unbound_script.
* This will return nullptr if the script cannot be serialized. The
* CachedData returned by this function should be owned by the caller.
*/
static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script,
Local<String> source);
static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script);
/**
* Creates and returns code cache for the specified unbound_module_script.
* This will return nullptr if the script cannot be serialized. The
* CachedData returned by this function should be owned by the caller.
*/
static CachedData* CreateCodeCache(
Local<UnboundModuleScript> unbound_module_script);
/**
* Creates and returns code cache for the specified function that was
* previously produced by CompileFunctionInContext.
* This will return nullptr if the script cannot be serialized. The
* CachedData returned by this function should be owned by the caller.
*/
static CachedData* CreateCodeCacheForFunction(Local<Function> function,
Local<String> source);
static CachedData* CreateCodeCacheForFunction(Local<Function> function);
private:
static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
Isolate* isolate, Source* source, CompileOptions options,
NoCacheReason no_cache_reason);
};
/**
* An error message.
*/
class V8_EXPORT Message {
public:
Local<String> Get() const;
V8_DEPRECATED("Use maybe version", Local<String> GetSourceLine() const);
V8_WARN_UNUSED_RESULT MaybeLocal<String> GetSourceLine(
Local<Context> context) const;
/**
* Returns the origin for the script from where the function causing the
* error originates.
*/
ScriptOrigin GetScriptOrigin() const;
/**
* Returns the resource name for the script from where the function causing
* the error originates.
*/
Local<Value> GetScriptResourceName() const;
/**
* Exception stack trace. By default stack traces are not captured for
* uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
* to change this option.
*/
Local<StackTrace> GetStackTrace() const;
/**
* Returns the number, 1-based, of the line where the error occurred.
*/
V8_DEPRECATED("Use maybe version", int GetLineNumber() const);
V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
/**
* Returns the index within the script of the first character where
* the error occurred.
*/
int GetStartPosition() const;
/**
* Returns the index within the script of the last character where
* the error occurred.
*/
int GetEndPosition() const;
/**
* Returns the error level of the message.
*/
int ErrorLevel() const;
/**
* Returns the index within the line of the first character where
* the error occurred.
*/
int GetStartColumn() const;
V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
/**
* Returns the index within the line of the last character where
* the error occurred.
*/
int GetEndColumn() const;
V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
/**
* Passes on the value set by the embedder when it fed the script from which
* this Message was generated to V8.
*/
bool IsSharedCrossOrigin() const;
bool IsOpaque() const;
// TODO(1245381): Print to a string instead of on a FILE.
static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
static const int kNoLineNumberInfo = 0;
static const int kNoColumnInfo = 0;
static const int kNoScriptIdInfo = 0;
};
/**
* Representation of a JavaScript stack trace. The information collected is a
* snapshot of the execution stack and the information remains valid after
* execution continues.
*/
class V8_EXPORT StackTrace {
public:
/**
* Flags that determine what information is placed captured for each
* StackFrame when grabbing the current stack trace.
* Note: these options are deprecated and we always collect all available
* information (kDetailed).
*/
enum StackTraceOptions {
kLineNumber = 1,
kColumnOffset = 1 << 1 | kLineNumber,
kScriptName = 1 << 2,
kFunctionName = 1 << 3,
kIsEval = 1 << 4,
kIsConstructor = 1 << 5,
kScriptNameOrSourceURL = 1 << 6,
kScriptId = 1 << 7,
kExposeFramesAcrossSecurityOrigins = 1 << 8,
kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
};
/**
* Returns a StackFrame at a particular index.
*/
V8_DEPRECATE_SOON("Use Isolate version",
Local<StackFrame> GetFrame(uint32_t index) const);
Local<StackFrame> GetFrame(Isolate* isolate, uint32_t index) const;
/**
* Returns the number of StackFrames.
*/
int GetFrameCount() const;
/**
* Grab a snapshot of the current JavaScript execution stack.
*
* \param frame_limit The maximum number of stack frames we want to capture.
* \param options Enumerates the set of things we will capture for each
* StackFrame.
*/
static Local<StackTrace> CurrentStackTrace(
Isolate* isolate, int frame_limit, StackTraceOptions options = kDetailed);
};
/**
* A single JavaScript stack frame.
*/
class V8_EXPORT StackFrame {
public:
/**
* Returns the number, 1-based, of the line for the associate function call.
* This method will return Message::kNoLineNumberInfo if it is unable to
* retrieve the line number, or if kLineNumber was not passed as an option
* when capturing the StackTrace.
*/
int GetLineNumber() const;
/**
* Returns the 1-based column offset on the line for the associated function
* call.
* This method will return Message::kNoColumnInfo if it is unable to retrieve
* the column number, or if kColumnOffset was not passed as an option when
* capturing the StackTrace.
*/
int GetColumn() const;
/**
* Returns the id of the script for the function for this StackFrame.
* This method will return Message::kNoScriptIdInfo if it is unable to
* retrieve the script id, or if kScriptId was not passed as an option when
* capturing the StackTrace.
*/
int GetScriptId() const;
/**
* Returns the name of the resource that contains the script for the
* function for this StackFrame.
*/
Local<String> GetScriptName() const;
/**
* Returns the name of the resource that contains the script for the
* function for this StackFrame or sourceURL value if the script name
* is undefined and its source ends with //# sourceURL=... string or
* deprecated //@ sourceURL=... string.
*/
Local<String> GetScriptNameOrSourceURL() const;
/**
* Returns the name of the function associated with this stack frame.
*/
Local<String> GetFunctionName() const;
/**
* Returns whether or not the associated function is compiled via a call to
* eval().
*/
bool IsEval() const;
/**
* Returns whether or not the associated function is called as a
* constructor via "new".
*/
bool IsConstructor() const;
/**
* Returns whether or not the associated functions is defined in wasm.
*/
bool IsWasm() const;
};
// A StateTag represents a possible state of the VM.
enum StateTag {
JS,
GC,
PARSER,
BYTECODE_COMPILER,
COMPILER,
OTHER,
EXTERNAL,
IDLE
};
// A RegisterState represents the current state of registers used
// by the sampling profiler API.
struct RegisterState {
RegisterState() : pc(nullptr), sp(nullptr), fp(nullptr) {}
void* pc; // Instruction pointer.
void* sp; // Stack pointer.
void* fp; // Frame pointer.
};
// The output structure filled up by GetStackSample API function.
struct SampleInfo {
size_t frames_count; // Number of frames collected.
StateTag vm_state; // Current VM state.
void* external_callback_entry; // External callback address if VM is
// executing an external callback.
};
/**
* A JSON Parser and Stringifier.
*/
class V8_EXPORT JSON {
public:
/**
* Tries to parse the string |json_string| and returns it as value if
* successful.
*
* \param json_string The string to parse.
* \return The corresponding value if successfully parsed.
*/
static V8_DEPRECATE_SOON("Use the maybe version taking context",
MaybeLocal<Value> Parse(Isolate* isolate,
Local<String> json_string));
static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse(
Local<Context> context, Local<String> json_string);
/**
* Tries to stringify the JSON-serializable object |json_object| and returns
* it as string if successful.
*
* \param json_object The JSON-serializable object to stringify.
* \return The corresponding string if successfully stringified.
*/
static V8_WARN_UNUSED_RESULT MaybeLocal<String> Stringify(
Local<Context> context, Local<Value> json_object,
Local<String> gap = Local<String>());
};
/**
* Value serialization compatible with the HTML structured clone algorithm.
* The format is backward-compatible (i.e. safe to store to disk).
*
* WARNING: This API is under development, and changes (including incompatible
* changes to the API or wire format) may occur without notice until this
* warning is removed.
*/
class V8_EXPORT ValueSerializer {
public:
class V8_EXPORT Delegate {
public:
virtual ~Delegate() {}
/**
* Handles the case where a DataCloneError would be thrown in the structured
* clone spec. Other V8 embedders may throw some other appropriate exception
* type.
*/
virtual void ThrowDataCloneError(Local<String> message) = 0;
/**
* The embedder overrides this method to write some kind of host object, if
* possible. If not, a suitable exception should be thrown and
* Nothing<bool>() returned.
*/
virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object);
/**
* Called when the ValueSerializer is going to serialize a
* SharedArrayBuffer object. The embedder must return an ID for the
* object, using the same ID if this SharedArrayBuffer has already been
* serialized in this buffer. When deserializing, this ID will be passed to
* ValueDeserializer::GetSharedArrayBufferFromId as |clone_id|.
*
* If the object cannot be serialized, an
* exception should be thrown and Nothing<uint32_t>() returned.
*/
virtual Maybe<uint32_t> GetSharedArrayBufferId(
Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer);
virtual Maybe<uint32_t> GetWasmModuleTransferId(
Isolate* isolate, Local<WasmCompiledModule> module);
/**
* Allocates memory for the buffer of at least the size provided. The actual
* size (which may be greater or equal) is written to |actual_size|. If no
* buffer has been allocated yet, nullptr will be provided.
*
* If the memory cannot be allocated, nullptr should be returned.
* |actual_size| will be ignored. It is assumed that |old_buffer| is still
* valid in this case and has not been modified.
*
* The default implementation uses the stdlib's `realloc()` function.
*/
virtual void* ReallocateBufferMemory(void* old_buffer, size_t size,
size_t* actual_size);
/**
* Frees a buffer allocated with |ReallocateBufferMemory|.
*
* The default implementation uses the stdlib's `free()` function.
*/
virtual void FreeBufferMemory(void* buffer);
};
explicit ValueSerializer(Isolate* isolate);
ValueSerializer(Isolate* isolate, Delegate* delegate);
~ValueSerializer();
/**
* Writes out a header, which includes the format version.
*/
void WriteHeader();
/**
* Serializes a JavaScript value into the buffer.
*/
V8_WARN_UNUSED_RESULT Maybe<bool> WriteValue(Local<Context> context,
Local<Value> value);
/**
* Returns the stored data. This serializer should not be used once the buffer
* is released. The contents are undefined if a previous write has failed.
*/
V8_DEPRECATE_SOON("Use Release()", std::vector<uint8_t> ReleaseBuffer());
/**
* Returns the stored data (allocated using the delegate's
* ReallocateBufferMemory) and its size. This serializer should not be used
* once the buffer is released. The contents are undefined if a previous write
* has failed. Ownership of the buffer is transferred to the caller.
*/
V8_WARN_UNUSED_RESULT std::pair<uint8_t*, size_t> Release();
/**
* Marks an ArrayBuffer as havings its contents transferred out of band.
* Pass the corresponding ArrayBuffer in the deserializing context to
* ValueDeserializer::TransferArrayBuffer.
*/
void TransferArrayBuffer(uint32_t transfer_id,
Local<ArrayBuffer> array_buffer);
/**
* Similar to TransferArrayBuffer, but for SharedArrayBuffer.
*/
V8_DEPRECATE_SOON("Use Delegate::GetSharedArrayBufferId",
void TransferSharedArrayBuffer(
uint32_t transfer_id,
Local<SharedArrayBuffer> shared_array_buffer));
/**
* Indicate whether to treat ArrayBufferView objects as host objects,
* i.e. pass them to Delegate::WriteHostObject. This should not be
* called when no Delegate was passed.
*
* The default is not to treat ArrayBufferViews as host objects.
*/
void SetTreatArrayBufferViewsAsHostObjects(bool mode);
/**
* Write raw data in various common formats to the buffer.
* Note that integer types are written in base-128 varint format, not with a
* binary copy. For use during an override of Delegate::WriteHostObject.
*/
void WriteUint32(uint32_t value);
void WriteUint64(uint64_t value);
void WriteDouble(double value);
void WriteRawBytes(const void* source, size_t length);
private:
ValueSerializer(const ValueSerializer&) = delete;
void operator=(const ValueSerializer&) = delete;
struct PrivateData;
PrivateData* private_;
};
/**
* Deserializes values from data written with ValueSerializer, or a compatible
* implementation.
*
* WARNING: This API is under development, and changes (including incompatible
* changes to the API or wire format) may occur without notice until this
* warning is removed.
*/
class V8_EXPORT ValueDeserializer {
public:
class V8_EXPORT Delegate {
public:
virtual ~Delegate() {}
/**
* The embedder overrides this method to read some kind of host object, if
* possible. If not, a suitable exception should be thrown and
* MaybeLocal<Object>() returned.
*/
virtual MaybeLocal<Object> ReadHostObject(Isolate* isolate);
/**
* Get a WasmCompiledModule given a transfer_id previously provided
* by ValueSerializer::GetWasmModuleTransferId
*/
virtual MaybeLocal<WasmCompiledModule> GetWasmModuleFromId(
Isolate* isolate, uint32_t transfer_id);
/**
* Get a SharedArrayBuffer given a clone_id previously provided
* by ValueSerializer::GetSharedArrayBufferId
*/
virtual MaybeLocal<SharedArrayBuffer> GetSharedArrayBufferFromId(
Isolate* isolate, uint32_t clone_id);
};
ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size);
ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size,
Delegate* delegate);
~ValueDeserializer();
/**
* Reads and validates a header (including the format version).
* May, for example, reject an invalid or unsupported wire format.
*/
V8_WARN_UNUSED_RESULT Maybe<bool> ReadHeader(Local<Context> context);
/**
* Deserializes a JavaScript value from the buffer.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Value> ReadValue(Local<Context> context);
/**
* Accepts the array buffer corresponding to the one passed previously to
* ValueSerializer::TransferArrayBuffer.
*/
void TransferArrayBuffer(uint32_t transfer_id,
Local<ArrayBuffer> array_buffer);
/**
* Similar to TransferArrayBuffer, but for SharedArrayBuffer.
* The id is not necessarily in the same namespace as unshared ArrayBuffer
* objects.
*/
void TransferSharedArrayBuffer(uint32_t id,
Local<SharedArrayBuffer> shared_array_buffer);
/**
* Must be called before ReadHeader to enable support for reading the legacy
* wire format (i.e., which predates this being shipped).
*
* Don't use this unless you need to read data written by previous versions of
* blink::ScriptValueSerializer.
*/
void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format);
/**
* Expect inline wasm in the data stream (rather than in-memory transfer)
*/
void SetExpectInlineWasm(bool allow_inline_wasm);
/**
* Reads the underlying wire format version. Likely mostly to be useful to
* legacy code reading old wire format versions. Must be called after
* ReadHeader.
*/
uint32_t GetWireFormatVersion() const;
/**
* Reads raw data in various common formats to the buffer.
* Note that integer types are read in base-128 varint format, not with a
* binary copy. For use during an override of Delegate::ReadHostObject.
*/
V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value);
V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value);
V8_WARN_UNUSED_RESULT bool ReadDouble(double* value);
V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data);
private:
ValueDeserializer(const ValueDeserializer&) = delete;
void operator=(const ValueDeserializer&) = delete;
struct PrivateData;
PrivateData* private_;
};
// --- Value ---
/**
* The superclass of all JavaScript values and objects.
*/
class V8_EXPORT Value : public Data {
public:
/**
* Returns true if this value is the undefined value. See ECMA-262
* 4.3.10.
*/
V8_INLINE bool IsUndefined() const;
/**
* Returns true if this value is the null value. See ECMA-262
* 4.3.11.
*/
V8_INLINE bool IsNull() const;
/**
* Returns true if this value is either the null or the undefined value.
* See ECMA-262
* 4.3.11. and 4.3.12
*/
V8_INLINE bool IsNullOrUndefined() const;
/**
* Returns true if this value is true.
*/
bool IsTrue() const;
/**
* Returns true if this value is false.
*/
bool IsFalse() const;
/**
* Returns true if this value is a symbol or a string.
*/
bool IsName() const;
/**
* Returns true if this value is an instance of the String type.
* See ECMA-262 8.4.
*/
V8_INLINE bool IsString() const;
/**
* Returns true if this value is a symbol.
*/
bool IsSymbol() const;
/**
* Returns true if this value is a function.
*/
bool IsFunction() const;
/**
* Returns true if this value is an array. Note that it will return false for
* an Proxy for an array.
*/
bool IsArray() const;
/**
* Returns true if this value is an object.
*/
bool IsObject() const;
/**
* Returns true if this value is a bigint.
*/
bool IsBigInt() const;
/**
* Returns true if this value is boolean.
*/
bool IsBoolean() const;
/**
* Returns true if this value is a number.
*/
bool IsNumber() const;
/**
* Returns true if this value is external.
*/
bool IsExternal() const;
/**
* Returns true if this value is a 32-bit signed integer.
*/
bool IsInt32() const;
/**
* Returns true if this value is a 32-bit unsigned integer.
*/
bool IsUint32() const;
/**
* Returns true if this value is a Date.
*/
bool IsDate() const;
/**
* Returns true if this value is an Arguments object.
*/
bool IsArgumentsObject() const;
/**
* Returns true if this value is a BigInt object.
*/
bool IsBigIntObject() const;
/**
* Returns true if this value is a Boolean object.
*/
bool IsBooleanObject() const;
/**
* Returns true if this value is a Number object.
*/
bool IsNumberObject() const;
/**
* Returns true if this value is a String object.
*/
bool IsStringObject() const;
/**
* Returns true if this value is a Symbol object.
*/
bool IsSymbolObject() const;
/**
* Returns true if this value is a NativeError.
*/
bool IsNativeError() const;
/**
* Returns true if this value is a RegExp.
*/
bool IsRegExp() const;
/**
* Returns true if this value is an async function.
*/
bool IsAsyncFunction() const;
/**
* Returns true if this value is a Generator function.
*/
bool IsGeneratorFunction() const;
/**
* Returns true if this value is a Generator object (iterator).
*/
bool IsGeneratorObject() const;
/**
* Returns true if this value is a Promise.
*/
bool IsPromise() const;
/**
* Returns true if this value is a Map.
*/
bool IsMap() const;
/**
* Returns true if this value is a Set.
*/
bool IsSet() const;
/**
* Returns true if this value is a Map Iterator.
*/
bool IsMapIterator() const;
/**
* Returns true if this value is a Set Iterator.
*/
bool IsSetIterator() const;
/**
* Returns true if this value is a WeakMap.
*/
bool IsWeakMap() const;
/**
* Returns true if this value is a WeakSet.
*/
bool IsWeakSet() const;
/**
* Returns true if this value is an ArrayBuffer.
*/
bool IsArrayBuffer() const;
/**
* Returns true if this value is an ArrayBufferView.
*/
bool IsArrayBufferView() const;
/**
* Returns true if this value is one of TypedArrays.
*/
bool IsTypedArray() const;
/**
* Returns true if this value is an Uint8Array.
*/
bool IsUint8Array() const;
/**
* Returns true if this value is an Uint8ClampedArray.
*/
bool IsUint8ClampedArray() const;
/**
* Returns true if this value is an Int8Array.
*/
bool IsInt8Array() const;
/**
* Returns true if this value is an Uint16Array.
*/
bool IsUint16Array() const;
/**
* Returns true if this value is an Int16Array.
*/
bool IsInt16Array() const;
/**
* Returns true if this value is an Uint32Array.
*/
bool IsUint32Array() const;
/**
* Returns true if this value is an Int32Array.
*/
bool IsInt32Array() const;
/**
* Returns true if this value is a Float32Array.
*/
bool IsFloat32Array() const;
/**
* Returns true if this value is a Float64Array.
*/
bool IsFloat64Array() const;
/**
* Returns true if this value is a BigInt64Array.
*/
bool IsBigInt64Array() const;
/**
* Returns true if this value is a BigUint64Array.
*/
bool IsBigUint64Array() const;
/**
* Returns true if this value is a DataView.
*/
bool IsDataView() const;
/**
* Returns true if this value is a SharedArrayBuffer.
* This is an experimental feature.
*/
bool IsSharedArrayBuffer() const;
/**
* Returns true if this value is a JavaScript Proxy.
*/
bool IsProxy() const;
bool IsWebAssemblyCompiledModule() const;
/**
* Returns true if the value is a Module Namespace Object.
*/
bool IsModuleNamespaceObject() const;
V8_WARN_UNUSED_RESULT MaybeLocal<BigInt> ToBigInt(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT MaybeLocal<String> ToDetailString(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT MaybeLocal<Object> ToObject(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT MaybeLocal<Integer> ToInteger(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToUint32(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
V8_DEPRECATED("Use maybe version",
Local<Boolean> ToBoolean(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<Number> ToNumber(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<String> ToString(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<Object> ToObject(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<Integer> ToInteger(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<Int32> ToInt32(Isolate* isolate) const);
inline V8_DEPRECATED("Use maybe version",
Local<Boolean> ToBoolean() const);
inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const);
inline V8_DEPRECATED("Use maybe version", Local<Object> ToObject() const);
inline V8_DEPRECATED("Use maybe version",
Local<Integer> ToInteger() const);
/**
* Attempts to convert a string to an array index.
* Returns an empty handle if the conversion fails.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToArrayIndex(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const;
V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const);
V8_DEPRECATED("Use maybe version", double NumberValue() const);
V8_DEPRECATED("Use maybe version", int64_t IntegerValue() const);
V8_DEPRECATED("Use maybe version", uint32_t Uint32Value() const);
V8_DEPRECATED("Use maybe version", int32_t Int32Value() const);
/** JS == */
V8_DEPRECATED("Use maybe version", bool Equals(Local<Value> that) const);
V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
Local<Value> that) const;
bool StrictEquals(Local<Value> that) const;
bool SameValue(Local<Value> that) const;
template <class T> V8_INLINE static Value* Cast(T* value);
Local<String> TypeOf(Isolate*);
Maybe<bool> InstanceOf(Local<Context> context, Local<Object> object);
private:
V8_INLINE bool QuickIsUndefined() const;
V8_INLINE bool QuickIsNull() const;
V8_INLINE bool QuickIsNullOrUndefined() const;
V8_INLINE bool QuickIsString() const;
bool FullIsUndefined() const;
bool FullIsNull() const;
bool FullIsString() const;
};
/**
* The superclass of primitive values. See ECMA-262 4.3.2.
*/
class V8_EXPORT Primitive : public Value { };
/**
* A primitive boolean value (ECMA-262, 4.3.14). Either the true
* or false value.
*/
class V8_EXPORT Boolean : public Primitive {
public:
bool Value() const;
V8_INLINE static Boolean* Cast(v8::Value* obj);
V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
private:
static void CheckCast(v8::Value* obj);
};
/**
* A superclass for symbols and strings.
*/
class V8_EXPORT Name : public Primitive {
public:
/**
* Returns the identity hash for this object. The current implementation
* uses an inline property on the object to store the identity hash.
*
* The return value will never be 0. Also, it is not guaranteed to be
* unique.
*/
int GetIdentityHash();
V8_INLINE static Name* Cast(Value* obj);
private:
static void CheckCast(Value* obj);
};
/**
* A flag describing different modes of string creation.
*
* Aside from performance implications there are no differences between the two
* creation modes.
*/
enum class NewStringType {
/**
* Create a new string, always allocating new storage memory.
*/
kNormal,
/**
* Acts as a hint that the string should be created in the
* old generation heap space and be deduplicated if an identical string
* already exists.
*/
kInternalized
};
/**
* A JavaScript string value (ECMA-262, 4.3.17).
*/
class V8_EXPORT String : public Name {
public:
static constexpr int kMaxLength =
sizeof(void*) == 4 ? (1 << 28) - 16 : (1 << 30) - 1 - 24;
enum Encoding {
UNKNOWN_ENCODING = 0x1,
TWO_BYTE_ENCODING = 0x0,
ONE_BYTE_ENCODING = 0x8
};
/**
* Returns the number of characters (UTF-16 code units) in this string.
*/
int Length() const;
/**
* Returns the number of bytes in the UTF-8 encoded
* representation of this string.
*/
V8_DEPRECATE_SOON("Use Isolate version instead", int Utf8Length() const);
int Utf8Length(Isolate* isolate) const;
/**
* Returns whether this string is known to contain only one byte data,
* i.e. ISO-8859-1 code points.
* Does not read the string.
* False negatives are possible.
*/
bool IsOneByte() const;
/**
* Returns whether this string contain only one byte data,
* i.e. ISO-8859-1 code points.
* Will read the entire string in some cases.
*/
bool ContainsOnlyOneByte() const;
/**
* Write the contents of the string to an external buffer.
* If no arguments are given, expects the buffer to be large
* enough to hold the entire string and NULL terminator. Copies
* the contents of the string and the NULL terminator into the
* buffer.
*
* WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
* before the end of the buffer.
*
* Copies up to length characters into the output buffer.
* Only null-terminates if there is enough space in the buffer.
*
* \param buffer The buffer into which the string will be copied.
* \param start The starting position within the string at which
* copying begins.
* \param length The number of characters to copy from the string. For
* WriteUtf8 the number of bytes in the buffer.
* \param nchars_ref The number of characters written, can be NULL.
* \param options Various options that might affect performance of this or
* subsequent operations.
* \return The number of characters copied to the buffer excluding the null
* terminator. For WriteUtf8: The number of bytes copied to the buffer
* including the null terminator (if written).
*/
enum WriteOptions {
NO_OPTIONS = 0,
HINT_MANY_WRITES_EXPECTED = 1,
NO_NULL_TERMINATION = 2,
PRESERVE_ONE_BYTE_NULL = 4,
// Used by WriteUtf8 to replace orphan surrogate code units with the
// unicode replacement character. Needs to be set to guarantee valid UTF-8
// output.
REPLACE_INVALID_UTF8 = 8
};
// 16-bit character codes.
int Write(Isolate* isolate, uint16_t* buffer, int start = 0, int length = -1,
int options = NO_OPTIONS) const;
V8_DEPRECATE_SOON("Use Isolate* version",
int Write(uint16_t* buffer, int start = 0, int length = -1,
int options = NO_OPTIONS) const);
// One byte characters.
int WriteOneByte(Isolate* isolate, uint8_t* buffer, int start = 0,
int length = -1, int options = NO_OPTIONS) const;
V8_DEPRECATE_SOON("Use Isolate* version",
int WriteOneByte(uint8_t* buffer, int start = 0,
int length = -1, int options = NO_OPTIONS)
const);
// UTF-8 encoded characters.
int WriteUtf8(Isolate* isolate, char* buffer, int length = -1,
int* nchars_ref = NULL, int options = NO_OPTIONS) const;
V8_DEPRECATE_SOON("Use Isolate* version",
int WriteUtf8(char* buffer, int length = -1,
int* nchars_ref = NULL,
int options = NO_OPTIONS) const);
/**
* A zero length string.
*/
V8_INLINE static Local<String> Empty(Isolate* isolate);
/**
* Returns true if the string is external
*/
bool IsExternal() const;
/**
* Returns true if the string is both external and one-byte.
*/
bool IsExternalOneByte() const;
class V8_EXPORT ExternalStringResourceBase { // NOLINT
public:
virtual ~ExternalStringResourceBase() {}
virtual bool IsCompressible() const { return false; }
protected:
ExternalStringResourceBase() {}
/**
* Internally V8 will call this Dispose method when the external string
* resource is no longer needed. The default implementation will use the
* delete operator. This method can be overridden in subclasses to
* control how allocated external string resources are disposed.
*/
virtual void Dispose() { delete this; }
// Disallow copying and assigning.
ExternalStringResourceBase(const ExternalStringResourceBase&) = delete;
void operator=(const ExternalStringResourceBase&) = delete;
private:
friend class internal::Heap;
friend class v8::String;
};
/**
* An ExternalStringResource is a wrapper around a two-byte string
* buffer that resides outside V8's heap. Implement an
* ExternalStringResource to manage the life cycle of the underlying
* buffer. Note that the string data must be immutable.
*/
class V8_EXPORT ExternalStringResource
: public ExternalStringResourceBase {
public:
/**
* Override the destructor to manage the life cycle of the underlying
* buffer.
*/
virtual ~ExternalStringResource() {}
/**
* The string data from the underlying buffer.
*/
virtual const uint16_t* data() const = 0;
/**
* The length of the string. That is, the number of two-byte characters.
*/
virtual size_t length() const = 0;
protected:
ExternalStringResource() {}
};
/**
* An ExternalOneByteStringResource is a wrapper around an one-byte
* string buffer that resides outside V8's heap. Implement an
* ExternalOneByteStringResource to manage the life cycle of the
* underlying buffer. Note that the string data must be immutable
* and that the data must be Latin-1 and not UTF-8, which would require
* special treatment internally in the engine and do not allow efficient
* indexing. Use String::New or convert to 16 bit data for non-Latin1.
*/
class V8_EXPORT ExternalOneByteStringResource
: public ExternalStringResourceBase {
public:
/**
* Override the destructor to manage the life cycle of the underlying
* buffer.
*/
virtual ~ExternalOneByteStringResource() {}
/** The string data from the underlying buffer.*/
virtual const char* data() const = 0;
/** The number of Latin-1 characters in the string.*/
virtual size_t length() const = 0;
protected:
ExternalOneByteStringResource() {}
};
/**
* If the string is an external string, return the ExternalStringResourceBase
* regardless of the encoding, otherwise return NULL. The encoding of the
* string is returned in encoding_out.
*/
V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
Encoding* encoding_out) const;
/**
* Get the ExternalStringResource for an external string. Returns
* NULL if IsExternal() doesn't return true.
*/
V8_INLINE ExternalStringResource* GetExternalStringResource() const;
/**
* Get the ExternalOneByteStringResource for an external one-byte string.
* Returns NULL if IsExternalOneByte() doesn't return true.
*/
const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
V8_INLINE static String* Cast(v8::Value* obj);
// TODO(dcarney): remove with deprecation of New functions.
enum NewStringType {
kNormalString = static_cast<int>(v8::NewStringType::kNormal),
kInternalizedString = static_cast<int>(v8::NewStringType::kInternalized)
};
/** Allocates a new string from UTF-8 data.*/
static V8_DEPRECATE_SOON(
"Use maybe version",
Local<String> NewFromUtf8(Isolate* isolate, const char* data,
NewStringType type = kNormalString,
int length = -1));
/** Allocates a new string from UTF-8 data. Only returns an empty value when
* length > kMaxLength. **/
static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
Isolate* isolate, const char* data, v8::NewStringType type,
int length = -1);
/** Allocates a new string from Latin-1 data. Only returns an empty value
* when length > kMaxLength. **/
static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
Isolate* isolate, const uint8_t* data, v8::NewStringType type,
int length = -1);
/** Allocates a new string from UTF-16 data.*/
static V8_DEPRECATE_SOON(
"Use maybe version",
Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
NewStringType type = kNormalString,
int length = -1));
/** Allocates a new string from UTF-16 data. Only returns an empty value when
* length > kMaxLength. **/
static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
Isolate* isolate, const uint16_t* data, v8::NewStringType type,
int length = -1);
/**
* Creates a new string by concatenating the left and the right strings
* passed in as parameters.
*/
static Local<String> Concat(Isolate* isolate, Local<String> left,
Local<String> right);
static V8_DEPRECATE_SOON("Use Isolate* version",
Local<String> Concat(Local<String> left,
Local<String> right));
/**
* Creates a new external string using the data defined in the given
* resource. When the external string is no longer live on V8's heap the
* resource will be disposed by calling its Dispose method. The caller of
* this function should not otherwise delete or modify the resource. Neither
* should the underlying buffer be deallocated or modified except through the
* destructor of the external string resource.
*/
static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
Isolate* isolate, ExternalStringResource* resource);
/**
* Associate an external string resource with this string by transforming it
* in place so that existing references to this string in the JavaScript heap
* will use the external string resource. The external string resource's
* character contents need to be equivalent to this string.
* Returns true if the string has been changed to be an external string.
* The string is not modified if the operation fails. See NewExternal for
* information on the lifetime of the resource.
*/
bool MakeExternal(ExternalStringResource* resource);
/**
* Creates a new external string using the one-byte data defined in the given
* resource. When the external string is no longer live on V8's heap the
* resource will be disposed by calling its Dispose method. The caller of
* this function should not otherwise delete or modify the resource. Neither
* should the underlying buffer be deallocated or modified except through the
* destructor of the external string resource.
*/
static V8_DEPRECATE_SOON(
"Use maybe version",
Local<String> NewExternal(Isolate* isolate,
ExternalOneByteStringResource* resource));
static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
Isolate* isolate, ExternalOneByteStringResource* resource);
/**
* Associate an external string resource with this string by transforming it
* in place so that existing references to this string in the JavaScript heap
* will use the external string resource. The external string resource's
* character contents need to be equivalent to this string.
* Returns true if the string has been changed to be an external string.
* The string is not modified if the operation fails. See NewExternal for
* information on the lifetime of the resource.
*/
bool MakeExternal(ExternalOneByteStringResource* resource);
/**
* Returns true if this string can be made external.
*/
bool CanMakeExternal();
/**
* Converts an object to a UTF-8-encoded character array. Useful if
* you want to print the object. If conversion to a string fails
* (e.g. due to an exception in the toString() method of the object)
* then the length() method returns 0 and the * operator returns
* NULL.
*/
class V8_EXPORT Utf8Value {
public:
V8_DEPRECATED("Use Isolate version",
explicit Utf8Value(Local<v8::Value> obj));
Utf8Value(Isolate* isolate, Local<v8::Value> obj);
~Utf8Value();
char* operator*() { return str_; }
const char* operator*() const { return str_; }
int length() const { return length_; }
// Disallow copying and assigning.
Utf8Value(const Utf8Value&) = delete;
void operator=(const Utf8Value&) = delete;
private:
char* str_;
int length_;
};
/**
* Converts an object to a two-byte (UTF-16-encoded) string.
* If conversion to a string fails (eg. due to an exception in the toString()
* method of the object) then the length() method returns 0 and the * operator
* returns NULL.
*/
class V8_EXPORT Value {
public:
V8_DEPRECATED("Use Isolate version", explicit Value(Local<v8::Value> obj));
Value(Isolate* isolate, Local<v8::Value> obj);
~Value();
uint16_t* operator*() { return str_; }
const uint16_t* operator*() const { return str_; }
int length() const { return length_; }
// Disallow copying and assigning.
Value(const Value&) = delete;
void operator=(const Value&) = delete;
private:
uint16_t* str_;
int length_;
};
private:
void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
Encoding encoding) const;
void VerifyExternalStringResource(ExternalStringResource* val) const;
static void CheckCast(v8::Value* obj);
};
/**
* A JavaScript symbol (ECMA-262 edition 6)
*/
class V8_EXPORT Symbol : public Name {
public:
/**
* Returns the print name string of the symbol, or undefined if none.
*/
Local<Value> Name() const;
/**
* Create a symbol. If name is not empty, it will be used as the description.
*/
static Local<Symbol> New(Isolate* isolate,
Local<String> name = Local<String>());
/**
* Access global symbol registry.
* Note that symbols created this way are never collected, so
* they should only be used for statically fixed properties.
* Also, there is only one global name space for the names used as keys.
* To minimize the potential for clashes, use qualified names as keys.
*/
static Local<Symbol> For(Isolate *isolate, Local<String> name);
/**
* Retrieve a global symbol. Similar to |For|, but using a separate
* registry that is not accessible by (and cannot clash with) JavaScript code.
*/
static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
// Well-known symbols
static Local<Symbol> GetHasInstance(Isolate* isolate);
static Local<Symbol> GetIsConcatSpreadable(Isolate* isolate);
static Local<Symbol> GetIterator(Isolate* isolate);
static Local<Symbol> GetMatch(Isolate* isolate);
static Local<Symbol> GetReplace(Isolate* isolate);
static Local<Symbol> GetSearch(Isolate* isolate);
static Local<Symbol> GetSplit(Isolate* isolate);
static Local<Symbol> GetToPrimitive(Isolate* isolate);
static Local<Symbol> GetToStringTag(Isolate* isolate);
static Local<Symbol> GetUnscopables(Isolate* isolate);
V8_INLINE static Symbol* Cast(Value* obj);
private:
Symbol();
static void CheckCast(Value* obj);
};
/**
* A private symbol
*
* This is an experimental feature. Use at your own risk.
*/
class V8_EXPORT Private : public Data {
public:
/**
* Returns the print name string of the private symbol, or undefined if none.
*/
Local<Value> Name() const;
/**
* Create a private symbol. If name is not empty, it will be the description.
*/
static Local<Private> New(Isolate* isolate,
Local<String> name = Local<String>());
/**
* Retrieve a global private symbol. If a symbol with this name has not
* been retrieved in the same isolate before, it is created.
* Note that private symbols created this way are never collected, so
* they should only be used for statically fixed properties.
* Also, there is only one global name space for the names used as keys.
* To minimize the potential for clashes, use qualified names as keys,
* e.g., "Class#property".
*/
static Local<Private> ForApi(Isolate* isolate, Local<String> name);
V8_INLINE static Private* Cast(Data* data);
private:
Private();
static void CheckCast(Data* that);
};
/**
* A JavaScript number value (ECMA-262, 4.3.20)
*/
class V8_EXPORT Number : public Primitive {
public:
double Value() const;
static Local<Number> New(Isolate* isolate, double value);
V8_INLINE static Number* Cast(v8::Value* obj);
private:
Number();
static void CheckCast(v8::Value* obj);
};
/**
* A JavaScript value representing a signed integer.
*/
class V8_EXPORT Integer : public Number {
public:
static Local<Integer> New(Isolate* isolate, int32_t value);
static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
int64_t Value() const;
V8_INLINE static Integer* Cast(v8::Value* obj);
private:
Integer();
static void CheckCast(v8::Value* obj);
};
/**
* A JavaScript value representing a 32-bit signed integer.
*/
class V8_EXPORT Int32 : public Integer {
public:
int32_t Value() const;
V8_INLINE static Int32* Cast(v8::Value* obj);
private:
Int32();
static void CheckCast(v8::Value* obj);
};
/**
* A JavaScript value representing a 32-bit unsigned integer.
*/
class V8_EXPORT Uint32 : public Integer {
public:
uint32_t Value() const;
V8_INLINE static Uint32* Cast(v8::Value* obj);
private:
Uint32();
static void CheckCast(v8::Value* obj);
};
/**
* A JavaScript BigInt value (https://tc39.github.io/proposal-bigint)
*/
class V8_EXPORT BigInt : public Primitive {
public:
static Local<BigInt> New(Isolate* isolate, int64_t value);
static Local<BigInt> NewFromUnsigned(Isolate* isolate, uint64_t value);
/**
* Creates a new BigInt object using a specified sign bit and a
* specified list of digits/words.
* The resulting number is calculated as:
*
* (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
*/
static MaybeLocal<BigInt> NewFromWords(Local<Context> context, int sign_bit,
int word_count, const uint64_t* words);
/**
* Returns the value of this BigInt as an unsigned 64-bit integer.
* If `lossless` is provided, it will reflect whether the return value was
* truncated or wrapped around. In particular, it is set to `false` if this
* BigInt is negative.
*/
uint64_t Uint64Value(bool* lossless = nullptr) const;
/**
* Returns the value of this BigInt as a signed 64-bit integer.
* If `lossless` is provided, it will reflect whether this BigInt was
* truncated or not.
*/
int64_t Int64Value(bool* lossless = nullptr) const;
/**
* Returns the number of 64-bit words needed to store the result of
* ToWordsArray().
*/
int WordCount() const;
/**
* Writes the contents of this BigInt to a specified memory location.
* `sign_bit` must be provided and will be set to 1 if this BigInt is
* negative.
* `*word_count` has to be initialized to the length of the `words` array.
* Upon return, it will be set to the actual number of words that would
* be needed to store this BigInt (i.e. the return value of `WordCount()`).
*/
void ToWordsArray(int* sign_bit, int* word_count, uint64_t* words) const;
V8_INLINE static BigInt* Cast(v8::Value* obj);
private:
BigInt();
static void CheckCast(v8::Value* obj);
};
/**
* PropertyAttribute.
*/
enum PropertyAttribute {
/** None. **/
None = 0,
/** ReadOnly, i.e., not writable. **/
ReadOnly = 1 << 0,
/** DontEnum, i.e., not enumerable. **/
DontEnum = 1 << 1,
/** DontDelete, i.e., not configurable. **/
DontDelete = 1 << 2
};
/**
* Accessor[Getter|Setter] are used as callback functions when
* setting|getting a particular property. See Object and ObjectTemplate's
* method SetAccessor.
*/
typedef void (*AccessorGetterCallback)(
Local<String> property,
const PropertyCallbackInfo<Value>& info);
typedef void (*AccessorNameGetterCallback)(
Local<Name> property,
const PropertyCallbackInfo<Value>& info);
typedef void (*AccessorSetterCallback)(
Local<String> property,
Local<Value> value,
const PropertyCallbackInfo<void>& info);
typedef void (*AccessorNameSetterCallback)(
Local<Name> property,
Local<Value> value,
const PropertyCallbackInfo<void>& info);
/**
* Access control specifications.
*
* Some accessors should be accessible across contexts. These
* accessors have an explicit access control parameter which specifies
* the kind of cross-context access that should be allowed.
*
* TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
*/
enum AccessControl {
DEFAULT = 0,
ALL_CAN_READ = 1,
ALL_CAN_WRITE = 1 << 1,
PROHIBITS_OVERWRITING = 1 << 2
};
/**
* Property filter bits. They can be or'ed to build a composite filter.
*/
enum PropertyFilter {
ALL_PROPERTIES = 0,
ONLY_WRITABLE = 1,
ONLY_ENUMERABLE = 2,
ONLY_CONFIGURABLE = 4,
SKIP_STRINGS = 8,
SKIP_SYMBOLS = 16
};
/**
* Options for marking whether callbacks may trigger JS-observable side effects.
* Side-effect-free callbacks are whitelisted during debug evaluation with
* throwOnSideEffect. It applies when calling a Function, FunctionTemplate,
* or an Accessor's getter callback. For Interceptors, please see
* PropertyHandlerFlags's kHasNoSideEffect.
*/
enum class SideEffectType { kHasSideEffect, kHasNoSideEffect };
/**
* Keys/Properties filter enums:
*
* KeyCollectionMode limits the range of collected properties. kOwnOnly limits
* the collected properties to the given Object only. kIncludesPrototypes will
* include all keys of the objects's prototype chain as well.
*/
enum class KeyCollectionMode { kOwnOnly, kIncludePrototypes };
/**
* kIncludesIndices allows for integer indices to be collected, while
* kSkipIndices will exclude integer indices from being collected.
*/
enum class IndexFilter { kIncludeIndices, kSkipIndices };
/**
* kConvertToString will convert integer indices to strings.
* kKeepNumbers will return numbers for integer indices.
*/
enum class KeyConversionMode { kConvertToString, kKeepNumbers };
/**
* Integrity level for objects.
*/
enum class IntegrityLevel { kFrozen, kSealed };
/**
* A JavaScript object (ECMA-262, 4.3.3)
*/
class V8_EXPORT Object : public Value {
public:
V8_DEPRECATE_SOON("Use maybe version",
bool Set(Local<Value> key, Local<Value> value));
V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
Local<Value> key, Local<Value> value);
V8_DEPRECATE_SOON("Use maybe version",
bool Set(uint32_t index, Local<Value> value));
V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
Local<Value> value);
// Implements CreateDataProperty (ECMA-262, 7.3.4).
//
// Defines a configurable, writable, enumerable property with the given value
// on the object unless the property already exists and is not configurable
// or the object is not extensible.
//
// Returns true on success.
V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
Local<Name> key,
Local<Value> value);
V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
uint32_t index,
Local<Value> value);
// Implements DefineOwnProperty.
//
// In general, CreateDataProperty will be faster, however, does not allow
// for specifying attributes.
//
// Returns true on success.
V8_WARN_UNUSED_RESULT Maybe<bool> DefineOwnProperty(
Local<Context> context, Local<Name> key, Local<Value> value,
PropertyAttribute attributes = None);
// Implements Object.DefineProperty(O, P, Attributes), see Ecma-262 19.1.2.4.
//
// The defineProperty function is used to add an own property or
// update the attributes of an existing own property of an object.
//
// Both data and accessor descriptors can be used.
//
// In general, CreateDataProperty is faster, however, does not allow
// for specifying attributes or an accessor descriptor.
//
// The PropertyDescriptor can change when redefining a property.
//
// Returns true on success.
V8_WARN_UNUSED_RESULT Maybe<bool> DefineProperty(
Local<Context> context, Local<Name> key, PropertyDescriptor& descriptor);
V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
Local<Value> key);
V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
uint32_t index);
/**
* Gets the property attributes of a property which can be None or
* any combination of ReadOnly, DontEnum and DontDelete. Returns
* None when the property doesn't exist.
*/
V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetPropertyAttributes(
Local<Context> context, Local<Value> key);
/**
* Returns Object.getOwnPropertyDescriptor as per ES2016 section 19.1.2.6.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetOwnPropertyDescriptor(
Local<Context> context, Local<Name> key);
V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
/**
* Object::Has() calls the abstract operation HasProperty(O, P) described
* in ECMA-262, 7.3.10. Has() returns
* true, if the object has the property, either own or on the prototype chain.
* Interceptors, i.e., PropertyQueryCallbacks, are called if present.
*
* Has() has the same side effects as JavaScript's `variable in object`.
* For example, calling Has() on a revoked proxy will throw an exception.
*
* \note Has() converts the key to a name, which possibly calls back into
* JavaScript.
*
* See also v8::Object::HasOwnProperty() and
* v8::Object::HasRealNamedProperty().
*/
V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
Local<Value> key);
V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
Local<Value> key);
V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
uint32_t index);
/**
* Note: SideEffectType affects the getter only, not the setter.
*/
V8_WARN_UNUSED_RESULT Maybe<bool> SetAccessor(
Local<Context> context, Local<Name> name,
AccessorNameGetterCallback getter, AccessorNameSetterCallback setter = 0,
MaybeLocal<Value> data = MaybeLocal<Value>(),
AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
void SetAccessorProperty(Local<Name> name, Local<Function> getter,
Local<Function> setter = Local<Function>(),
PropertyAttribute attribute = None,
AccessControl settings = DEFAULT);
/**
* Sets a native data property like Template::SetNativeDataProperty, but
* this method sets on this object directly.
*/
V8_WARN_UNUSED_RESULT Maybe<bool> SetNativeDataProperty(
Local<Context> context, Local<Name> name,
AccessorNameGetterCallback getter,
AccessorNameSetterCallback setter = nullptr,
Local<Value> data = Local<Value>(), PropertyAttribute attributes = None,
SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
/**
* Attempts to create a property with the given name which behaves like a data
* property, except that the provided getter is invoked (and provided with the
* data value) to supply its value the first time it is read. After the
* property is accessed once, it is replaced with an ordinary data property.
*
* Analogous to Template::SetLazyDataProperty.
*/
V8_WARN_UNUSED_RESULT Maybe<bool> SetLazyDataProperty(
Local<Context> context, Local<Name> name,
AccessorNameGetterCallback getter, Local<Value> data = Local<Value>(),
PropertyAttribute attributes = None,
SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
/**
* Functionality for private properties.
* This is an experimental feature, use at your own risk.
* Note: Private properties are not inherited. Do not rely on this, since it
* may change.
*/
Maybe<bool> HasPrivate(Local<Context> context, Local<Private> key);
Maybe<bool> SetPrivate(Local<Context> context, Local<Private> key,
Local<Value> value);
Maybe<bool> DeletePrivate(Local<Context> context, Local<Private> key);
MaybeLocal<Value> GetPrivate(Local<Context> context, Local<Private> key);
/**
* Returns an array containing the names of the enumerable properties
* of this object, including properties from prototype objects. The
* array returned by this method contains the same values as would
* be enumerated by a for-in statement over this object.
*/
V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
Local<Context> context);
V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
Local<Context> context, KeyCollectionMode mode,
PropertyFilter property_filter, IndexFilter index_filter,
KeyConversionMode key_conversion = KeyConversionMode::kKeepNumbers);
/**
* This function has the same functionality as GetPropertyNames but
* the returned array doesn't contain the names of properties from
* prototype objects.
*/
V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
Local<Context> context);
/**
* Returns an array containing the names of the filtered properties
* of this object, including properties from prototype objects. The
* array returned by this method contains the same values as would
* be enumerated by a for-in statement over this object.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
Local<Context> context, PropertyFilter filter,
KeyConversionMode key_conversion = KeyConversionMode::kKeepNumbers);
/**
* Get the prototype object. This does not skip objects marked to
* be skipped by __proto__ and it does not consult the security
* handler.
*/
Local<Value> GetPrototype();
/**
* Set the prototype object. This does not skip objects marked to
* be skipped by __proto__ and it does not consult the security
* handler.
*/
V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
Local<Value> prototype);
/**
* Finds an instance of the given function template in the prototype
* chain.
*/
Local<Object> FindInstanceInPrototypeChain(Local<FunctionTemplate> tmpl);
/**
* Call builtin Object.prototype.toString on this object.
* This is different from Value::ToString() that may call
* user-defined toString function. This one does not.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<String> ObjectProtoToString(
Local<Context> context);
/**
* Returns the name of the function invoked as a constructor for this object.
*/
Local<String> GetConstructorName();
/**
* Sets the integrity level of the object.
*/
Maybe<bool> SetIntegrityLevel(Local<Context> context, IntegrityLevel level);
/** Gets the number of internal fields for this Object. */
int InternalFieldCount();
/** Same as above, but works for Persistents */
V8_INLINE static int InternalFieldCount(
const PersistentBase<Object>& object) {
return object.val_->InternalFieldCount();
}
/** Gets the value from an internal field. */
V8_INLINE Local<Value> GetInternalField(int index);
/** Sets the value in an internal field. */
void SetInternalField(int index, Local<Value> value);
/**
* Gets a 2-byte-aligned native pointer from an internal field. This field
* must have been set by SetAlignedPointerInInternalField, everything else
* leads to undefined behavior.
*/
V8_INLINE void* GetAlignedPointerFromInternalField(int index);
/** Same as above, but works for Persistents */
V8_INLINE static void* GetAlignedPointerFromInternalField(
const PersistentBase<Object>& object, int index) {
return object.val_->GetAlignedPointerFromInternalField(index);
}
/**
* Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
* a field, GetAlignedPointerFromInternalField must be used, everything else
* leads to undefined behavior.
*/
void SetAlignedPointerInInternalField(int index, void* value);
void SetAlignedPointerInInternalFields(int argc, int indices[],
void* values[]);
/**
* HasOwnProperty() is like JavaScript's Object.prototype.hasOwnProperty().
*
* See also v8::Object::Has() and v8::Object::HasRealNamedProperty().
*/
V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
Local<Name> key);
V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
uint32_t index);
V8_DEPRECATE_SOON("Use maybe version",
bool HasRealNamedProperty(Local<String> key));
/**
* Use HasRealNamedProperty() if you want to check if an object has an own
* property without causing side effects, i.e., without calling interceptors.
*
* This function is similar to v8::Object::HasOwnProperty(), but it does not
* call interceptors.
*
* \note Consider using non-masking interceptors, i.e., the interceptors are
* not called if the receiver has the real named property. See
* `v8::PropertyHandlerFlags::kNonMasking`.
*
* See also v8::Object::Has().
*/
V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
Local<Name> key);
V8_DEPRECATE_SOON("Use maybe version",
bool HasRealIndexedProperty(uint32_t index));
V8_WARN_UNUSED_RESULT Maybe<bool> HasRealIndexedProperty(
Local<Context> context, uint32_t index);
V8_DEPRECATE_SOON("Use maybe version",
bool HasRealNamedCallbackProperty(Local<String> key));
V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedCallbackProperty(
Local<Context> context, Local<Name> key);
/**
* If result.IsEmpty() no real property was located in the prototype chain.
* This means interceptors in the prototype chain are not called.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain(
Local<Context> context, Local<Name> key);
/**
* Gets the property attributes of a real property in the prototype chain,
* which can be None or any combination of ReadOnly, DontEnum and DontDelete.
* Interceptors in the prototype chain are not called.
*/
V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute>
GetRealNamedPropertyAttributesInPrototypeChain(Local<Context> context,
Local<Name> key);
/**
* If result.IsEmpty() no real property was located on the object or
* in the prototype chain.
* This means interceptors in the prototype chain are not called.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedProperty(
Local<Context> context, Local<Name> key);
/**
* Gets the property attributes of a real property which can be
* None or any combination of ReadOnly, DontEnum and DontDelete.
* Interceptors in the prototype chain are not called.
*/
V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
Local<Context> context, Local<Name> key);
/** Tests for a named lookup interceptor.*/
bool HasNamedLookupInterceptor();
/** Tests for an index lookup interceptor.*/
bool HasIndexedLookupInterceptor();
/**
* Returns the identity hash for this object. The current implementation
* uses a hidden property on the object to store the identity hash.
*
* The return value will never be 0. Also, it is not guaranteed to be
* unique.
*/
int GetIdentityHash();
/**
* Clone this object with a fast but shallow copy. Values will point
* to the same values as the original object.
*/
// TODO(dcarney): take an isolate and optionally bail out?
Local<Object> Clone();
/**
* Returns the context in which the object was created.
*/
Local<Context> CreationContext();
/** Same as above, but works for Persistents */
V8_INLINE static Local<Context> CreationContext(
const PersistentBase<Object>& object) {
return object.val_->CreationContext();
}
/**
* Checks whether a callback is set by the
* ObjectTemplate::SetCallAsFunctionHandler method.
* When an Object is callable this method returns true.
*/
bool IsCallable();
/**
* True if this object is a constructor.
*/
bool IsConstructor();
/**
* Call an Object as a function if a callback is set by the
* ObjectTemplate::SetCallAsFunctionHandler method.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context,
Local<Value> recv,
int argc,
Local<Value> argv[]);
/**
* Call an Object as a constructor if a callback is set by the
* ObjectTemplate::SetCallAsFunctionHandler method.
* Note: This method behaves like the Function::NewInstance method.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsConstructor(
Local<Context> context, int argc, Local<Value> argv[]);
/**
* Return the isolate to which the Object belongs to.
*/
Isolate* GetIsolate();
/**
* If this object is a Set, Map, WeakSet or WeakMap, this returns a
* representation of the elements of this object as an array.
* If this object is a SetIterator or MapIterator, this returns all
* elements of the underlying collection, starting at the iterator's current
* position.
* For other types, this will return an empty MaybeLocal<Array> (without
* scheduling an exception).
*/
MaybeLocal<Array> PreviewEntries(bool* is_key_value);
static Local<Object> New(Isolate* isolate);
V8_INLINE static Object* Cast(Value* obj);
private:
Object();
static void CheckCast(Value* obj);
Local<Value> SlowGetInternalField(int index);
void* SlowGetAlignedPointerFromInternalField(int index);
};
/**
* An instance of the built-in array constructor (ECMA-262, 15.4.2).
*/
class V8_EXPORT Array : public Object {
public:
uint32_t Length() const;
/**
* Creates a JavaScript array with the given length. If the length
* is negative the returned array will have length 0.
*/
static Local<Array> New(Isolate* isolate, int length = 0);
V8_INLINE static Array* Cast(Value* obj);
private:
Array();
static void CheckCast(Value* obj);
};
/**
* An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
*/
class V8_EXPORT Map : public Object {
public:
size_t Size() const;
void Clear();
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
Local<Value> key);
V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context,
Local<Value> key,
Local<Value> value);
V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
Local<Value> key);
V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
Local<Value> key);
/**
* Returns an array of length Size() * 2, where index N is the Nth key and
* index N + 1 is the Nth value.
*/
Local<Array> AsArray() const;
/**
* Creates a new empty Map.
*/
static Local<Map> New(Isolate* isolate);
V8_INLINE static Map* Cast(Value* obj);
private:
Map();
static void CheckCast(Value* obj);
};
/**
* An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
*/
class V8_EXPORT Set : public Object {
public:
size_t Size() const;
void Clear();
V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context,
Local<Value> key);
V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
Local<Value> key);
V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
Local<Value> key);
/**
* Returns an array of the keys in this Set.
*/
Local<Array> AsArray() const;
/**
* Creates a new empty Set.
*/
static Local<Set> New(Isolate* isolate);
V8_INLINE static Set* Cast(Value* obj);
private:
Set();
static void CheckCast(Value* obj);
};
template<typename T>
class ReturnValue {
public:
template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
: value_(that.value_) {
TYPE_CHECK(T, S);
}
// Local setters
template <typename S>
V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
void Set(const Persistent<S>& handle));
template <typename S>
V8_INLINE void Set(const Global<S>& handle);
template <typename S>
V8_INLINE void Set(const Local<S> handle);
// Fast primitive setters
V8_INLINE void Set(bool value);
V8_INLINE void Set(double i);
V8_INLINE void Set(int32_t i);
V8_INLINE void Set(uint32_t i);
// Fast JS primitive setters
V8_INLINE void SetNull();
V8_INLINE void SetUndefined();
V8_INLINE void SetEmptyString();
// Convenience getter for Isolate
V8_INLINE Isolate* GetIsolate() const;
// Pointer setter: Uncompilable to prevent inadvertent misuse.
template <typename S>
V8_INLINE void Set(S* whatever);
// Getter. Creates a new Local<> so it comes with a certain performance
// hit. If the ReturnValue was not yet set, this will return the undefined
// value.
V8_INLINE Local<Value> Get() const;
private:
template<class F> friend class ReturnValue;
template<class F> friend class FunctionCallbackInfo;
template<class F> friend class PropertyCallbackInfo;
template <class F, class G, class H>
friend class PersistentValueMapBase;
V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
V8_INLINE internal::Object* GetDefaultValue();
V8_INLINE explicit ReturnValue(internal::Object** slot);
internal::Object** value_;
};
/**
* The argument information given to function call callbacks. This
* class provides access to information about the context of the call,
* including the receiver, the number and values of arguments, and
* the holder of the function.
*/
template<typename T>
class FunctionCallbackInfo {
public:
/** The number of available arguments. */
V8_INLINE int Length() const;
/** Accessor for the available arguments. */
V8_INLINE Local<Value> operator[](int i) const;
/** Returns the receiver. This corresponds to the "this" value. */
V8_INLINE Local<Object> This() const;
/**
* If the callback was created without a Signature, this is the same
* value as This(). If there is a signature, and the signature didn't match
* This() but one of its hidden prototypes, this will be the respective
* hidden prototype.
*
* Note that this is not the prototype of This() on which the accessor
* referencing this callback was found (which in V8 internally is often
* referred to as holder [sic]).
*/
V8_INLINE Local<Object> Holder() const;
/** For construct calls, this returns the "new.target" value. */
V8_INLINE Local<Value> NewTarget() const;
/** Indicates whether this is a regular call or a construct call. */
V8_INLINE bool IsConstructCall() const;
/** The data argument specified when creating the callback. */
V8_INLINE Local<Value> Data() const;
/** The current Isolate. */
V8_INLINE Isolate* GetIsolate() const;
/** The ReturnValue for the call. */
V8_INLINE ReturnValue<T> GetReturnValue() const;
// This shouldn't be public, but the arm compiler needs it.
static const int kArgsLength = 6;
protected:
friend class internal::FunctionCallbackArguments;
friend class internal::CustomArguments<FunctionCallbackInfo>;
friend class debug::ConsoleCallArguments;
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kNewTargetIndex = 5;
V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
internal::Object** values, int length);
internal::Object** implicit_args_;
internal::Object** values_;
int length_;
};
/**
* The information passed to a property callback about the context
* of the property access.
*/
template<typename T>
class PropertyCallbackInfo {
public:
/**
* \return The isolate of the property access.
*/
V8_INLINE Isolate* GetIsolate() const;
/**
* \return The data set in the configuration, i.e., in
* `NamedPropertyHandlerConfiguration` or
* `IndexedPropertyHandlerConfiguration.`
*/
V8_INLINE Local<Value> Data() const;
/**
* \return The receiver. In many cases, this is the object on which the
* property access was intercepted. When using
* `Reflect.get`, `Function.prototype.call`, or similar functions, it is the
* object passed in as receiver or thisArg.
*
* \code
* void GetterCallback(Local<Name> name,
* const v8::PropertyCallbackInfo<v8::Value>& info) {
* auto context = info.GetIsolate()->GetCurrentContext();
*
* v8::Local<v8::Value> a_this =
* info.This()
* ->GetRealNamedProperty(context, v8_str("a"))
* .ToLocalChecked();
* v8::Local<v8::Value> a_holder =
* info.Holder()
* ->GetRealNamedProperty(context, v8_str("a"))
* .ToLocalChecked();
*
* CHECK(v8_str("r")->Equals(context, a_this).FromJust());
* CHECK(v8_str("obj")->Equals(context, a_holder).FromJust());
*
* info.GetReturnValue().Set(name);
* }
*
* v8::Local<v8::FunctionTemplate> templ =
* v8::FunctionTemplate::New(isolate);
* templ->InstanceTemplate()->SetHandler(
* v8::NamedPropertyHandlerConfiguration(GetterCallback));
* LocalContext env;
* env->Global()
* ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
* .ToLocalChecked()
* ->NewInstance(env.local())
* .ToLocalChecked())
* .FromJust();
*
* CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)");
* \endcode
*/
V8_INLINE Local<Object> This() const;
/**
* \return The object in the prototype chain of the receiver that has the
* interceptor. Suppose you have `x` and its prototype is `y`, and `y`
* has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`.
* The Holder() could be a hidden object (the global object, rather
* than the global proxy).
*
* \note For security reasons, do not pass the object back into the runtime.
*/
V8_INLINE Local<Object> Holder() const;
/**
* \return The return value of the callback.
* Can be changed by calling Set().
* \code
* info.GetReturnValue().Set(...)
* \endcode
*
*/
V8_INLINE ReturnValue<T> GetReturnValue() const;
/**
* \return True if the intercepted function should throw if an error occurs.
* Usually, `true` corresponds to `'use strict'`.
*
* \note Always `false` when intercepting `Reflect.set()`
* independent of the language mode.
*/
V8_INLINE bool ShouldThrowOnError() const;
// This shouldn't be public, but the arm compiler needs it.
static const int kArgsLength = 7;
protected:
friend class MacroAssembler;
friend class internal::PropertyCallbackArguments;
friend class internal::CustomArguments<PropertyCallbackInfo>;
static const int kShouldThrowOnErrorIndex = 0;
static const int kHolderIndex = 1;
static const int kIsolateIndex = 2;
static const int kReturnValueDefaultValueIndex = 3;
static const int kReturnValueIndex = 4;
static const int kDataIndex = 5;
static const int kThisIndex = 6;
V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
internal::Object** args_;
};
typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
enum class ConstructorBehavior { kThrow, kAllow };
/**
* A JavaScript function object (ECMA-262, 15.3).
*/
class V8_EXPORT Function : public Object {
public:
/**
* Create a function in the current execution context
* for a given FunctionCallback.
*/
static MaybeLocal<Function> New(
Local<Context> context, FunctionCallback callback,
Local<Value> data = Local<Value>(), int length = 0,
ConstructorBehavior behavior = ConstructorBehavior::kAllow,
SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
static V8_DEPRECATE_SOON(
"Use maybe version",
Local<Function> New(Isolate* isolate, FunctionCallback callback,
Local<Value> data = Local<Value>(), int length = 0));
V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
Local<Context> context, int argc, Local<Value> argv[]) const;
V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
Local<Context> context) const {
return NewInstance(context, 0, nullptr);
}
/**
* When side effect checks are enabled, passing kHasNoSideEffect allows the
* constructor to be invoked without throwing. Calls made within the
* constructor are still checked.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstanceWithSideEffectType(
Local<Context> context, int argc, Local<Value> argv[],
SideEffectType side_effect_type = SideEffectType::kHasSideEffect) const;
V8_DEPRECATE_SOON("Use maybe version",
Local<Value> Call(Local<Value> recv, int argc,
Local<Value> argv[]));
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context,
Local<Value> recv, int argc,
Local<Value> argv[]);
void SetName(Local<String> name);
Local<Value> GetName() const;
/**
* Name inferred from variable or property assignment of this function.
* Used to facilitate debugging and profiling of JavaScript code written
* in an OO style, where many functions are anonymous but are assigned
* to object properties.
*/
Local<Value> GetInferredName() const;
/**
* displayName if it is set, otherwise name if it is configured, otherwise
* function name, otherwise inferred name.
*/
Local<Value> GetDebugName() const;
/**
* User-defined name assigned to the "displayName" property of this function.
* Used to facilitate debugging and profiling of JavaScript code.
*/
Local<Value> GetDisplayName() const;
/**
* Returns zero based line number of function body and
* kLineOffsetNotFound if no information available.
*/
int GetScriptLineNumber() const;
/**
* Returns zero based column number of function body and
* kLineOffsetNotFound if no information available.
*/
int GetScriptColumnNumber() const;
/**
* Returns scriptId.
*/
int ScriptId() const;
/**
* Returns the original function if this function is bound, else returns
* v8::Undefined.
*/
Local<Value> GetBoundFunction() const;
ScriptOrigin GetScriptOrigin() const;
V8_INLINE static Function* Cast(Value* obj);
static const int kLineOffsetNotFound;
private:
Function();
static void CheckCast(Value* obj);
};
#ifndef V8_PROMISE_INTERNAL_FIELD_COUNT
// The number of required internal fields can be defined by embedder.
#define V8_PROMISE_INTERNAL_FIELD_COUNT 0
#endif
/**
* An instance of the built-in Promise constructor (ES6 draft).
*/
class V8_EXPORT Promise : public Object {
public:
/**
* State of the promise. Each value corresponds to one of the possible values
* of the [[PromiseState]] field.
*/
enum PromiseState { kPending, kFulfilled, kRejected };
class V8_EXPORT Resolver : public Object {
public:
/**
* Create a new resolver, along with an associated promise in pending state.
*/
static V8_DEPRECATED("Use maybe version",
Local<Resolver> New(Isolate* isolate));
static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New(
Local<Context> context);
/**
* Extract the associated promise.
*/
Local<Promise> GetPromise();
/**
* Resolve/reject the associated promise with a given value.
* Ignored if the promise is no longer pending.
*/
V8_DEPRECATED("Use maybe version", void Resolve(Local<Value> value));
V8_WARN_UNUSED_RESULT Maybe<bool> Resolve(Local<Context> context,
Local<Value> value);
V8_DEPRECATED("Use maybe version", void Reject(Local<Value> value));
V8_WARN_UNUSED_RESULT Maybe<bool> Reject(Local<Context> context,
Local<Value> value);
V8_INLINE static Resolver* Cast(Value* obj);
private:
Resolver();
static void CheckCast(Value* obj);
};
/**
* Register a resolution/rejection handler with a promise.
* The handler is given the respective resolution/rejection value as
* an argument. If the promise is already resolved/rejected, the handler is
* invoked at the end of turn.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context,
Local<Function> handler);
V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
Local<Function> handler);
/**
* Returns true if the promise has at least one derived promise, and
* therefore resolve/reject handlers (including default handler).
*/
bool HasHandler();
/**
* Returns the content of the [[PromiseResult]] field. The Promise must not
* be pending.
*/
Local<Value> Result();
/**
* Returns the value of the [[PromiseState]] field.
*/
PromiseState State();
V8_INLINE static Promise* Cast(Value* obj);
static const int kEmbedderFieldCount = V8_PROMISE_INTERNAL_FIELD_COUNT;
private:
Promise();
static void CheckCast(Value* obj);
};
/**
* An instance of a Property Descriptor, see Ecma-262 6.2.4.
*
* Properties in a descriptor are present or absent. If you do not set
* `enumerable`, `configurable`, and `writable`, they are absent. If `value`,
* `get`, or `set` are absent, but you must specify them in the constructor, use
* empty handles.
*
* Accessors `get` and `set` must be callable or undefined if they are present.
*
* \note Only query properties if they are present, i.e., call `x()` only if
* `has_x()` returns true.
*
* \code
* // var desc = {writable: false}
* v8::PropertyDescriptor d(Local<Value>()), false);
* d.value(); // error, value not set
* if (d.has_writable()) {
* d.writable(); // false
* }
*
* // var desc = {value: undefined}
* v8::PropertyDescriptor d(v8::Undefined(isolate));
*
* // var desc = {get: undefined}
* v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>()));
* \endcode
*/
class V8_EXPORT PropertyDescriptor {
public:
// GenericDescriptor
PropertyDescriptor();
// DataDescriptor
PropertyDescriptor(Local<Value> value);
// DataDescriptor with writable property
PropertyDescriptor(Local<Value> value, bool writable);
// AccessorDescriptor
PropertyDescriptor(Local<Value> get, Local<Value> set);
~PropertyDescriptor();
Local<Value> value() const;
bool has_value() const;
Local<Value> get() const;
bool has_get() const;
Local<Value> set() const;
bool has_set() const;
void set_enumerable(bool enumerable);
bool enumerable() const;
bool has_enumerable() const;
void set_configurable(bool configurable);
bool configurable() const;
bool has_configurable() const;
bool writable() const;
bool has_writable() const;
struct PrivateData;
PrivateData* get_private() const { return private_; }
PropertyDescriptor(const PropertyDescriptor&) = delete;
void operator=(const PropertyDescriptor&) = delete;
private:
PrivateData* private_;
};
/**
* An instance of the built-in Proxy constructor (ECMA-262, 6th Edition,
* 26.2.1).
*/
class V8_EXPORT Proxy : public Object {
public:
Local<Value> GetTarget();
Local<Value> GetHandler();
bool IsRevoked();
void Revoke();
/**
* Creates a new Proxy for the target object.
*/
static MaybeLocal<Proxy> New(Local<Context> context,
Local<Object> local_target,
Local<Object> local_handler);
V8_INLINE static Proxy* Cast(Value* obj);
private:
Proxy();
static void CheckCast(Value* obj);
};
// TODO(mtrofin): rename WasmCompiledModule to WasmModuleObject, for
// consistency with internal APIs.
class V8_EXPORT WasmCompiledModule : public Object {
public:
typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> SerializedModule;
/**
* A buffer that is owned by the caller.
*/
typedef std::pair<const uint8_t*, size_t> CallerOwnedBuffer;
/**
* An opaque, native heap object for transferring wasm modules. It
* supports move semantics, and does not support copy semantics.
*/
class TransferrableModule final {
public:
TransferrableModule(TransferrableModule&& src) = default;
TransferrableModule(const TransferrableModule& src) = delete;
TransferrableModule& operator=(TransferrableModule&& src) = default;
TransferrableModule& operator=(const TransferrableModule& src) = delete;
private:
typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> OwnedBuffer;
friend class WasmCompiledModule;
TransferrableModule(OwnedBuffer&& code, OwnedBuffer&& bytes)
: compiled_code(std::move(code)), wire_bytes(std::move(bytes)) {}
OwnedBuffer compiled_code = {nullptr, 0};
OwnedBuffer wire_bytes = {nullptr, 0};
};
/**
* Get an in-memory, non-persistable, and context-independent (meaning,
* suitable for transfer to another Isolate and Context) representation
* of this wasm compiled module.
*/
TransferrableModule GetTransferrableModule();
/**
* Efficiently re-create a WasmCompiledModule, without recompiling, from
* a TransferrableModule.
*/
static MaybeLocal<WasmCompiledModule> FromTransferrableModule(
Isolate* isolate, const TransferrableModule&);
/**
* Get the wasm-encoded bytes that were used to compile this module.
*/
Local<String> GetWasmWireBytes();
/**
* Serialize the compiled module. The serialized data does not include the
* uncompiled bytes.
*/
SerializedModule Serialize();
/**
* If possible, deserialize the module, otherwise compile it from the provided
* uncompiled bytes.
*/
static MaybeLocal<WasmCompiledModule> DeserializeOrCompile(
Isolate* isolate, const CallerOwnedBuffer& serialized_module,
const CallerOwnedBuffer& wire_bytes);
V8_INLINE static WasmCompiledModule* Cast(Value* obj);
private:
static MaybeLocal<WasmCompiledModule> Deserialize(
Isolate* isolate, const CallerOwnedBuffer& serialized_module,
const CallerOwnedBuffer& wire_bytes);
static MaybeLocal<WasmCompiledModule> Compile(Isolate* isolate,
const uint8_t* start,
size_t length);
static CallerOwnedBuffer AsCallerOwned(
const TransferrableModule::OwnedBuffer& buff) {
return {buff.first.get(), buff.second};
}
WasmCompiledModule();
static void CheckCast(Value* obj);
};
// TODO(mtrofin): when streaming compilation is done, we can rename this
// to simply WasmModuleObjectBuilder
class V8_EXPORT WasmModuleObjectBuilderStreaming final {
public:
explicit WasmModuleObjectBuilderStreaming(Isolate* isolate);
/**
* The buffer passed into OnBytesReceived is owned by the caller.
*/
void OnBytesReceived(const uint8_t*, size_t size);
void Finish();
/**
* Abort streaming compilation. If {exception} has a value, then the promise
* associated with streaming compilation is rejected with that value. If
* {exception} does not have value, the promise does not get rejected.
*/
void Abort(MaybeLocal<Value> exception);
Local<Promise> GetPromise();
~WasmModuleObjectBuilderStreaming();
private:
WasmModuleObjectBuilderStreaming(const WasmModuleObjectBuilderStreaming&) =
delete;
WasmModuleObjectBuilderStreaming(WasmModuleObjectBuilderStreaming&&) =
default;
WasmModuleObjectBuilderStreaming& operator=(
const WasmModuleObjectBuilderStreaming&) = delete;
WasmModuleObjectBuilderStreaming& operator=(
WasmModuleObjectBuilderStreaming&&) = default;
Isolate* isolate_ = nullptr;
#if V8_CC_MSVC
/**
* We don't need the static Copy API, so the default
* NonCopyablePersistentTraits would be sufficient, however,
* MSVC eagerly instantiates the Copy.
* We ensure we don't use Copy, however, by compiling with the
* defaults everywhere else.
*/
Persistent<Promise, CopyablePersistentTraits<Promise>> promise_;
#else
Persistent<Promise> promise_;
#endif
std::shared_ptr<internal::wasm::StreamingDecoder> streaming_decoder_;
};
#ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
// The number of required internal fields can be defined by embedder.
#define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
#endif
enum class ArrayBufferCreationMode { kInternalized, kExternalized };
/**
* An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
*/
class V8_EXPORT ArrayBuffer : public Object {
public:
/**
* A thread-safe allocator that V8 uses to allocate |ArrayBuffer|'s memory.
* The allocator is a global V8 setting. It has to be set via
* Isolate::CreateParams.
*
* Memory allocated through this allocator by V8 is accounted for as external
* memory by V8. Note that V8 keeps track of the memory for all internalized
* |ArrayBuffer|s. Responsibility for tracking external memory (using
* Isolate::AdjustAmountOfExternalAllocatedMemory) is handed over to the
* embedder upon externalization and taken over upon internalization (creating
* an internalized buffer from an existing buffer).
*
* Note that it is unsafe to call back into V8 from any of the allocator
* functions.
*/
class V8_EXPORT Allocator { // NOLINT
public:
virtual ~Allocator() {}
/**
* Allocate |length| bytes. Return NULL if allocation is not successful.
* Memory should be initialized to zeroes.
*/
virtual void* Allocate(size_t length) = 0;
/**
* Allocate |length| bytes. Return NULL if allocation is not successful.
* Memory does not have to be initialized.
*/
virtual void* AllocateUninitialized(size_t length) = 0;
/**
* Free the memory block of size |length|, pointed to by |data|.
* That memory is guaranteed to be previously allocated by |Allocate|.
*/
virtual void Free(void* data, size_t length) = 0;
/**
* ArrayBuffer allocation mode. kNormal is a malloc/free style allocation,
* while kReservation is for larger allocations with the ability to set
* access permissions.
*/
enum class AllocationMode { kNormal, kReservation };
/**
* malloc/free based convenience allocator.
*
* Caller takes ownership, i.e. the returned object needs to be freed using
* |delete allocator| once it is no longer in use.
*/
static Allocator* NewDefaultAllocator();
};
/**
* The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
* returns an instance of this class, populated, with a pointer to data
* and byte length.
*
* The Data pointer of ArrayBuffer::Contents is always allocated with
* Allocator::Allocate that is set via Isolate::CreateParams.
*/
class V8_EXPORT Contents { // NOLINT
public:
Contents()
: data_(nullptr),
byte_length_(0),
allocation_base_(nullptr),
allocation_length_(0),
allocation_mode_(Allocator::AllocationMode::kNormal) {}
void* AllocationBase() const { return allocation_base_; }
size_t AllocationLength() const { return allocation_length_; }
Allocator::AllocationMode AllocationMode() const {
return allocation_mode_;
}
void* Data() const { return data_; }
size_t ByteLength() const { return byte_length_; }
private:
void* data_;
size_t byte_length_;
void* allocation_base_;
size_t allocation_length_;
Allocator::AllocationMode allocation_mode_;
friend class ArrayBuffer;
};
/**
* Data length in bytes.
*/
size_t ByteLength() const;
/**
* Create a new ArrayBuffer. Allocate |byte_length| bytes.
* Allocated memory will be owned by a created ArrayBuffer and
* will be deallocated when it is garbage-collected,
* unless the object is externalized.
*/
static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
/**
* Create a new ArrayBuffer over an existing memory block.
* The created array buffer is by default immediately in externalized state.
* In externalized state, the memory block will not be reclaimed when a
* created ArrayBuffer is garbage-collected.
* In internalized state, the memory block will be released using
* |Allocator::Free| once all ArrayBuffers referencing it are collected by
* the garbage collector.
*/
static Local<ArrayBuffer> New(
Isolate* isolate, void* data, size_t byte_length,
ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
/**
* Returns true if ArrayBuffer is externalized, that is, does not
* own its memory block.
*/
bool IsExternal() const;
/**
* Returns true if this ArrayBuffer may be neutered.
*/
bool IsNeuterable() const;
/**
* Neuters this ArrayBuffer and all its views (typed arrays).
* Neutering sets the byte length of the buffer and all typed arrays to zero,
* preventing JavaScript from ever accessing underlying backing store.
* ArrayBuffer should have been externalized and must be neuterable.
*/
void Neuter();
/**
* Make this ArrayBuffer external. The pointer to underlying memory block
* and byte length are returned as |Contents| structure. After ArrayBuffer
* had been externalized, it does no longer own the memory block. The caller
* should take steps to free memory when it is no longer needed.
*
* The memory block is guaranteed to be allocated with |Allocator::Allocate|
* that has been set via Isolate::CreateParams.
*/
Contents Externalize();
/**
* Get a pointer to the ArrayBuffer's underlying memory block without
* externalizing it. If the ArrayBuffer is not externalized, this pointer
* will become invalid as soon as the ArrayBuffer gets garbage collected.
*
* The embedder should make sure to hold a strong reference to the
* ArrayBuffer while accessing this pointer.
*
* The memory block is guaranteed to be allocated with |Allocator::Allocate|.
*/
Contents GetContents();
V8_INLINE static ArrayBuffer* Cast(Value* obj);
static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
static const int kEmbedderFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
private:
ArrayBuffer();
static void CheckCast(Value* obj);
};
#ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
// The number of required internal fields can be defined by embedder.
#define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
#endif
/**
* A base class for an instance of one of "views" over ArrayBuffer,
* including TypedArrays and DataView (ES6 draft 15.13).
*/
class V8_EXPORT ArrayBufferView : public Object {
public:
/**
* Returns underlying ArrayBuffer.
*/
Local<ArrayBuffer> Buffer();
/**
* Byte offset in |Buffer|.
*/
size_t ByteOffset();
/**
* Size of a view in bytes.
*/
size_t ByteLength();
/**
* Copy the contents of the ArrayBufferView's buffer to an embedder defined
* memory without additional overhead that calling ArrayBufferView::Buffer
* might incur.
*
* Will write at most min(|byte_length|, ByteLength) bytes starting at
* ByteOffset of the underlying buffer to the memory starting at |dest|.
* Returns the number of bytes actually written.
*/
size_t CopyContents(void* dest, size_t byte_length);
/**
* Returns true if ArrayBufferView's backing ArrayBuffer has already been
* allocated.
*/
bool HasBuffer() const;
V8_INLINE static ArrayBufferView* Cast(Value* obj);
static const int kInternalFieldCount =
V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
static const int kEmbedderFieldCount =
V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
private:
ArrayBufferView();
static void CheckCast(Value* obj);
};
/**
* A base class for an instance of TypedArray series of constructors
* (ES6 draft 15.13.6).
*/
class V8_EXPORT TypedArray : public ArrayBufferView {
public:
/*
* The largest typed array size that can be constructed using New.
*/
static constexpr size_t kMaxLength =
sizeof(void*) == 4 ? (1u << 30) - 1 : (1u << 31) - 1;
/**
* Number of elements in this typed array
* (e.g. for Int16Array, |ByteLength|/2).
*/
size_t Length();
V8_INLINE static TypedArray* Cast(Value* obj);
private:
TypedArray();
static void CheckCast(Value* obj);
};
/**
* An instance of Uint8Array constructor (ES6 draft 15.13.6).
*/
class V8_EXPORT Uint8Array : public TypedArray {
public:
static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static Uint8Array* Cast(Value* obj);
private:
Uint8Array();
static void CheckCast(Value* obj);
};
/**
* An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
*/
class V8_EXPORT Uint8ClampedArray : public TypedArray {
public:
static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<Uint8ClampedArray> New(
Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
size_t length);
V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
private:
Uint8ClampedArray();
static void CheckCast(Value* obj);
};
/**
* An instance of Int8Array constructor (ES6 draft 15.13.6).
*/
class V8_EXPORT Int8Array : public TypedArray {
public:
static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static Int8Array* Cast(Value* obj);
private:
Int8Array();
static void CheckCast(Value* obj);
};
/**
* An instance of Uint16Array constructor (ES6 draft 15.13.6).
*/
class V8_EXPORT Uint16Array : public TypedArray {
public:
static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static Uint16Array* Cast(Value* obj);
private:
Uint16Array();
static void CheckCast(Value* obj);
};
/**
* An instance of Int16Array constructor (ES6 draft 15.13.6).
*/
class V8_EXPORT Int16Array : public TypedArray {
public:
static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static Int16Array* Cast(Value* obj);
private:
Int16Array();
static void CheckCast(Value* obj);
};
/**
* An instance of Uint32Array constructor (ES6 draft 15.13.6).
*/
class V8_EXPORT Uint32Array : public TypedArray {
public:
static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static Uint32Array* Cast(Value* obj);
private:
Uint32Array();
static void CheckCast(Value* obj);
};
/**
* An instance of Int32Array constructor (ES6 draft 15.13.6).
*/
class V8_EXPORT Int32Array : public TypedArray {
public:
static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static Int32Array* Cast(Value* obj);
private:
Int32Array();
static void CheckCast(Value* obj);
};
/**
* An instance of Float32Array constructor (ES6 draft 15.13.6).
*/
class V8_EXPORT Float32Array : public TypedArray {
public:
static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static Float32Array* Cast(Value* obj);
private:
Float32Array();
static void CheckCast(Value* obj);
};
/**
* An instance of Float64Array constructor (ES6 draft 15.13.6).
*/
class V8_EXPORT Float64Array : public TypedArray {
public:
static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static Float64Array* Cast(Value* obj);
private:
Float64Array();
static void CheckCast(Value* obj);
};
/**
* An instance of BigInt64Array constructor.
*/
class V8_EXPORT BigInt64Array : public TypedArray {
public:
static Local<BigInt64Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<BigInt64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static BigInt64Array* Cast(Value* obj);
private:
BigInt64Array();
static void CheckCast(Value* obj);
};
/**
* An instance of BigUint64Array constructor.
*/
class V8_EXPORT BigUint64Array : public TypedArray {
public:
static Local<BigUint64Array> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<BigUint64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static BigUint64Array* Cast(Value* obj);
private:
BigUint64Array();
static void CheckCast(Value* obj);
};
/**
* An instance of DataView constructor (ES6 draft 15.13.7).
*/
class V8_EXPORT DataView : public ArrayBufferView {
public:
static Local<DataView> New(Local<ArrayBuffer> array_buffer,
size_t byte_offset, size_t length);
static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
size_t byte_offset, size_t length);
V8_INLINE static DataView* Cast(Value* obj);
private:
DataView();
static void CheckCast(Value* obj);
};
/**
* An instance of the built-in SharedArrayBuffer constructor.
* This API is experimental and may change significantly.
*/
class V8_EXPORT SharedArrayBuffer : public Object {
public:
/**
* The contents of an |SharedArrayBuffer|. Externalization of
* |SharedArrayBuffer| returns an instance of this class, populated, with a
* pointer to data and byte length.
*
* The Data pointer of SharedArrayBuffer::Contents is always allocated with
* |ArrayBuffer::Allocator::Allocate| by the allocator specified in
* v8::Isolate::CreateParams::array_buffer_allocator.
*
* This API is experimental and may change significantly.
*/
class V8_EXPORT Contents { // NOLINT
public:
Contents()
: data_(nullptr),
byte_length_(0),
allocation_base_(nullptr),
allocation_length_(0),
allocation_mode_(ArrayBuffer::Allocator::AllocationMode::kNormal) {}
void* AllocationBase() const { return allocation_base_; }
size_t AllocationLength() const { return allocation_length_; }
ArrayBuffer::Allocator::AllocationMode AllocationMode() const {
return allocation_mode_;
}
void* Data() const { return data_; }
size_t ByteLength() const { return byte_length_; }
private:
void* data_;
size_t byte_length_;
void* allocation_base_;
size_t allocation_length_;
ArrayBuffer::Allocator::AllocationMode allocation_mode_;
friend class SharedArrayBuffer;
};
/**
* Data length in bytes.
*/
size_t ByteLength() const;
/**
* Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
* Allocated memory will be owned by a created SharedArrayBuffer and
* will be deallocated when it is garbage-collected,
* unless the object is externalized.
*/
static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
/**
* Create a new SharedArrayBuffer over an existing memory block. The created
* array buffer is immediately in externalized state unless otherwise
* specified. The memory block will not be reclaimed when a created
* SharedArrayBuffer is garbage-collected.
*/
static Local<SharedArrayBuffer> New(
Isolate* isolate, void* data, size_t byte_length,
ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
/**
* Returns true if SharedArrayBuffer is externalized, that is, does not
* own its memory block.
*/
bool IsExternal() const;
/**
* Make this SharedArrayBuffer external. The pointer to underlying memory
* block and byte length are returned as |Contents| structure. After
* SharedArrayBuffer had been externalized, it does no longer own the memory
* block. The caller should take steps to free memory when it is no longer
* needed.
*
* The memory block is guaranteed to be allocated with |Allocator::Allocate|
* by the allocator specified in
* v8::Isolate::CreateParams::array_buffer_allocator.
*
*/
Contents Externalize();
/**
* Get a pointer to the ArrayBuffer's underlying memory block without
* externalizing it. If the ArrayBuffer is not externalized, this pointer
* will become invalid as soon as the ArrayBuffer became garbage collected.
*
* The embedder should make sure to hold a strong reference to the
* ArrayBuffer while accessing this pointer.
*
* The memory block is guaranteed to be allocated with |Allocator::Allocate|
* by the allocator specified in
* v8::Isolate::CreateParams::array_buffer_allocator.
*/
Contents GetContents();
V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
private:
SharedArrayBuffer();
static void CheckCast(Value* obj);
};
/**
* An instance of the built-in Date constructor (ECMA-262, 15.9).
*/
class V8_EXPORT Date : public Object {
public:
static V8_DEPRECATE_SOON("Use maybe version.",
Local<Value> New(Isolate* isolate, double time));
static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
double time);
/**
* A specialization of Value::NumberValue that is more efficient
* because we know the structure of this object.
*/
double ValueOf() const;
V8_INLINE static Date* Cast(Value* obj);
/**
* Notification that the embedder has changed the time zone,
* daylight savings time, or other date / time configuration
* parameters. V8 keeps a cache of various values used for
* date / time computation. This notification will reset
* those cached values for the current context so that date /
* time configuration changes would be reflected in the Date
* object.
*
* This API should not be called more than needed as it will
* negatively impact the performance of date operations.
*/
static void DateTimeConfigurationChangeNotification(Isolate* isolate);
private:
static void CheckCast(Value* obj);
};
/**
* A Number object (ECMA-262, 4.3.21).
*/
class V8_EXPORT NumberObject : public Object {
public:
static Local<Value> New(Isolate* isolate, double value);
double ValueOf() const;
V8_INLINE static NumberObject* Cast(Value* obj);
private:
static void CheckCast(Value* obj);
};
/**
* A BigInt object (https://tc39.github.io/proposal-bigint)
*/
class V8_EXPORT BigIntObject : public Object {
public:
static Local<Value> New(Isolate* isolate, int64_t value);
Local<BigInt> ValueOf() const;
V8_INLINE static BigIntObject* Cast(Value* obj);
private:
static void CheckCast(Value* obj);
};
/**
* A Boolean object (ECMA-262, 4.3.15).
*/
class V8_EXPORT BooleanObject : public Object {
public:
static Local<Value> New(Isolate* isolate, bool value);
bool ValueOf() const;
V8_INLINE static BooleanObject* Cast(Value* obj);
private:
static void CheckCast(Value* obj);
};
/**
* A String object (ECMA-262, 4.3.18).
*/
class V8_EXPORT StringObject : public Object {
public:
static Local<Value> New(Isolate* isolate, Local<String> value);
V8_DEPRECATE_SOON("Use Isolate* version",
static Local<Value> New(Local<String> value));
Local<String> ValueOf() const;
V8_INLINE static StringObject* Cast(Value* obj);
private:
static void CheckCast(Value* obj);
};
/**
* A Symbol object (ECMA-262 edition 6).
*/
class V8_EXPORT SymbolObject : public Object {
public:
static Local<Value> New(Isolate* isolate, Local<Symbol> value);
Local<Symbol> ValueOf() const;
V8_INLINE static SymbolObject* Cast(Value* obj);
private:
static void CheckCast(Value* obj);
};
/**
* An instance of the built-in RegExp constructor (ECMA-262, 15.10).
*/
class V8_EXPORT RegExp : public Object {
public:
/**
* Regular expression flag bits. They can be or'ed to enable a set
* of flags.
*/
enum Flags {
kNone = 0,
kGlobal = 1 << 0,
kIgnoreCase = 1 << 1,
kMultiline = 1 << 2,
kSticky = 1 << 3,
kUnicode = 1 << 4,
kDotAll = 1 << 5,
};
/**
* Creates a regular expression from the given pattern string and
* the flags bit field. May throw a JavaScript exception as
* described in ECMA-262, 15.10.4.1.
*
* For example,
* RegExp::New(v8::String::New("foo"),
* static_cast<RegExp::Flags>(kGlobal | kMultiline))
* is equivalent to evaluating "/foo/gm".
*/
static V8_DEPRECATED("Use maybe version",
Local<RegExp> New(Local<String> pattern, Flags flags));
static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
Local<String> pattern,
Flags flags);
/**
* Returns the value of the source property: a string representing
* the regular expression.
*/
Local<String> GetSource() const;
/**
* Returns the flags bit field.
*/
Flags GetFlags() const;
V8_INLINE static RegExp* Cast(Value* obj);
private:
static void CheckCast(Value* obj);
};
/**
* A JavaScript value that wraps a C++ void*. This type of value is mainly used
* to associate C++ data structures with JavaScript objects.
*/
class V8_EXPORT External : public Value {
public:
static Local<External> New(Isolate* isolate, void* value);
V8_INLINE static External* Cast(Value* obj);
void* Value() const;
private:
static void CheckCast(v8::Value* obj);
};
#define V8_INTRINSICS_LIST(F) \
F(ArrayProto_entries, array_entries_iterator) \
F(ArrayProto_forEach, array_for_each_iterator) \
F(ArrayProto_keys, array_keys_iterator) \
F(ArrayProto_values, array_values_iterator) \
F(ErrorPrototype, initial_error_prototype) \
F(IteratorPrototype, initial_iterator_prototype)
enum Intrinsic {
#define V8_DECL_INTRINSIC(name, iname) k##name,
V8_INTRINSICS_LIST(V8_DECL_INTRINSIC)
#undef V8_DECL_INTRINSIC
};
// --- Templates ---
/**
* The superclass of object and function templates.
*/
class V8_EXPORT Template : public Data {
public:
/**
* Adds a property to each instance created by this template.
*
* The property must be defined either as a primitive value, or a template.
*/
void Set(Local<Name> name, Local<Data> value,
PropertyAttribute attributes = None);
void SetPrivate(Local<Private> name, Local<Data> value,
PropertyAttribute attributes = None);
V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
void SetAccessorProperty(
Local<Name> name,
Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
PropertyAttribute attribute = None,
AccessControl settings = DEFAULT);
/**
* Whenever the property with the given name is accessed on objects
* created from this Template the getter and setter callbacks
* are called instead of getting and setting the property directly
* on the JavaScript object.
*
* \param name The name of the property for which an accessor is added.
* \param getter The callback to invoke when getting the property.
* \param setter The callback to invoke when setting the property.
* \param data A piece of data that will be passed to the getter and setter
* callbacks whenever they are invoked.
* \param settings Access control settings for the accessor. This is a bit
* field consisting of one of more of
* DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
* The default is to not allow cross-context access.
* ALL_CAN_READ means that all cross-context reads are allowed.
* ALL_CAN_WRITE means that all cross-context writes are allowed.
* The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
* cross-context access.
* \param attribute The attributes of the property for which an accessor
* is added.
* \param signature The signature describes valid receivers for the accessor
* and is used to perform implicit instance checks against them. If the
* receiver is incompatible (i.e. is not an instance of the constructor as
* defined by FunctionTemplate::HasInstance()), an implicit TypeError is
* thrown and no callback is invoked.
*/
void SetNativeDataProperty(
Local<String> name, AccessorGetterCallback getter,
AccessorSetterCallback setter = 0,
// TODO(dcarney): gcc can't handle Local below
Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
Local<AccessorSignature> signature = Local<AccessorSignature>(),
AccessControl settings = DEFAULT);
void SetNativeDataProperty(
Local<Name> name, AccessorNameGetterCallback getter,
AccessorNameSetterCallback setter = 0,
// TODO(dcarney): gcc can't handle Local below
Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
Local<AccessorSignature> signature = Local<AccessorSignature>(),
AccessControl settings = DEFAULT);
/**
* Like SetNativeDataProperty, but V8 will replace the native data property
* with a real data property on first access.
*/
void SetLazyDataProperty(Local<Name> name, AccessorNameGetterCallback getter,
Local<Value> data = Local<Value>(),
PropertyAttribute attribute = None);
/**
* During template instantiation, sets the value with the intrinsic property
* from the correct context.
*/
void SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic,
PropertyAttribute attribute = None);
private:
Template();
friend class ObjectTemplate;
friend class FunctionTemplate;
};
/**
* NamedProperty[Getter|Setter] are used as interceptors on object.
* See ObjectTemplate::SetNamedPropertyHandler.
*/
typedef void (*NamedPropertyGetterCallback)(
Local<String> property,
const PropertyCallbackInfo<Value>& info);
/**
* Returns the value if the setter intercepts the request.
* Otherwise, returns an empty handle.
*/
typedef void (*NamedPropertySetterCallback)(
Local<String> property,
Local<Value> value,
const PropertyCallbackInfo<Value>& info);
/**
* Returns a non-empty handle if the interceptor intercepts the request.
* The result is an integer encoding property attributes (like v8::None,
* v8::DontEnum, etc.)
*/
typedef void (*NamedPropertyQueryCallback)(
Local<String> property,
const PropertyCallbackInfo<Integer>& info);
/**
* Returns a non-empty handle if the deleter intercepts the request.
* The return value is true if the property could be deleted and false
* otherwise.
*/
typedef void (*NamedPropertyDeleterCallback)(
Local<String> property,
const PropertyCallbackInfo<Boolean>& info);
/**
* Returns an array containing the names of the properties the named
* property getter intercepts.
*
* Note: The values in the array must be of type v8::Name.
*/
typedef void (*NamedPropertyEnumeratorCallback)(
const PropertyCallbackInfo<Array>& info);
// TODO(dcarney): Deprecate and remove previous typedefs, and replace
// GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
/**
* Interceptor for get requests on an object.
*
* Use `info.GetReturnValue().Set()` to set the return value of the
* intercepted get request.
*
* \param property The name of the property for which the request was
* intercepted.
* \param info Information about the intercepted request, such as
* isolate, receiver, return value, or whether running in `'use strict`' mode.
* See `PropertyCallbackInfo`.
*
* \code
* void GetterCallback(
* Local<Name> name,
* const v8::PropertyCallbackInfo<v8::Value>& info) {
* info.GetReturnValue().Set(v8_num(42));
* }
*
* v8::Local<v8::FunctionTemplate> templ =
* v8::FunctionTemplate::New(isolate);
* templ->InstanceTemplate()->SetHandler(
* v8::NamedPropertyHandlerConfiguration(GetterCallback));
* LocalContext env;
* env->Global()
* ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
* .ToLocalChecked()
* ->NewInstance(env.local())
* .ToLocalChecked())
* .FromJust();
* v8::Local<v8::Value> result = CompileRun("obj.a = 17; obj.a");
* CHECK(v8_num(42)->Equals(env.local(), result).FromJust());
* \endcode
*
* See also `ObjectTemplate::SetHandler`.
*/
typedef void (*GenericNamedPropertyGetterCallback)(
Local<Name> property, const PropertyCallbackInfo<Value>& info);
/**
* Interceptor for set requests on an object.
*
* Use `info.GetReturnValue()` to indicate whether the request was intercepted
* or not. If the setter successfully intercepts the request, i.e., if the
* request should not be further executed, call
* `info.GetReturnValue().Set(value)`. If the setter
* did not intercept the request, i.e., if the request should be handled as
* if no interceptor is present, do not not call `Set()`.
*
* \param property The name of the property for which the request was
* intercepted.
* \param value The value which the property will have if the request
* is not intercepted.
* \param info Information about the intercepted request, such as
* isolate, receiver, return value, or whether running in `'use strict'` mode.
* See `PropertyCallbackInfo`.
*
* See also
* `ObjectTemplate::SetHandler.`
*/
typedef void (*GenericNamedPropertySetterCallback)(
Local<Name> property, Local<Value> value,
const PropertyCallbackInfo<Value>& info);
/**
* Intercepts all requests that query the attributes of the
* property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and
* defineProperty().
*
* Use `info.GetReturnValue().Set(value)` to set the property attributes. The
* value is an integer encoding a `v8::PropertyAttribute`.
*
* \param property The name of the property for which the request was
* intercepted.
* \param info Information about the intercepted request, such as
* isolate, receiver, return value, or whether running in `'use strict'` mode.
* See `PropertyCallbackInfo`.
*
* \note Some functions query the property attributes internally, even though
* they do not return the attributes. For example, `hasOwnProperty()` can
* trigger this interceptor depending on the state of the object.
*
* See also
* `ObjectTemplate::SetHandler.`
*/
typedef void (*GenericNamedPropertyQueryCallback)(
Local<Name> property, const PropertyCallbackInfo<Integer>& info);
/**
* Interceptor for delete requests on an object.
*
* Use `info.GetReturnValue()` to indicate whether the request was intercepted
* or not. If the deleter successfully intercepts the request, i.e., if the
* request should not be further executed, call
* `info.GetReturnValue().Set(value)` with a boolean `value`. The `value` is
* used as the return value of `delete`.
*
* \param property The name of the property for which the request was
* intercepted.
* \param info Information about the intercepted request, such as
* isolate, receiver, return value, or whether running in `'use strict'` mode.
* See `PropertyCallbackInfo`.
*
* \note If you need to mimic the behavior of `delete`, i.e., throw in strict
* mode instead of returning false, use `info.ShouldThrowOnError()` to determine
* if you are in strict mode.
*
* See also `ObjectTemplate::SetHandler.`
*/
typedef void (*GenericNamedPropertyDeleterCallback)(
Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
/**
* Returns an array containing the names of the properties the named
* property getter intercepts.
*
* Note: The values in the array must be of type v8::Name.
*/
typedef void (*GenericNamedPropertyEnumeratorCallback)(
const PropertyCallbackInfo<Array>& info);
/**
* Interceptor for defineProperty requests on an object.
*
* Use `info.GetReturnValue()` to indicate whether the request was intercepted
* or not. If the definer successfully intercepts the request, i.e., if the
* request should not be further executed, call
* `info.GetReturnValue().Set(value)`. If the definer
* did not intercept the request, i.e., if the request should be handled as
* if no interceptor is present, do not not call `Set()`.
*
* \param property The name of the property for which the request was
* intercepted.
* \param desc The property descriptor which is used to define the
* property if the request is not intercepted.
* \param info Information about the intercepted request, such as
* isolate, receiver, return value, or whether running in `'use strict'` mode.
* See `PropertyCallbackInfo`.
*
* See also `ObjectTemplate::SetHandler`.
*/
typedef void (*GenericNamedPropertyDefinerCallback)(
Local<Name> property, const PropertyDescriptor& desc,
const PropertyCallbackInfo<Value>& info);
/**
* Interceptor for getOwnPropertyDescriptor requests on an object.
*
* Use `info.GetReturnValue().Set()` to set the return value of the
* intercepted request. The return value must be an object that
* can be converted to a PropertyDescriptor, e.g., a `v8::value` returned from
* `v8::Object::getOwnPropertyDescriptor`.
*
* \param property The name of the property for which the request was
* intercepted.
* \info Information about the intercepted request, such as
* isolate, receiver, return value, or whether running in `'use strict'` mode.
* See `PropertyCallbackInfo`.
*
* \note If GetOwnPropertyDescriptor is intercepted, it will
* always return true, i.e., indicate that the property was found.
*
* See also `ObjectTemplate::SetHandler`.
*/
typedef void (*GenericNamedPropertyDescriptorCallback)(
Local<Name> property, const PropertyCallbackInfo<Value>& info);
/**
* See `v8::GenericNamedPropertyGetterCallback`.
*/
typedef void (*IndexedPropertyGetterCallback)(
uint32_t index,
const PropertyCallbackInfo<Value>& info);
/**
* See `v8::GenericNamedPropertySetterCallback`.
*/
typedef void (*IndexedPropertySetterCallback)(
uint32_t index,
Local<Value> value,
const PropertyCallbackInfo<Value>& info);
/**
* See `v8::GenericNamedPropertyQueryCallback`.
*/
typedef void (*IndexedPropertyQueryCallback)(
uint32_t index,
const PropertyCallbackInfo<Integer>& info);
/**
* See `v8::GenericNamedPropertyDeleterCallback`.
*/
typedef void (*IndexedPropertyDeleterCallback)(
uint32_t index,
const PropertyCallbackInfo<Boolean>& info);
/**
* Returns an array containing the indices of the properties the indexed
* property getter intercepts.
*
* Note: The values in the array must be uint32_t.
*/
typedef void (*IndexedPropertyEnumeratorCallback)(
const PropertyCallbackInfo<Array>& info);
/**
* See `v8::GenericNamedPropertyDefinerCallback`.
*/
typedef void (*IndexedPropertyDefinerCallback)(
uint32_t index, const PropertyDescriptor& desc,
const PropertyCallbackInfo<Value>& info);
/**
* See `v8::GenericNamedPropertyDescriptorCallback`.
*/
typedef void (*IndexedPropertyDescriptorCallback)(
uint32_t index, const PropertyCallbackInfo<Value>& info);
/**
* Access type specification.
*/
enum AccessType {
ACCESS_GET,
ACCESS_SET,
ACCESS_HAS,
ACCESS_DELETE,
ACCESS_KEYS
};
/**
* Returns true if the given context should be allowed to access the given
* object.
*/
typedef bool (*AccessCheckCallback)(Local<Context> accessing_context,
Local<Object> accessed_object,
Local<Value> data);
/**
* A FunctionTemplate is used to create functions at runtime. There
* can only be one function created from a FunctionTemplate in a
* context. The lifetime of the created function is equal to the
* lifetime of the context. So in case the embedder needs to create
* temporary functions that can be collected using Scripts is
* preferred.
*
* Any modification of a FunctionTemplate after first instantiation will trigger
* a crash.
*
* A FunctionTemplate can have properties, these properties are added to the
* function object when it is created.
*
* A FunctionTemplate has a corresponding instance template which is
* used to create object instances when the function is used as a
* constructor. Properties added to the instance template are added to
* each object instance.
*
* A FunctionTemplate can have a prototype template. The prototype template
* is used to create the prototype object of the function.
*
* The following example shows how to use a FunctionTemplate:
*
* \code
* v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate);
* t->Set(isolate, "func_property", v8::Number::New(isolate, 1));
*
* v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
* proto_t->Set(isolate,
* "proto_method",
* v8::FunctionTemplate::New(isolate, InvokeCallback));
* proto_t->Set(isolate, "proto_const", v8::Number::New(isolate, 2));
*
* v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
* instance_t->SetAccessor(String::NewFromUtf8(isolate, "instance_accessor"),
* InstanceAccessorCallback);
* instance_t->SetHandler(
* NamedPropertyHandlerConfiguration(PropertyHandlerCallback));
* instance_t->Set(String::NewFromUtf8(isolate, "instance_property"),
* Number::New(isolate, 3));
*
* v8::Local<v8::Function> function = t->GetFunction();
* v8::Local<v8::Object> instance = function->NewInstance();
* \endcode
*
* Let's use "function" as the JS variable name of the function object
* and "instance" for the instance object created above. The function
* and the instance will have the following properties:
*
* \code
* func_property in function == true;
* function.func_property == 1;
*
* function.prototype.proto_method() invokes 'InvokeCallback'
* function.prototype.proto_const == 2;
*
* instance instanceof function == true;
* instance.instance_accessor calls 'InstanceAccessorCallback'
* instance.instance_property == 3;
* \endcode
*
* A FunctionTemplate can inherit from another one by calling the
* FunctionTemplate::Inherit method. The following graph illustrates
* the semantics of inheritance:
*
* \code
* FunctionTemplate Parent -> Parent() . prototype -> { }
* ^ ^
* | Inherit(Parent) | .__proto__
* | |
* FunctionTemplate Child -> Child() . prototype -> { }
* \endcode
*
* A FunctionTemplate 'Child' inherits from 'Parent', the prototype
* object of the Child() function has __proto__ pointing to the
* Parent() function's prototype object. An instance of the Child
* function has all properties on Parent's instance templates.
*
* Let Parent be the FunctionTemplate initialized in the previous
* section and create a Child FunctionTemplate by:
*
* \code
* Local<FunctionTemplate> parent = t;
* Local<FunctionTemplate> child = FunctionTemplate::New();
* child->Inherit(parent);
*
* Local<Function> child_function = child->GetFunction();
* Local<Object> child_instance = child_function->NewInstance();
* \endcode
*
* The Child function and Child instance will have the following
* properties:
*
* \code
* child_func.prototype.__proto__ == function.prototype;
* child_instance.instance_accessor calls 'InstanceAccessorCallback'
* child_instance.instance_property == 3;
* \endcode
*/
class V8_EXPORT FunctionTemplate : public Template {
public:
/** Creates a function template.*/
static Local<FunctionTemplate> New(
Isolate* isolate, FunctionCallback callback = 0,
Local<Value> data = Local<Value>(),
Local<Signature> signature = Local<Signature>(), int length = 0,
ConstructorBehavior behavior = ConstructorBehavior::kAllow,
SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
/** Get a template included in the snapshot by index. */
static MaybeLocal<FunctionTemplate> FromSnapshot(Isolate* isolate,
size_t index);
/**
* Creates a function template backed/cached by a private property.
*/
static Local<FunctionTemplate> NewWithCache(
Isolate* isolate, FunctionCallback callback,
Local<Private> cache_property, Local<Value> data = Local<Value>(),
Local<Signature> signature = Local<Signature>(), int length = 0,
SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
/** Returns the unique function instance in the current execution context.*/
V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
Local<Context> context);
/**
* Similar to Context::NewRemoteContext, this creates an instance that
* isn't backed by an actual object.
*
* The InstanceTemplate of this FunctionTemplate must have access checks with
* handlers installed.
*/
V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewRemoteInstance();
/**
* Set the call-handler callback for a FunctionTemplate. This
* callback is called whenever the function created from this
* FunctionTemplate is called.
*/
void SetCallHandler(
FunctionCallback callback, Local<Value> data = Local<Value>(),
SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
/** Set the predefined length property for the FunctionTemplate. */
void SetLength(int length);
/** Get the InstanceTemplate. */
Local<ObjectTemplate> InstanceTemplate();
/**
* Causes the function template to inherit from a parent function template.
* This means the function's prototype.__proto__ is set to the parent
* function's prototype.
**/
void Inherit(Local<FunctionTemplate> parent);
/**
* A PrototypeTemplate is the template used to create the prototype object
* of the function created by this template.
*/
Local<ObjectTemplate> PrototypeTemplate();
/**
* A PrototypeProviderTemplate is another function template whose prototype
* property is used for this template. This is mutually exclusive with setting
* a prototype template indirectly by calling PrototypeTemplate() or using
* Inherit().
**/
void SetPrototypeProviderTemplate(Local<FunctionTemplate> prototype_provider);
/**
* Set the class name of the FunctionTemplate. This is used for
* printing objects created with the function created from the
* FunctionTemplate as its constructor.
*/
void SetClassName(Local<String> name);
/**
* When set to true, no access check will be performed on the receiver of a
* function call. Currently defaults to true, but this is subject to change.
*/
void SetAcceptAnyReceiver(bool value);
/**
* Determines whether the __proto__ accessor ignores instances of
* the function template. If instances of the function template are
* ignored, __proto__ skips all instances and instead returns the
* next object in the prototype chain.
*
* Call with a value of true to make the __proto__ accessor ignore
* instances of the function template. Call with a value of false
* to make the __proto__ accessor not ignore instances of the
* function template. By default, instances of a function template
* are not ignored.
*/
void SetHiddenPrototype(bool value);
/**
* Sets the ReadOnly flag in the attributes of the 'prototype' property
* of functions created from this FunctionTemplate to true.
*/
void ReadOnlyPrototype();
/**
* Removes the prototype property from functions created from this
* FunctionTemplate.
*/
void RemovePrototype();
/**
* Returns true if the given object is an instance of this function
* template.
*/
bool HasInstance(Local<Value> object);
V8_INLINE static FunctionTemplate* Cast(Data* data);
private:
FunctionTemplate();
static void CheckCast(Data* that);
friend class Context;
friend class ObjectTemplate;
};
/**
* Configuration flags for v8::NamedPropertyHandlerConfiguration or
* v8::IndexedPropertyHandlerConfiguration.
*/
enum class PropertyHandlerFlags {
/**
* None.
*/
kNone = 0,
/**
* See ALL_CAN_READ above.
*/
kAllCanRead = 1,
/** Will not call into interceptor for properties on the receiver or prototype
* chain, i.e., only call into interceptor for properties that do not exist.
* Currently only valid for named interceptors.
*/
kNonMasking = 1 << 1,
/**
* Will not call into interceptor for symbol lookup. Only meaningful for
* named interceptors.
*/
kOnlyInterceptStrings = 1 << 2,
/**
* The getter, query, enumerator callbacks do not produce side effects.
*/
kHasNoSideEffect = 1 << 3,
};
struct NamedPropertyHandlerConfiguration {
NamedPropertyHandlerConfiguration(
/** Note: getter is required */
GenericNamedPropertyGetterCallback getter = 0,
GenericNamedPropertySetterCallback setter = 0,
GenericNamedPropertyQueryCallback query = 0,
GenericNamedPropertyDeleterCallback deleter = 0,
GenericNamedPropertyEnumeratorCallback enumerator = 0,
Local<Value> data = Local<Value>(),
PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
: getter(getter),
setter(setter),
query(query),
deleter(deleter),
enumerator(enumerator),
definer(0),
descriptor(0),
data(data),
flags(flags) {}
NamedPropertyHandlerConfiguration(
GenericNamedPropertyGetterCallback getter,
GenericNamedPropertySetterCallback setter,
GenericNamedPropertyDescriptorCallback descriptor,
GenericNamedPropertyDeleterCallback deleter,
GenericNamedPropertyEnumeratorCallback enumerator,
GenericNamedPropertyDefinerCallback definer,
Local<Value> data = Local<Value>(),
PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
: getter(getter),
setter(setter),
query(0),
deleter(deleter),
enumerator(enumerator),
definer(definer),
descriptor(descriptor),
data(data),
flags(flags) {}
GenericNamedPropertyGetterCallback getter;
GenericNamedPropertySetterCallback setter;
GenericNamedPropertyQueryCallback query;
GenericNamedPropertyDeleterCallback deleter;
GenericNamedPropertyEnumeratorCallback enumerator;
GenericNamedPropertyDefinerCallback definer;
GenericNamedPropertyDescriptorCallback descriptor;
Local<Value> data;
PropertyHandlerFlags flags;
};
struct IndexedPropertyHandlerConfiguration {
IndexedPropertyHandlerConfiguration(
/** Note: getter is required */
IndexedPropertyGetterCallback getter = 0,
IndexedPropertySetterCallback setter = 0,
IndexedPropertyQueryCallback query = 0,
IndexedPropertyDeleterCallback deleter = 0,
IndexedPropertyEnumeratorCallback enumerator = 0,
Local<Value> data = Local<Value>(),
PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
: getter(getter),
setter(setter),
query(query),
deleter(deleter),
enumerator(enumerator),
definer(0),
descriptor(0),
data(data),
flags(flags) {}
IndexedPropertyHandlerConfiguration(
IndexedPropertyGetterCallback getter,
IndexedPropertySetterCallback setter,
IndexedPropertyDescriptorCallback descriptor,
IndexedPropertyDeleterCallback deleter,
IndexedPropertyEnumeratorCallback enumerator,
IndexedPropertyDefinerCallback definer,
Local<Value> data = Local<Value>(),
PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
: getter(getter),
setter(setter),
query(0),
deleter(deleter),
enumerator(enumerator),
definer(definer),
descriptor(descriptor),
data(data),
flags(flags) {}
IndexedPropertyGetterCallback getter;
IndexedPropertySetterCallback setter;
IndexedPropertyQueryCallback query;
IndexedPropertyDeleterCallback deleter;
IndexedPropertyEnumeratorCallback enumerator;
IndexedPropertyDefinerCallback definer;
IndexedPropertyDescriptorCallback descriptor;
Local<Value> data;
PropertyHandlerFlags flags;
};
/**
* An ObjectTemplate is used to create objects at runtime.
*
* Properties added to an ObjectTemplate are added to each object
* created from the ObjectTemplate.
*/
class V8_EXPORT ObjectTemplate : public Template {
public:
/** Creates an ObjectTemplate. */
static Local<ObjectTemplate> New(
Isolate* isolate,
Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
/** Get a template included in the snapshot by index. */
static MaybeLocal<ObjectTemplate> FromSnapshot(Isolate* isolate,
size_t index);
/** Creates a new instance of this template.*/
V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context);
/**
* Sets an accessor on the object template.
*
* Whenever the property with the given name is accessed on objects
* created from this ObjectTemplate the getter and setter callbacks
* are called instead of getting and setting the property directly
* on the JavaScript object.
*
* \param name The name of the property for which an accessor is added.
* \param getter The callback to invoke when getting the property.
* \param setter The callback to invoke when setting the property.
* \param data A piece of data that will be passed to the getter and setter
* callbacks whenever they are invoked.
* \param settings Access control settings for the accessor. This is a bit
* field consisting of one of more of
* DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
* The default is to not allow cross-context access.
* ALL_CAN_READ means that all cross-context reads are allowed.
* ALL_CAN_WRITE means that all cross-context writes are allowed.
* The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
* cross-context access.
* \param attribute The attributes of the property for which an accessor
* is added.
* \param signature The signature describes valid receivers for the accessor
* and is used to perform implicit instance checks against them. If the
* receiver is incompatible (i.e. is not an instance of the constructor as
* defined by FunctionTemplate::HasInstance()), an implicit TypeError is
* thrown and no callback is invoked.
*/
void SetAccessor(
Local<String> name, AccessorGetterCallback getter,
AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
Local<AccessorSignature> signature = Local<AccessorSignature>());
void SetAccessor(
Local<Name> name, AccessorNameGetterCallback getter,
AccessorNameSetterCallback setter = 0, Local<Value> data = Local<Value>(),
AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
Local<AccessorSignature> signature = Local<AccessorSignature>());
/**
* Sets a named property handler on the object template.
*
* Whenever a property whose name is a string is accessed on objects created
* from this object template, the provided callback is invoked instead of
* accessing the property directly on the JavaScript object.
*
* SetNamedPropertyHandler() is different from SetHandler(), in
* that the latter can intercept symbol-named properties as well as
* string-named properties when called with a
* NamedPropertyHandlerConfiguration. New code should use SetHandler().
*
* \param getter The callback to invoke when getting a property.
* \param setter The callback to invoke when setting a property.
* \param query The callback to invoke to check if a property is present,
* and if present, get its attributes.
* \param deleter The callback to invoke when deleting a property.
* \param enumerator The callback to invoke to enumerate all the named
* properties of an object.
* \param data A piece of data that will be passed to the callbacks
* whenever they are invoked.
*/
V8_DEPRECATED(
"Use SetHandler(const NamedPropertyHandlerConfiguration) "
"with the kOnlyInterceptStrings flag set.",
void SetNamedPropertyHandler(
NamedPropertyGetterCallback getter,
NamedPropertySetterCallback setter = 0,
NamedPropertyQueryCallback query = 0,
NamedPropertyDeleterCallback deleter = 0,
NamedPropertyEnumeratorCallback enumerator = 0,
Local<Value> data = Local<Value>()));
/**
* Sets a named property handler on the object template.
*
* Whenever a property whose name is a string or a symbol is accessed on
* objects created from this object template, the provided callback is
* invoked instead of accessing the property directly on the JavaScript
* object.
*
* @param configuration The NamedPropertyHandlerConfiguration that defines the
* callbacks to invoke when accessing a property.
*/
void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
/**
* Sets an indexed property handler on the object template.
*
* Whenever an indexed property is accessed on objects created from
* this object template, the provided callback is invoked instead of
* accessing the property directly on the JavaScript object.
*
* \param getter The callback to invoke when getting a property.
* \param setter The callback to invoke when setting a property.
* \param query The callback to invoke to check if an object has a property.
* \param deleter The callback to invoke when deleting a property.
* \param enumerator The callback to invoke to enumerate all the indexed
* properties of an object.
* \param data A piece of data that will be passed to the callbacks
* whenever they are invoked.
*/
// TODO(dcarney): deprecate
void SetIndexedPropertyHandler(
IndexedPropertyGetterCallback getter,
IndexedPropertySetterCallback setter = 0,
IndexedPropertyQueryCallback query = 0,
IndexedPropertyDeleterCallback deleter = 0,
IndexedPropertyEnumeratorCallback enumerator = 0,
Local<Value> data = Local<Value>()) {
SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
deleter, enumerator, data));
}
/**
* Sets an indexed property handler on the object template.
*
* Whenever an indexed property is accessed on objects created from
* this object template, the provided callback is invoked instead of
* accessing the property directly on the JavaScript object.
*
* @param configuration The IndexedPropertyHandlerConfiguration that defines
* the callbacks to invoke when accessing a property.
*/
void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
/**
* Sets the callback to be used when calling instances created from
* this template as a function. If no callback is set, instances
* behave like normal JavaScript objects that cannot be called as a
* function.
*/
void SetCallAsFunctionHandler(FunctionCallback callback,
Local<Value> data = Local<Value>());
/**
* Mark object instances of the template as undetectable.
*
* In many ways, undetectable objects behave as though they are not
* there. They behave like 'undefined' in conditionals and when
* printed. However, properties can be accessed and called as on
* normal objects.
*/
void MarkAsUndetectable();
/**
* Sets access check callback on the object template and enables access
* checks.
*
* When accessing properties on instances of this object template,
* the access check callback will be called to determine whether or
* not to allow cross-context access to the properties.
*/
void SetAccessCheckCallback(AccessCheckCallback callback,
Local<Value> data = Local<Value>());
/**
* Like SetAccessCheckCallback but invokes an interceptor on failed access
* checks instead of looking up all-can-read properties. You can only use
* either this method or SetAccessCheckCallback, but not both at the same
* time.
*/
void SetAccessCheckCallbackAndHandler(
AccessCheckCallback callback,
const NamedPropertyHandlerConfiguration& named_handler,
const IndexedPropertyHandlerConfiguration& indexed_handler,
Local<Value> data = Local<Value>());
/**
* Gets the number of internal fields for objects generated from
* this template.
*/
int InternalFieldCount();
/**
* Sets the number of internal fields for objects generated from
* this template.
*/
void SetInternalFieldCount(int value);
/**
* Returns true if the object will be an immutable prototype exotic object.
*/
bool IsImmutableProto();
/**
* Makes the ObjectTemplate for an immutable prototype exotic object, with an
* immutable __proto__.
*/
void SetImmutableProto();
V8_INLINE static ObjectTemplate* Cast(Data* data);
private:
ObjectTemplate();
static Local<ObjectTemplate> New(internal::Isolate* isolate,
Local<FunctionTemplate> constructor);
static void CheckCast(Data* that);
friend class FunctionTemplate;
};
/**
* A Signature specifies which receiver is valid for a function.
*
* A receiver matches a given signature if the receiver (or any of its
* hidden prototypes) was created from the signature's FunctionTemplate, or
* from a FunctionTemplate that inherits directly or indirectly from the
* signature's FunctionTemplate.
*/
class V8_EXPORT Signature : public Data {
public:
static Local<Signature> New(
Isolate* isolate,
Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
V8_INLINE static Signature* Cast(Data* data);
private:
Signature();
static void CheckCast(Data* that);
};
/**
* An AccessorSignature specifies which receivers are valid parameters
* to an accessor callback.
*/
class V8_EXPORT AccessorSignature : public Data {
public:
static Local<AccessorSignature> New(
Isolate* isolate,
Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
V8_INLINE static AccessorSignature* Cast(Data* data);
private:
AccessorSignature();
static void CheckCast(Data* that);
};
// --- Extensions ---
class V8_EXPORT ExternalOneByteStringResourceImpl
: public String::ExternalOneByteStringResource {
public:
ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
ExternalOneByteStringResourceImpl(const char* data, size_t length)
: data_(data), length_(length) {}
const char* data() const { return data_; }
size_t length() const { return length_; }
private:
const char* data_;
size_t length_;
};
/**
* Ignore
*/
class V8_EXPORT Extension { // NOLINT
public:
// Note that the strings passed into this constructor must live as long
// as the Extension itself.
Extension(const char* name,
const char* source = 0,
int dep_count = 0,
const char** deps = 0,
int source_length = -1);
virtual ~Extension() { }
virtual Local<FunctionTemplate> GetNativeFunctionTemplate(
Isolate* isolate, Local<String> name) {
return Local<FunctionTemplate>();
}
const char* name() const { return name_; }
size_t source_length() const { return source_length_; }
const String::ExternalOneByteStringResource* source() const {
return &source_; }
int dependency_count() { return dep_count_; }
const char** dependencies() { return deps_; }
void set_auto_enable(bool value) { auto_enable_ = value; }
bool auto_enable() { return auto_enable_; }
// Disallow copying and assigning.
Extension(const Extension&) = delete;
void operator=(const Extension&) = delete;
private:
const char* name_;
size_t source_length_; // expected to initialize before source_
ExternalOneByteStringResourceImpl source_;
int dep_count_;
const char** deps_;
bool auto_enable_;
};
void V8_EXPORT RegisterExtension(Extension* extension);
// --- Statics ---
V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
V8_INLINE Local<Primitive> Null(Isolate* isolate);
V8_INLINE Local<Boolean> True(Isolate* isolate);
V8_INLINE Local<Boolean> False(Isolate* isolate);
/**
* A set of constraints that specifies the limits of the runtime's memory use.
* You must set the heap size before initializing the VM - the size cannot be
* adjusted after the VM is initialized.
*
* If you are using threads then you should hold the V8::Locker lock while
* setting the stack limit and you must set a non-default stack limit separately
* for each thread.
*
* The arguments for set_max_semi_space_size, set_max_old_space_size,
* set_max_executable_size, set_code_range_size specify limits in MB.
*
* The argument for set_max_semi_space_size_in_kb is in KB.
*/
class V8_EXPORT ResourceConstraints {
public:
ResourceConstraints();
/**
* Configures the constraints with reasonable default values based on the
* capabilities of the current device the VM is running on.
*
* \param physical_memory The total amount of physical memory on the current
* device, in bytes.
* \param virtual_memory_limit The amount of virtual memory on the current
* device, in bytes, or zero, if there is no limit.
*/
void ConfigureDefaults(uint64_t physical_memory,
uint64_t virtual_memory_limit);
// Returns the max semi-space size in MB.
V8_DEPRECATE_SOON("Use max_semi_space_size_in_kb()",
size_t max_semi_space_size()) {
return max_semi_space_size_in_kb_ / 1024;
}
// Sets the max semi-space size in MB.
V8_DEPRECATE_SOON("Use set_max_semi_space_size_in_kb(size_t limit_in_kb)",
void set_max_semi_space_size(size_t limit_in_mb)) {
max_semi_space_size_in_kb_ = limit_in_mb * 1024;
}
// Returns the max semi-space size in KB.
size_t max_semi_space_size_in_kb() const {
return max_semi_space_size_in_kb_;
}
// Sets the max semi-space size in KB.
void set_max_semi_space_size_in_kb(size_t limit_in_kb) {
max_semi_space_size_in_kb_ = limit_in_kb;
}
size_t max_old_space_size() const { return max_old_space_size_; }
void set_max_old_space_size(size_t limit_in_mb) {
max_old_space_size_ = limit_in_mb;
}
V8_DEPRECATE_SOON("max_executable_size_ is subsumed by max_old_space_size_",
size_t max_executable_size() const) {
return max_executable_size_;
}
V8_DEPRECATE_SOON("max_executable_size_ is subsumed by max_old_space_size_",
void set_max_executable_size(size_t limit_in_mb)) {
max_executable_size_ = limit_in_mb;
}
uint32_t* stack_limit() const { return stack_limit_; }
// Sets an address beyond which the VM's stack may not grow.
void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
size_t code_range_size() const { return code_range_size_; }
void set_code_range_size(size_t limit_in_mb) {
code_range_size_ = limit_in_mb;
}
size_t max_zone_pool_size() const { return max_zone_pool_size_; }
void set_max_zone_pool_size(size_t bytes) { max_zone_pool_size_ = bytes; }
private:
// max_semi_space_size_ is in KB
size_t max_semi_space_size_in_kb_;
// The remaining limits are in MB
size_t max_old_space_size_;
size_t max_executable_size_;
uint32_t* stack_limit_;
size_t code_range_size_;
size_t max_zone_pool_size_;
};
// --- Exceptions ---
typedef void (*FatalErrorCallback)(const char* location, const char* message);
typedef void (*OOMErrorCallback)(const char* location, bool is_heap_oom);
typedef void (*DcheckErrorCallback)(const char* file, int line,
const char* message);
typedef void (*MessageCallback)(Local<Message> message, Local<Value> data);
// --- Tracing ---
typedef void (*LogEventCallback)(const char* name, int event);
/**
* Create new error objects by calling the corresponding error object
* constructor with the message.
*/
class V8_EXPORT Exception {
public:
static Local<Value> RangeError(Local<String> message);
static Local<Value> ReferenceError(Local<String> message);
static Local<Value> SyntaxError(Local<String> message);
static Local<Value> TypeError(Local<String> message);
static Local<Value> Error(Local<String> message);
/**
* Creates an error message for the given exception.
* Will try to reconstruct the original stack trace from the exception value,
* or capture the current stack trace if not available.
*/
static Local<Message> CreateMessage(Isolate* isolate, Local<Value> exception);
/**
* Returns the original stack trace that was captured at the creation time
* of a given exception, or an empty handle if not available.
*/
static Local<StackTrace> GetStackTrace(Local<Value> exception);
};
// --- Counters Callbacks ---
typedef int* (*CounterLookupCallback)(const char* name);
typedef void* (*CreateHistogramCallback)(const char* name,
int min,
int max,
size_t buckets);
typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
// --- Enter/Leave Script Callback ---
typedef void (*BeforeCallEnteredCallback)(Isolate*);
typedef void (*CallCompletedCallback)(Isolate*);
typedef void (*DeprecatedCallCompletedCallback)();
/**
* HostImportModuleDynamicallyCallback is called when we require the
* embedder to load a module. This is used as part of the dynamic
* import syntax.
*
* The referrer contains metadata about the script/module that calls
* import.
*
* The specifier is the name of the module that should be imported.
*
* The embedder must compile, instantiate, evaluate the Module, and
* obtain it's namespace object.
*
* The Promise returned from this function is forwarded to userland
* JavaScript. The embedder must resolve this promise with the module
* namespace object. In case of an exception, the embedder must reject
* this promise with the exception. If the promise creation itself
* fails (e.g. due to stack overflow), the embedder must propagate
* that exception by returning an empty MaybeLocal.
*/
typedef MaybeLocal<Promise> (*HostImportModuleDynamicallyCallback)(
Local<Context> context, Local<ScriptOrModule> referrer,
Local<String> specifier);
/**
* HostInitializeImportMetaObjectCallback is called the first time import.meta
* is accessed for a module. Subsequent access will reuse the same value.
*
* The method combines two implementation-defined abstract operations into one:
* HostGetImportMetaProperties and HostFinalizeImportMeta.
*
* The embedder should use v8::Object::CreateDataProperty to add properties on
* the meta object.
*/
typedef void (*HostInitializeImportMetaObjectCallback)(Local<Context> context,
Local<Module> module,
Local<Object> meta);
/**
* PromiseHook with type kInit is called when a new promise is
* created. When a new promise is created as part of the chain in the
* case of Promise.then or in the intermediate promises created by
* Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise
* otherwise we pass undefined.
*
* PromiseHook with type kResolve is called at the beginning of
* resolve or reject function defined by CreateResolvingFunctions.
*
* PromiseHook with type kBefore is called at the beginning of the
* PromiseReactionJob.
*
* PromiseHook with type kAfter is called right at the end of the
* PromiseReactionJob.
*/
enum class PromiseHookType { kInit, kResolve, kBefore, kAfter };
typedef void (*PromiseHook)(PromiseHookType type, Local<Promise> promise,
Local<Value> parent);
// --- Promise Reject Callback ---
enum PromiseRejectEvent {
kPromiseRejectWithNoHandler = 0,
kPromiseHandlerAddedAfterReject = 1,
kPromiseRejectAfterResolved = 2,
kPromiseResolveAfterResolved = 3,
};
class PromiseRejectMessage {
public:
PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
Local<Value> value, Local<StackTrace> stack_trace)
: promise_(promise),
event_(event),
value_(value),
stack_trace_(stack_trace) {}
V8_INLINE Local<Promise> GetPromise() const { return promise_; }
V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
V8_INLINE Local<Value> GetValue() const { return value_; }
private:
Local<Promise> promise_;
PromiseRejectEvent event_;
Local<Value> value_;
Local<StackTrace> stack_trace_;
};
typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
// --- Microtasks Callbacks ---
typedef void (*MicrotasksCompletedCallback)(Isolate*);
typedef void (*MicrotaskCallback)(void* data);
/**
* Policy for running microtasks:
* - explicit: microtasks are invoked with Isolate::RunMicrotasks() method;
* - scoped: microtasks invocation is controlled by MicrotasksScope objects;
* - auto: microtasks are invoked when the script call depth decrements
* to zero.
*/
enum class MicrotasksPolicy { kExplicit, kScoped, kAuto };
/**
* This scope is used to control microtasks when kScopeMicrotasksInvocation
* is used on Isolate. In this mode every non-primitive call to V8 should be
* done inside some MicrotasksScope.
* Microtasks are executed when topmost MicrotasksScope marked as kRunMicrotasks
* exits.
* kDoNotRunMicrotasks should be used to annotate calls not intended to trigger
* microtasks.
*/
class V8_EXPORT MicrotasksScope {
public:
enum Type { kRunMicrotasks, kDoNotRunMicrotasks };
MicrotasksScope(Isolate* isolate, Type type);
~MicrotasksScope();
/**
* Runs microtasks if no kRunMicrotasks scope is currently active.
*/
static void PerformCheckpoint(Isolate* isolate);
/**
* Returns current depth of nested kRunMicrotasks scopes.
*/
static int GetCurrentDepth(Isolate* isolate);
/**
* Returns true while microtasks are being executed.
*/
static bool IsRunningMicrotasks(Isolate* isolate);
// Prevent copying.
MicrotasksScope(const MicrotasksScope&) = delete;
MicrotasksScope& operator=(const MicrotasksScope&) = delete;
private:
internal::Isolate* const isolate_;
bool run_;
};
// --- Failed Access Check Callback ---
typedef void (*FailedAccessCheckCallback)(Local<Object> target,
AccessType type,
Local<Value> data);
// --- AllowCodeGenerationFromStrings callbacks ---
/**
* Callback to check if code generation from strings is allowed. See
* Context::AllowCodeGenerationFromStrings.
*/
typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context,
Local<String> source);
// --- WebAssembly compilation callbacks ---
typedef bool (*ExtensionCallback)(const FunctionCallbackInfo<Value>&);
typedef bool (*AllowWasmCodeGenerationCallback)(Local<Context> context,
Local<String> source);
// --- Callback for APIs defined on v8-supported objects, but implemented
// by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
typedef void (*ApiImplementationCallback)(const FunctionCallbackInfo<Value>&);
// --- Garbage Collection Callbacks ---
/**
* Applications can register callback functions which will be called before and
* after certain garbage collection operations. Allocations are not allowed in
* the callback functions, you therefore cannot manipulate objects (set or
* delete properties for example) since it is possible such operations will
* result in the allocation of objects.
*/
enum GCType {
kGCTypeScavenge = 1 << 0,
kGCTypeMarkSweepCompact = 1 << 1,
kGCTypeIncrementalMarking = 1 << 2,
kGCTypeProcessWeakCallbacks = 1 << 3,
kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact |
kGCTypeIncrementalMarking | kGCTypeProcessWeakCallbacks
};
/**
* GCCallbackFlags is used to notify additional information about the GC
* callback.
* - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
* constructing retained object infos.
* - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
* - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
* is called synchronously without getting posted to an idle task.
* - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
* in a phase where V8 is trying to collect all available garbage
* (e.g., handling a low memory notification).
* - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
* trigger an idle garbage collection.
*/
enum GCCallbackFlags {
kNoGCCallbackFlags = 0,
kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
kGCCallbackFlagForced = 1 << 2,
kGCCallbackFlagSynchronousPhantomCallbackProcessing = 1 << 3,
kGCCallbackFlagCollectAllAvailableGarbage = 1 << 4,
kGCCallbackFlagCollectAllExternalMemory = 1 << 5,
kGCCallbackScheduleIdleGarbageCollection = 1 << 6,
};
typedef void (*GCCallback)(GCType type, GCCallbackFlags flags);
typedef void (*InterruptCallback)(Isolate* isolate, void* data);
/**
* This callback is invoked when the heap size is close to the heap limit and
* V8 is likely to abort with out-of-memory error.
* The callback can extend the heap limit by returning a value that is greater
* than the current_heap_limit. The initial heap limit is the limit that was
* set after heap setup.
*/
typedef size_t (*NearHeapLimitCallback)(void* data, size_t current_heap_limit,
size_t initial_heap_limit);
/**
* Collection of V8 heap information.
*
* Instances of this class can be passed to v8::V8::HeapStatistics to
* get heap statistics from V8.
*/
class V8_EXPORT HeapStatistics {
public:
HeapStatistics();
size_t total_heap_size() { return total_heap_size_; }
size_t total_heap_size_executable() { return total_heap_size_executable_; }
size_t total_physical_size() { return total_physical_size_; }
size_t total_available_size() { return total_available_size_; }
size_t used_heap_size() { return used_heap_size_; }
size_t heap_size_limit() { return heap_size_limit_; }
size_t malloced_memory() { return malloced_memory_; }
size_t peak_malloced_memory() { return peak_malloced_memory_; }
size_t number_of_native_contexts() { return number_of_native_contexts_; }
size_t number_of_detached_contexts() { return number_of_detached_contexts_; }
/**
* Returns a 0/1 boolean, which signifies whether the V8 overwrite heap
* garbage with a bit pattern.
*/
size_t does_zap_garbage() { return does_zap_garbage_; }
private:
size_t total_heap_size_;
size_t total_heap_size_executable_;
size_t total_physical_size_;
size_t total_available_size_;
size_t used_heap_size_;
size_t heap_size_limit_;
size_t malloced_memory_;
size_t peak_malloced_memory_;
bool does_zap_garbage_;
size_t number_of_native_contexts_;
size_t number_of_detached_contexts_;
friend class V8;
friend class Isolate;
};
class V8_EXPORT HeapSpaceStatistics {
public:
HeapSpaceStatistics();
const char* space_name() { return space_name_; }
size_t space_size() { return space_size_; }
size_t space_used_size() { return space_used_size_; }
size_t space_available_size() { return space_available_size_; }
size_t physical_space_size() { return physical_space_size_; }
private:
const char* space_name_;
size_t space_size_;
size_t space_used_size_;
size_t space_available_size_;
size_t physical_space_size_;
friend class Isolate;
};
class V8_EXPORT HeapObjectStatistics {
public:
HeapObjectStatistics();
const char* object_type() { return object_type_; }
const char* object_sub_type() { return object_sub_type_; }
size_t object_count() { return object_count_; }
size_t object_size() { return object_size_; }
private:
const char* object_type_;
const char* object_sub_type_;
size_t object_count_;
size_t object_size_;
friend class Isolate;
};
class V8_EXPORT HeapCodeStatistics {
public:
HeapCodeStatistics();
size_t code_and_metadata_size() { return code_and_metadata_size_; }
size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; }
private:
size_t code_and_metadata_size_;
size_t bytecode_and_metadata_size_;
friend class Isolate;
};
class RetainedObjectInfo;
/**
* FunctionEntryHook is the type of the profile entry hook called at entry to
* any generated function when function-level profiling is enabled.
*
* \param function the address of the function that's being entered.
* \param return_addr_location points to a location on stack where the machine
* return address resides. This can be used to identify the caller of
* \p function, and/or modified to divert execution when \p function exits.
*
* \note the entry hook must not cause garbage collection.
*/
typedef void (*FunctionEntryHook)(uintptr_t function,
uintptr_t return_addr_location);
/**
* A JIT code event is issued each time code is added, moved or removed.
*
* \note removal events are not currently issued.
*/
struct JitCodeEvent {
enum EventType {
CODE_ADDED,
CODE_MOVED,
CODE_REMOVED,
CODE_ADD_LINE_POS_INFO,
CODE_START_LINE_INFO_RECORDING,
CODE_END_LINE_INFO_RECORDING
};
// Definition of the code position type. The "POSITION" type means the place
// in the source code which are of interest when making stack traces to
// pin-point the source location of a stack frame as close as possible.
// The "STATEMENT_POSITION" means the place at the beginning of each
// statement, and is used to indicate possible break locations.
enum PositionType { POSITION, STATEMENT_POSITION };
// There are two different kinds of JitCodeEvents, one for JIT code generated
// by the optimizing compiler, and one for byte code generated for the
// interpreter. For JIT_CODE events, the |code_start| member of the event
// points to the beginning of jitted assembly code, while for BYTE_CODE
// events, |code_start| points to the first bytecode of the interpreted
// function.
enum CodeType { BYTE_CODE, JIT_CODE };
// Type of event.
EventType type;
CodeType code_type;
// Start of the instructions.
void* code_start;
// Size of the instructions.
size_t code_len;
// Script info for CODE_ADDED event.
Local<UnboundScript> script;
// User-defined data for *_LINE_INFO_* event. It's used to hold the source
// code line information which is returned from the
// CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
// CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
void* user_data;
struct name_t {
// Name of the object associated with the code, note that the string is not
// zero-terminated.
const char* str;
// Number of chars in str.
size_t len;
};
struct line_info_t {
// PC offset
size_t offset;
// Code position
size_t pos;
// The position type.
PositionType position_type;
};
union {
// Only valid for CODE_ADDED.
struct name_t name;
// Only valid for CODE_ADD_LINE_POS_INFO
struct line_info_t line_info;
// New location of instructions. Only valid for CODE_MOVED.
void* new_code_start;
};
};
/**
* Option flags passed to the SetRAILMode function.
* See documentation https://developers.google.com/web/tools/chrome-devtools/
* profile/evaluate-performance/rail
*/
enum RAILMode {
// Response performance mode: In this mode very low virtual machine latency
// is provided. V8 will try to avoid JavaScript execution interruptions.
// Throughput may be throttled.
PERFORMANCE_RESPONSE,
// Animation performance mode: In this mode low virtual machine latency is
// provided. V8 will try to avoid as many JavaScript execution interruptions
// as possible. Throughput may be throttled. This is the default mode.
PERFORMANCE_ANIMATION,
// Idle performance mode: The embedder is idle. V8 can complete deferred work
// in this mode.
PERFORMANCE_IDLE,
// Load performance mode: In this mode high throughput is provided. V8 may
// turn off latency optimizations.
PERFORMANCE_LOAD
};
/**
* Option flags passed to the SetJitCodeEventHandler function.
*/
enum JitCodeEventOptions {
kJitCodeEventDefault = 0,
// Generate callbacks for already existent code.
kJitCodeEventEnumExisting = 1
};
/**
* Callback function passed to SetJitCodeEventHandler.
*
* \param event code add, move or removal event.
*/
typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
/**
* Interface for iterating through all external resources in the heap.
*/
class V8_EXPORT ExternalResourceVisitor { // NOLINT
public:
virtual ~ExternalResourceVisitor() {}
virtual void VisitExternalString(Local<String> string) {}
};
/**
* Interface for iterating through all the persistent handles in the heap.
*/
class V8_EXPORT PersistentHandleVisitor { // NOLINT
public:
virtual ~PersistentHandleVisitor() {}
virtual void VisitPersistentHandle(Persistent<Value>* value,
uint16_t class_id) {}
};
/**
* Memory pressure level for the MemoryPressureNotification.
* kNone hints V8 that there is no memory pressure.
* kModerate hints V8 to speed up incremental garbage collection at the cost of
* of higher latency due to garbage collection pauses.
* kCritical hints V8 to free memory as soon as possible. Garbage collection
* pauses at this level will be large.
*/
enum class MemoryPressureLevel { kNone, kModerate, kCritical };
/**
* Interface for tracing through the embedder heap. During a v8 garbage
* collection, v8 collects hidden fields of all potential wrappers, and at the
* end of its marking phase iterates the collection and asks the embedder to
* trace through its heap and use reporter to report each JavaScript object
* reachable from any of the given wrappers.
*
* Before the first call to the TraceWrappersFrom function TracePrologue will be
* called. When the garbage collection cycle is finished, TraceEpilogue will be
* called.
*/
class V8_EXPORT EmbedderHeapTracer {
public:
enum ForceCompletionAction { FORCE_COMPLETION, DO_NOT_FORCE_COMPLETION };
struct AdvanceTracingActions {
explicit AdvanceTracingActions(ForceCompletionAction force_completion_)
: force_completion(force_completion_) {}
ForceCompletionAction force_completion;
};
/**
* Called by v8 to register internal fields of found wrappers.
*
* The embedder is expected to store them somewhere and trace reachable
* wrappers from them when called through |AdvanceTracing|.
*/
virtual void RegisterV8References(
const std::vector<std::pair<void*, void*> >& embedder_fields) = 0;
/**
* Called at the beginning of a GC cycle.
*/
virtual void TracePrologue() = 0;
/**
* Called to to make a tracing step in the embedder.
*
* The embedder is expected to trace its heap starting from wrappers reported
* by RegisterV8References method, and report back all reachable wrappers.
* Furthermore, the embedder is expected to stop tracing by the given
* deadline.
*
* Returns true if there is still work to do.
*/
virtual bool AdvanceTracing(double deadline_in_ms,
AdvanceTracingActions actions) = 0;
/**
* Called at the end of a GC cycle.
*
* Note that allocation is *not* allowed within |TraceEpilogue|.
*/
virtual void TraceEpilogue() = 0;
/**
* Called upon entering the final marking pause. No more incremental marking
* steps will follow this call.
*/
virtual void EnterFinalPause() = 0;
/**
* Called when tracing is aborted.
*
* The embedder is expected to throw away all intermediate data and reset to
* the initial state.
*/
virtual void AbortTracing() = 0;
/**
* Returns the number of wrappers that are still to be traced by the embedder.
*/
virtual size_t NumberOfWrappersToTrace() { return 0; }
protected:
virtual ~EmbedderHeapTracer() = default;
};
/**
* Callback and supporting data used in SnapshotCreator to implement embedder
* logic to serialize internal fields.
*/
struct SerializeInternalFieldsCallback {
typedef StartupData (*CallbackFunction)(Local<Object> holder, int index,
void* data);
SerializeInternalFieldsCallback(CallbackFunction function = nullptr,
void* data_arg = nullptr)
: callback(function), data(data_arg) {}
CallbackFunction callback;
void* data;
};
// Note that these fields are called "internal fields" in the API and called
// "embedder fields" within V8.
typedef SerializeInternalFieldsCallback SerializeEmbedderFieldsCallback;
/**
* Callback and supporting data used to implement embedder logic to deserialize
* internal fields.
*/
struct DeserializeInternalFieldsCallback {
typedef void (*CallbackFunction)(Local<Object> holder, int index,
StartupData payload, void* data);
DeserializeInternalFieldsCallback(CallbackFunction function = nullptr,
void* data_arg = nullptr)
: callback(function), data(data_arg) {}
void (*callback)(Local<Object> holder, int index, StartupData payload,
void* data);
void* data;
};
typedef DeserializeInternalFieldsCallback DeserializeEmbedderFieldsCallback;
/**
* Isolate represents an isolated instance of the V8 engine. V8 isolates have
* completely separate states. Objects from one isolate must not be used in
* other isolates. The embedder can create multiple isolates and use them in
* parallel in multiple threads. An isolate can be entered by at most one
* thread at any given time. The Locker/Unlocker API must be used to
* synchronize.
*/
class V8_EXPORT Isolate {
public:
/**
* Initial configuration parameters for a new Isolate.
*/
struct CreateParams {
CreateParams()
: entry_hook(nullptr),
code_event_handler(nullptr),
snapshot_blob(nullptr),
counter_lookup_callback(nullptr),
create_histogram_callback(nullptr),
add_histogram_sample_callback(nullptr),
array_buffer_allocator(nullptr),
external_references(nullptr),
allow_atomics_wait(true) {}
/**
* The optional entry_hook allows the host application to provide the
* address of a function that's invoked on entry to every V8-generated
* function. Note that entry_hook is invoked at the very start of each
* generated function.
* An entry_hook can only be provided in no-snapshot builds; in snapshot
* builds it must be nullptr.
*/
FunctionEntryHook entry_hook;
/**
* Allows the host application to provide the address of a function that is
* notified each time code is added, moved or removed.
*/
JitCodeEventHandler code_event_handler;
/**
* ResourceConstraints to use for the new Isolate.
*/
ResourceConstraints constraints;
/**
* Explicitly specify a startup snapshot blob. The embedder owns the blob.
*/
StartupData* snapshot_blob;
/**
* Enables the host application to provide a mechanism for recording
* statistics counters.
*/
CounterLookupCallback counter_lookup_callback;
/**
* Enables the host application to provide a mechanism for recording
* histograms. The CreateHistogram function returns a
* histogram which will later be passed to the AddHistogramSample
* function.
*/
CreateHistogramCallback create_histogram_callback;
AddHistogramSampleCallback add_histogram_sample_callback;
/**
* The ArrayBuffer::Allocator to use for allocating and freeing the backing
* store of ArrayBuffers.
*/
ArrayBuffer::Allocator* array_buffer_allocator;
/**
* Specifies an optional nullptr-terminated array of raw addresses in the
* embedder that V8 can match against during serialization and use for
* deserialization. This array and its content must stay valid for the
* entire lifetime of the isolate.
*/
const intptr_t* external_references;
/**
* Whether calling Atomics.wait (a function that may block) is allowed in
* this isolate. This can also be configured via SetAllowAtomicsWait.
*/
bool allow_atomics_wait;
};
/**
* Stack-allocated class which sets the isolate for all operations
* executed within a local scope.
*/
class V8_EXPORT Scope {
public:
explicit Scope(Isolate* isolate) : isolate_(isolate) {
isolate->Enter();
}
~Scope() { isolate_->Exit(); }
// Prevent copying of Scope objects.
Scope(const Scope&) = delete;
Scope& operator=(const Scope&) = delete;
private:
Isolate* const isolate_;
};
/**
* Assert that no Javascript code is invoked.
*/
class V8_EXPORT DisallowJavascriptExecutionScope {
public:
enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
~DisallowJavascriptExecutionScope();
// Prevent copying of Scope objects.
DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&) =
delete;
DisallowJavascriptExecutionScope& operator=(
const DisallowJavascriptExecutionScope&) = delete;
private:
bool on_failure_;
void* internal_;
};
/**
* Introduce exception to DisallowJavascriptExecutionScope.
*/
class V8_EXPORT AllowJavascriptExecutionScope {
public:
explicit AllowJavascriptExecutionScope(Isolate* isolate);
~AllowJavascriptExecutionScope();
// Prevent copying of Scope objects.
AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&) =
delete;
AllowJavascriptExecutionScope& operator=(
const AllowJavascriptExecutionScope&) = delete;
private:
void* internal_throws_;
void* internal_assert_;
};
/**
* Do not run microtasks while this scope is active, even if microtasks are
* automatically executed otherwise.
*/
class V8_EXPORT SuppressMicrotaskExecutionScope {
public:
explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
~SuppressMicrotaskExecutionScope();
// Prevent copying of Scope objects.
SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&) =
delete;
SuppressMicrotaskExecutionScope& operator=(
const SuppressMicrotaskExecutionScope&) = delete;
private:
internal::Isolate* const isolate_;
};
/**
* This scope allows terminations inside direct V8 API calls and forbid them
* inside any recursice API calls without explicit SafeForTerminationScope.
*/
class V8_EXPORT SafeForTerminationScope {
public:
explicit SafeForTerminationScope(v8::Isolate* isolate);
~SafeForTerminationScope();
// Prevent copying of Scope objects.
SafeForTerminationScope(const SafeForTerminationScope&) = delete;
SafeForTerminationScope& operator=(const SafeForTerminationScope&) = delete;
private:
internal::Isolate* isolate_;
bool prev_value_;
};
/**
* Types of garbage collections that can be requested via
* RequestGarbageCollectionForTesting.
*/
enum GarbageCollectionType {
kFullGarbageCollection,
kMinorGarbageCollection
};
/**
* Features reported via the SetUseCounterCallback callback. Do not change
* assigned numbers of existing items; add new features to the end of this
* list.
*/
enum UseCounterFeature {
kUseAsm = 0,
kBreakIterator = 1,
kLegacyConst = 2,
kMarkDequeOverflow = 3,
kStoreBufferOverflow = 4,
kSlotsBufferOverflow = 5,
kObjectObserve = 6,
kForcedGC = 7,
kSloppyMode = 8,
kStrictMode = 9,
kStrongMode = 10,
kRegExpPrototypeStickyGetter = 11,
kRegExpPrototypeToString = 12,
kRegExpPrototypeUnicodeGetter = 13,
kIntlV8Parse = 14,
kIntlPattern = 15,
kIntlResolved = 16,
kPromiseChain = 17,
kPromiseAccept = 18,
kPromiseDefer = 19,
kHtmlCommentInExternalScript = 20,
kHtmlComment = 21,
kSloppyModeBlockScopedFunctionRedefinition = 22,
kForInInitializer = 23,
kArrayProtectorDirtied = 24,
kArraySpeciesModified = 25,
kArrayPrototypeConstructorModified = 26,
kArrayInstanceProtoModified = 27,
kArrayInstanceConstructorModified = 28,
kLegacyFunctionDeclaration = 29,
kRegExpPrototypeSourceGetter = 30,
kRegExpPrototypeOldFlagGetter = 31,
kDecimalWithLeadingZeroInStrictMode = 32,
kLegacyDateParser = 33,
kDefineGetterOrSetterWouldThrow = 34,
kFunctionConstructorReturnedUndefined = 35,
kAssigmentExpressionLHSIsCallInSloppy = 36,
kAssigmentExpressionLHSIsCallInStrict = 37,
kPromiseConstructorReturnedUndefined = 38,
kConstructorNonUndefinedPrimitiveReturn = 39,
kLabeledExpressionStatement = 40,
kLineOrParagraphSeparatorAsLineTerminator = 41,
kIndexAccessor = 42,
kErrorCaptureStackTrace = 43,
kErrorPrepareStackTrace = 44,
kErrorStackTraceLimit = 45,
kWebAssemblyInstantiation = 46,
kDeoptimizerDisableSpeculation = 47,
kArrayPrototypeSortJSArrayModifiedPrototype = 48,
// If you add new values here, you'll also need to update Chromium's:
// web_feature.mojom, UseCounterCallback.cpp, and enums.xml. V8 changes to
// this list need to be landed first, then changes on the Chromium side.
kUseCounterFeatureCount // This enum value must be last.
};
enum MessageErrorLevel {
kMessageLog = (1 << 0),
kMessageDebug = (1 << 1),
kMessageInfo = (1 << 2),
kMessageError = (1 << 3),
kMessageWarning = (1 << 4),
kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError |
kMessageWarning,
};
typedef void (*UseCounterCallback)(Isolate* isolate,
UseCounterFeature feature);
/**
* Allocates a new isolate but does not initialize it. Does not change the
* currently entered isolate.
*
* Only Isolate::GetData() and Isolate::SetData(), which access the
* embedder-controlled parts of the isolate, are allowed to be called on the
* uninitialized isolate. To initialize the isolate, call
* Isolate::Initialize().
*
* When an isolate is no longer used its resources should be freed
* by calling Dispose(). Using the delete operator is not allowed.
*
* V8::Initialize() must have run prior to this.
*/
static Isolate* Allocate();
/**
* Initialize an Isolate previously allocated by Isolate::Allocate().
*/
static void Initialize(Isolate* isolate, const CreateParams& params);
/**
* Creates a new isolate. Does not change the currently entered
* isolate.
*
* When an isolate is no longer used its resources should be freed
* by calling Dispose(). Using the delete operator is not allowed.
*
* V8::Initialize() must have run prior to this.
*/
static Isolate* New(const CreateParams& params);
/**
* Returns the entered isolate for the current thread or NULL in
* case there is no current isolate.
*
* This method must not be invoked before V8::Initialize() was invoked.
*/
static Isolate* GetCurrent();
/**
* Custom callback used by embedders to help V8 determine if it should abort
* when it throws and no internal handler is predicted to catch the
* exception. If --abort-on-uncaught-exception is used on the command line,
* then V8 will abort if either:
* - no custom callback is set.
* - the custom callback set returns true.
* Otherwise, the custom callback will not be called and V8 will not abort.
*/
typedef bool (*AbortOnUncaughtExceptionCallback)(Isolate*);
void SetAbortOnUncaughtExceptionCallback(
AbortOnUncaughtExceptionCallback callback);
/**
* This specifies the callback called by the upcoming dynamic
* import() language feature to load modules.
*/
void SetHostImportModuleDynamicallyCallback(
HostImportModuleDynamicallyCallback callback);
/**
* This specifies the callback called by the upcoming importa.meta
* language feature to retrieve host-defined meta data for a module.
*/
void SetHostInitializeImportMetaObjectCallback(
HostInitializeImportMetaObjectCallback callback);
/**
* Optional notification that the system is running low on memory.
* V8 uses these notifications to guide heuristics.
* It is allowed to call this function from another thread while
* the isolate is executing long running JavaScript code.
*/
void MemoryPressureNotification(MemoryPressureLevel level);
/**
* Methods below this point require holding a lock (using Locker) in
* a multi-threaded environment.
*/
/**
* Sets this isolate as the entered one for the current thread.
* Saves the previously entered one (if any), so that it can be
* restored when exiting. Re-entering an isolate is allowed.
*/
void Enter();
/**
* Exits this isolate by restoring the previously entered one in the
* current thread. The isolate may still stay the same, if it was
* entered more than once.
*
* Requires: this == Isolate::GetCurrent().
*/
void Exit();
/**
* Disposes the isolate. The isolate must not be entered by any
* thread to be disposable.
*/
void Dispose();
/**
* Dumps activated low-level V8 internal stats. This can be used instead
* of performing a full isolate disposal.
*/
void DumpAndResetStats();
/**
* Discards all V8 thread-specific data for the Isolate. Should be used
* if a thread is terminating and it has used an Isolate that will outlive
* the thread -- all thread-specific data for an Isolate is discarded when
* an Isolate is disposed so this call is pointless if an Isolate is about
* to be Disposed.
*/
void DiscardThreadSpecificMetadata();
/**
* Associate embedder-specific data with the isolate. |slot| has to be
* between 0 and GetNumberOfDataSlots() - 1.
*/
V8_INLINE void SetData(uint32_t slot, void* data);
/**
* Retrieve embedder-specific data from the isolate.
* Returns NULL if SetData has never been called for the given |slot|.
*/
V8_INLINE void* GetData(uint32_t slot);
/**
* Returns the maximum number of available embedder data slots. Valid slots
* are in the range of 0 - GetNumberOfDataSlots() - 1.
*/
V8_INLINE static uint32_t GetNumberOfDataSlots();
/**
* Return data that was previously attached to the isolate snapshot via
* SnapshotCreator, and removes the reference to it.
* Repeated call with the same index returns an empty MaybeLocal.
*/
template <class T>
V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
/**
* Get statistics about the heap memory usage.
*/
void GetHeapStatistics(HeapStatistics* heap_statistics);
/**
* Returns the number of spaces in the heap.
*/
size_t NumberOfHeapSpaces();
/**
* Get the memory usage of a space in the heap.
*
* \param space_statistics The HeapSpaceStatistics object to fill in
* statistics.
* \param index The index of the space to get statistics from, which ranges
* from 0 to NumberOfHeapSpaces() - 1.
* \returns true on success.
*/
bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
size_t index);
/**
* Returns the number of types of objects tracked in the heap at GC.
*/
size_t NumberOfTrackedHeapObjectTypes();
/**
* Get statistics about objects in the heap.
*
* \param object_statistics The HeapObjectStatistics object to fill in
* statistics of objects of given type, which were live in the previous GC.
* \param type_index The index of the type of object to fill details about,
* which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
* \returns true on success.
*/
bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
size_t type_index);
/**
* Get statistics about code and its metadata in the heap.
*
* \param object_statistics The HeapCodeStatistics object to fill in
* statistics of code, bytecode and their metadata.
* \returns true on success.
*/
bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics);
/**
* Get a call stack sample from the isolate.
* \param state Execution state.
* \param frames Caller allocated buffer to store stack frames.
* \param frames_limit Maximum number of frames to capture. The buffer must
* be large enough to hold the number of frames.
* \param sample_info The sample info is filled up by the function
* provides number of actual captured stack frames and
* the current VM state.
* \note GetStackSample should only be called when the JS thread is paused or
* interrupted. Otherwise the behavior is undefined.
*/
void GetStackSample(const RegisterState& state, void** frames,
size_t frames_limit, SampleInfo* sample_info);
/**
* Adjusts the amount of registered external memory. Used to give V8 an
* indication of the amount of externally allocated memory that is kept alive
* by JavaScript objects. V8 uses this to decide when to perform global
* garbage collections. Registering externally allocated memory will trigger
* global garbage collections more often than it would otherwise in an attempt
* to garbage collect the JavaScript objects that keep the externally
* allocated memory alive.
*
* \param change_in_bytes the change in externally allocated memory that is
* kept alive by JavaScript objects.
* \returns the adjusted value.
*/
V8_INLINE int64_t
AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
/**
* Returns the number of phantom handles without callbacks that were reset
* by the garbage collector since the last call to this function.
*/
size_t NumberOfPhantomHandleResetsSinceLastCall();
/**
* Returns heap profiler for this isolate. Will return NULL until the isolate
* is initialized.
*/
HeapProfiler* GetHeapProfiler();
/**
* Returns CPU profiler for this isolate. Will return NULL unless the isolate
* is initialized. It is the embedder's responsibility to stop all CPU
* profiling activities if it has started any.
*/
V8_DEPRECATED("CpuProfiler should be created with CpuProfiler::New call.",
CpuProfiler* GetCpuProfiler());
/**
* Tells the CPU profiler whether the embedder is idle.
*/
void SetIdle(bool is_idle);
/** Returns true if this isolate has a current context. */
bool InContext();
/**
* Returns the context of the currently running JavaScript, or the context
* on the top of the stack if no JavaScript is running.
*/
Local<Context> GetCurrentContext();
/**
* Returns the context of the calling JavaScript code. That is the
* context of the top-most JavaScript frame. If there are no
* JavaScript frames an empty handle is returned.
*/
V8_DEPRECATED(
"Calling context concept is not compatible with tail calls, and will be "
"removed.",
Local<Context> GetCallingContext());
/** Returns the last context entered through V8's C++ API. */
Local<Context> GetEnteredContext();
/**
* Returns either the last context entered through V8's C++ API, or the
* context of the currently running microtask while processing microtasks.
* If a context is entered while executing a microtask, that context is
* returned.
*/
Local<Context> GetEnteredOrMicrotaskContext();
/**
* Returns the Context that corresponds to the Incumbent realm in HTML spec.
* https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
*/
Local<Context> GetIncumbentContext();
/**
* Schedules an exception to be thrown when returning to JavaScript. When an
* exception has been scheduled it is illegal to invoke any JavaScript
* operation; the caller must return immediately and only after the exception
* has been handled does it become legal to invoke JavaScript operations.
*/
Local<Value> ThrowException(Local<Value> exception);
typedef void (*GCCallback)(Isolate* isolate, GCType type,
GCCallbackFlags flags);
typedef void (*GCCallbackWithData)(Isolate* isolate, GCType type,
GCCallbackFlags flags, void* data);
/**
* Enables the host application to receive a notification before a
* garbage collection. Allocations are allowed in the callback function,
* but the callback is not re-entrant: if the allocation inside it will
* trigger the garbage collection, the callback won't be called again.
* It is possible to specify the GCType filter for your callback. But it is
* not possible to register the same callback function two times with
* different GCType filters.
*/
void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
GCType gc_type_filter = kGCTypeAll);
void AddGCPrologueCallback(GCCallback callback,
GCType gc_type_filter = kGCTypeAll);
/**
* This function removes callback which was installed by
* AddGCPrologueCallback function.
*/
void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
void RemoveGCPrologueCallback(GCCallback callback);
/**
* Sets the embedder heap tracer for the isolate.
*/
void SetEmbedderHeapTracer(EmbedderHeapTracer* tracer);
/**
* Enables the host application to receive a notification after a
* garbage collection. Allocations are allowed in the callback function,
* but the callback is not re-entrant: if the allocation inside it will
* trigger the garbage collection, the callback won't be called again.
* It is possible to specify the GCType filter for your callback. But it is
* not possible to register the same callback function two times with
* different GCType filters.
*/
void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr,
GCType gc_type_filter = kGCTypeAll);
void AddGCEpilogueCallback(GCCallback callback,
GCType gc_type_filter = kGCTypeAll);
/**
* This function removes callback which was installed by
* AddGCEpilogueCallback function.
*/
void RemoveGCEpilogueCallback(GCCallbackWithData callback,
void* data = nullptr);
void RemoveGCEpilogueCallback(GCCallback callback);
typedef size_t (*GetExternallyAllocatedMemoryInBytesCallback)();
/**
* Set the callback that tells V8 how much memory is currently allocated
* externally of the V8 heap. Ideally this memory is somehow connected to V8
* objects and may get freed-up when the corresponding V8 objects get
* collected by a V8 garbage collection.
*/
void SetGetExternallyAllocatedMemoryInBytesCallback(
GetExternallyAllocatedMemoryInBytesCallback callback);
/**
* Forcefully terminate the current thread of JavaScript execution
* in the given isolate.
*
* This method can be used by any thread even if that thread has not
* acquired the V8 lock with a Locker object.
*/
void TerminateExecution();
/**
* Is V8 terminating JavaScript execution.
*
* Returns true if JavaScript execution is currently terminating
* because of a call to TerminateExecution. In that case there are
* still JavaScript frames on the stack and the termination
* exception is still active.
*/
bool IsExecutionTerminating();
/**
* Resume execution capability in the given isolate, whose execution
* was previously forcefully terminated using TerminateExecution().
*
* When execution is forcefully terminated using TerminateExecution(),
* the isolate can not resume execution until all JavaScript frames
* have propagated the uncatchable exception which is generated. This
* method allows the program embedding the engine to handle the
* termination event and resume execution capability, even if
* JavaScript frames remain on the stack.
*
* This method can be used by any thread even if that thread has not
* acquired the V8 lock with a Locker object.
*/
void CancelTerminateExecution();
/**
* Request V8 to interrupt long running JavaScript code and invoke
* the given |callback| passing the given |data| to it. After |callback|
* returns control will be returned to the JavaScript code.
* There may be a number of interrupt requests in flight.
* Can be called from another thread without acquiring a |Locker|.
* Registered |callback| must not reenter interrupted Isolate.
*/
void RequestInterrupt(InterruptCallback callback, void* data);
/**
* Request garbage collection in this Isolate. It is only valid to call this
* function if --expose_gc was specified.
*
* This should only be used for testing purposes and not to enforce a garbage
* collection schedule. It has strong negative impact on the garbage
* collection performance. Use IdleNotificationDeadline() or
* LowMemoryNotification() instead to influence the garbage collection
* schedule.
*/
void RequestGarbageCollectionForTesting(GarbageCollectionType type);
/**
* Set the callback to invoke for logging event.
*/
void SetEventLogger(LogEventCallback that);
/**
* Adds a callback to notify the host application right before a script
* is about to run. If a script re-enters the runtime during executing, the
* BeforeCallEnteredCallback is invoked for each re-entrance.
* Executing scripts inside the callback will re-trigger the callback.
*/
void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
/**
* Removes callback that was installed by AddBeforeCallEnteredCallback.
*/
void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
/**
* Adds a callback to notify the host application when a script finished
* running. If a script re-enters the runtime during executing, the
* CallCompletedCallback is only invoked when the outer-most script
* execution ends. Executing scripts inside the callback do not trigger
* further callbacks.
*/
void AddCallCompletedCallback(CallCompletedCallback callback);
V8_DEPRECATED(
"Use callback with parameter",
void AddCallCompletedCallback(DeprecatedCallCompletedCallback callback));
/**
* Removes callback that was installed by AddCallCompletedCallback.
*/
void RemoveCallCompletedCallback(CallCompletedCallback callback);
V8_DEPRECATED("Use callback with parameter",
void RemoveCallCompletedCallback(
DeprecatedCallCompletedCallback callback));
/**
* Set the PromiseHook callback for various promise lifecycle
* events.
*/
void SetPromiseHook(PromiseHook hook);
/**
* Set callback to notify about promise reject with no handler, or
* revocation of such a previous notification once the handler is added.
*/
void SetPromiseRejectCallback(PromiseRejectCallback callback);
/**
* Runs the Microtask Work Queue until empty
* Any exceptions thrown by microtask callbacks are swallowed.
*/
void RunMicrotasks();
/**
* Enqueues the callback to the Microtask Work Queue
*/
void EnqueueMicrotask(Local<Function> microtask);
/**
* Enqueues the callback to the Microtask Work Queue
*/
void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr);
/**
* Controls how Microtasks are invoked. See MicrotasksPolicy for details.
*/
void SetMicrotasksPolicy(MicrotasksPolicy policy);
V8_DEPRECATED("Use SetMicrotasksPolicy",
void SetAutorunMicrotasks(bool autorun));
/**
* Returns the policy controlling how Microtasks are invoked.
*/
MicrotasksPolicy GetMicrotasksPolicy() const;
V8_DEPRECATED("Use GetMicrotasksPolicy", bool WillAutorunMicrotasks() const);
/**
* Adds a callback to notify the host application after
* microtasks were run. The callback is triggered by explicit RunMicrotasks
* call or automatic microtasks execution (see SetAutorunMicrotasks).
*
* Callback will trigger even if microtasks were attempted to run,
* but the microtasks queue was empty and no single microtask was actually
* executed.
*
* Executing scriptsinside the callback will not re-trigger microtasks and
* the callback.
*/
void AddMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
/**
* Removes callback that was installed by AddMicrotasksCompletedCallback.
*/
void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
/**
* Sets a callback for counting the number of times a feature of V8 is used.
*/
void SetUseCounterCallback(UseCounterCallback callback);
/**
* Enables the host application to provide a mechanism for recording
* statistics counters.
*/
void SetCounterFunction(CounterLookupCallback);
/**
* Enables the host application to provide a mechanism for recording
* histograms. The CreateHistogram function returns a
* histogram which will later be passed to the AddHistogramSample
* function.
*/
void SetCreateHistogramFunction(CreateHistogramCallback);
void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
/**
* Optional notification that the embedder is idle.
* V8 uses the notification to perform garbage collection.
* This call can be used repeatedly if the embedder remains idle.
* Returns true if the embedder should stop calling IdleNotificationDeadline
* until real work has been done. This indicates that V8 has done
* as much cleanup as it will be able to do.
*
* The deadline_in_seconds argument specifies the deadline V8 has to finish
* garbage collection work. deadline_in_seconds is compared with
* MonotonicallyIncreasingTime() and should be based on the same timebase as
* that function. There is no guarantee that the actual work will be done
* within the time limit.
*/
bool IdleNotificationDeadline(double deadline_in_seconds);
/**
* Optional notification that the system is running low on memory.
* V8 uses these notifications to attempt to free memory.
*/
void LowMemoryNotification();
/**
* Optional notification that a context has been disposed. V8 uses
* these notifications to guide the GC heuristic. Returns the number
* of context disposals - including this one - since the last time
* V8 had a chance to clean up.
*
* The optional parameter |dependant_context| specifies whether the disposed
* context was depending on state from other contexts or not.
*/
int ContextDisposedNotification(bool dependant_context = true);
/**
* Optional notification that the isolate switched to the foreground.
* V8 uses these notifications to guide heuristics.
*/
void IsolateInForegroundNotification();
/**
* Optional notification that the isolate switched to the background.
* V8 uses these notifications to guide heuristics.
*/
void IsolateInBackgroundNotification();
/**
* Optional notification to tell V8 the current performance requirements
* of the embedder based on RAIL.
* V8 uses these notifications to guide heuristics.
* This is an unfinished experimental feature. Semantics and implementation
* may change frequently.
*/
void SetRAILMode(RAILMode rail_mode);
/**
* Optional notification to tell V8 the current isolate is used for debugging
* and requires higher heap limit.
*/
void IncreaseHeapLimitForDebugging();
/**
* Restores the original heap limit after IncreaseHeapLimitForDebugging().
*/
void RestoreOriginalHeapLimit();
/**
* Returns true if the heap limit was increased for debugging and the
* original heap limit was not restored yet.
*/
bool IsHeapLimitIncreasedForDebugging();
/**
* Allows the host application to provide the address of a function that is
* notified each time code is added, moved or removed.
*
* \param options options for the JIT code event handler.
* \param event_handler the JIT code event handler, which will be invoked
* each time code is added, moved or removed.
* \note \p event_handler won't get notified of existent code.
* \note since code removal notifications are not currently issued, the
* \p event_handler may get notifications of code that overlaps earlier
* code notifications. This happens when code areas are reused, and the
* earlier overlapping code areas should therefore be discarded.
* \note the events passed to \p event_handler and the strings they point to
* are not guaranteed to live past each call. The \p event_handler must
* copy strings and other parameters it needs to keep around.
* \note the set of events declared in JitCodeEvent::EventType is expected to
* grow over time, and the JitCodeEvent structure is expected to accrue
* new members. The \p event_handler function must ignore event codes
* it does not recognize to maintain future compatibility.
* \note Use Isolate::CreateParams to get events for code executed during
* Isolate setup.
*/
void SetJitCodeEventHandler(JitCodeEventOptions options,
JitCodeEventHandler event_handler);
/**
* Modifies the stack limit for this Isolate.
*
* \param stack_limit An address beyond which the Vm's stack may not grow.
*
* \note If you are using threads then you should hold the V8::Locker lock
* while setting the stack limit and you must set a non-default stack
* limit separately for each thread.
*/
void SetStackLimit(uintptr_t stack_limit);
/**
* Returns a memory range that can potentially contain jitted code.
*
* On Win64, embedders are advised to install function table callbacks for
* these ranges, as default SEH won't be able to unwind through jitted code.
*
* The first page of the code range is reserved for the embedder and is
* committed, writable, and executable.
*
* Might be empty on other platforms.
*
* https://code.google.com/p/v8/issues/detail?id=3598
*/
void GetCodeRange(void** start, size_t* length_in_bytes);
/** Set the callback to invoke in case of fatal errors. */
void SetFatalErrorHandler(FatalErrorCallback that);
/** Set the callback to invoke in case of OOM errors. */
void SetOOMErrorHandler(OOMErrorCallback that);
/**
* Add a callback to invoke in case the heap size is close to the heap limit.
* If multiple callbacks are added, only the most recently added callback is
* invoked.
*/
void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data);
/**
* Remove the given callback and restore the heap limit to the
* given limit. If the given limit is zero, then it is ignored.
* If the current heap size is greater than the given limit,
* then the heap limit is restored to the minimal limit that
* is possible for the current heap size.
*/
void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback,
size_t heap_limit);
/**
* Set the callback to invoke to check if code generation from
* strings should be allowed.
*/
void SetAllowCodeGenerationFromStringsCallback(
AllowCodeGenerationFromStringsCallback callback);
/**
* Set the callback to invoke to check if wasm code generation should
* be allowed.
*/
void SetAllowWasmCodeGenerationCallback(
AllowWasmCodeGenerationCallback callback);
/**
* Embedder over{ride|load} injection points for wasm APIs. The expectation
* is that the embedder sets them at most once.
*/
void SetWasmModuleCallback(ExtensionCallback callback);
void SetWasmInstanceCallback(ExtensionCallback callback);
void SetWasmCompileStreamingCallback(ApiImplementationCallback callback);
/**
* Check if V8 is dead and therefore unusable. This is the case after
* fatal errors such as out-of-memory situations.
*/
bool IsDead();
/**
* Adds a message listener (errors only).
*
* The same message listener can be added more than once and in that
* case it will be called more than once for each message.
*
* If data is specified, it will be passed to the callback when it is called.
* Otherwise, the exception object will be passed to the callback instead.
*/
bool AddMessageListener(MessageCallback that,
Local<Value> data = Local<Value>());
/**
* Adds a message listener.
*
* The same message listener can be added more than once and in that
* case it will be called more than once for each message.
*
* If data is specified, it will be passed to the callback when it is called.
* Otherwise, the exception object will be passed to the callback instead.
*
* A listener can listen for particular error levels by providing a mask.
*/
bool AddMessageListenerWithErrorLevel(MessageCallback that,
int message_levels,
Local<Value> data = Local<Value>());
/**
* Remove all message listeners from the specified callback function.
*/
void RemoveMessageListeners(MessageCallback that);
/** Callback function for reporting failed access checks.*/
void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
/**
* Tells V8 to capture current stack trace when uncaught exception occurs
* and report it to the message listeners. The option is off by default.
*/
void SetCaptureStackTraceForUncaughtExceptions(
bool capture, int frame_limit = 10,
StackTrace::StackTraceOptions options = StackTrace::kOverview);
/**
* Iterates through all external resources referenced from current isolate
* heap. GC is not invoked prior to iterating, therefore there is no
* guarantee that visited objects are still alive.
*/
void VisitExternalResources(ExternalResourceVisitor* visitor);
/**
* Iterates through all the persistent handles in the current isolate's heap
* that have class_ids.
*/
void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
/**
* Iterates through all the persistent handles in the current isolate's heap
* that have class_ids and are candidates to be marked as partially dependent
* handles. This will visit handles to young objects created since the last
* garbage collection but is free to visit an arbitrary superset of these
* objects.
*/
void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
/**
* Iterates through all the persistent handles in the current isolate's heap
* that have class_ids and are weak to be marked as inactive if there is no
* pending activity for the handle.
*/
void VisitWeakHandles(PersistentHandleVisitor* visitor);
/**
* Check if this isolate is in use.
* True if at least one thread Enter'ed this isolate.
*/
bool IsInUse();
/**
* Set whether calling Atomics.wait (a function that may block) is allowed in
* this isolate. This can also be configured via
* CreateParams::allow_atomics_wait.
*/
void SetAllowAtomicsWait(bool allow);
Isolate() = delete;
~Isolate() = delete;
Isolate(const Isolate&) = delete;
Isolate& operator=(const Isolate&) = delete;
// Deleting operator new and delete here is allowed as ctor and dtor is also
// deleted.
void* operator new(size_t size) = delete;
void* operator new[](size_t size) = delete;
void operator delete(void*, size_t) = delete;
void operator delete[](void*, size_t) = delete;
private:
template <class K, class V, class Traits>
friend class PersistentValueMapBase;
internal::Object** GetDataFromSnapshotOnce(size_t index);
void ReportExternalAllocationLimitReached();
void CheckMemoryPressure();
};
class V8_EXPORT StartupData {
public:
const char* data;
int raw_size;
};
/**
* EntropySource is used as a callback function when v8 needs a source
* of entropy.
*/
typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
/**
* ReturnAddressLocationResolver is used as a callback function when v8 is
* resolving the location of a return address on the stack. Profilers that
* change the return address on the stack can use this to resolve the stack
* location to wherever the profiler stashed the original return address.
*
* \param return_addr_location A location on stack where a machine
* return address resides.
* \returns Either return_addr_location, or else a pointer to the profiler's
* copy of the original return address.
*
* \note The resolver function must not cause garbage collection.
*/
typedef uintptr_t (*ReturnAddressLocationResolver)(
uintptr_t return_addr_location);
/**
* Container class for static utility functions.
*/
class V8_EXPORT V8 {
public:
/**
* Hand startup data to V8, in case the embedder has chosen to build
* V8 with external startup data.
*
* Note:
* - By default the startup data is linked into the V8 library, in which
* case this function is not meaningful.
* - If this needs to be called, it needs to be called before V8
* tries to make use of its built-ins.
* - To avoid unnecessary copies of data, V8 will point directly into the
* given data blob, so pretty please keep it around until V8 exit.
* - Compression of the startup blob might be useful, but needs to
* handled entirely on the embedders' side.
* - The call will abort if the data is invalid.
*/
static void SetNativesDataBlob(StartupData* startup_blob);
static void SetSnapshotDataBlob(StartupData* startup_blob);
/**
* Bootstrap an isolate and a context from scratch to create a startup
* snapshot. Include the side-effects of running the optional script.
* Returns { NULL, 0 } on failure.
* The caller acquires ownership of the data array in the return value.
*/
static StartupData CreateSnapshotDataBlob(const char* embedded_source = NULL);
/**
* Bootstrap an isolate and a context from the cold startup blob, run the
* warm-up script to trigger code compilation. The side effects are then
* discarded. The resulting startup snapshot will include compiled code.
* Returns { NULL, 0 } on failure.
* The caller acquires ownership of the data array in the return value.
* The argument startup blob is untouched.
*/
static StartupData WarmUpSnapshotDataBlob(StartupData cold_startup_blob,
const char* warmup_source);
/** Set the callback to invoke in case of Dcheck failures. */
static void SetDcheckErrorHandler(DcheckErrorCallback that);
/**
* Sets V8 flags from a string.
*/
static void SetFlagsFromString(const char* str, int length);
/**
* Sets V8 flags from the command line.
*/
static void SetFlagsFromCommandLine(int* argc,
char** argv,
bool remove_flags);
/** Get the version string. */
static const char* GetVersion();
/**
* Initializes V8. This function needs to be called before the first Isolate
* is created. It always returns true.
*/
static bool Initialize();
/**
* Allows the host application to provide a callback which can be used
* as a source of entropy for random number generators.
*/
static void SetEntropySource(EntropySource source);
/**
* Allows the host application to provide a callback that allows v8 to
* cooperate with a profiler that rewrites return addresses on stack.
*/
static void SetReturnAddressLocationResolver(
ReturnAddressLocationResolver return_address_resolver);
/**
* Releases any resources used by v8 and stops any utility threads
* that may be running. Note that disposing v8 is permanent, it
* cannot be reinitialized.
*
* It should generally not be necessary to dispose v8 before exiting
* a process, this should happen automatically. It is only necessary
* to use if the process needs the resources taken up by v8.
*/
static bool Dispose();
/**
* Initialize the ICU library bundled with V8. The embedder should only
* invoke this method when using the bundled ICU. Returns true on success.
*
* If V8 was compiled with the ICU data in an external file, the location
* of the data file has to be provided.
*/
static bool InitializeICU(const char* icu_data_file = nullptr);
/**
* Initialize the ICU library bundled with V8. The embedder should only
* invoke this method when using the bundled ICU. If V8 was compiled with
* the ICU data in an external file and when the default location of that
* file should be used, a path to the executable must be provided.
* Returns true on success.
*
* The default is a file called icudtl.dat side-by-side with the executable.
*
* Optionally, the location of the data file can be provided to override the
* default.
*/
static bool InitializeICUDefaultLocation(const char* exec_path,
const char* icu_data_file = nullptr);
/**
* Initialize the external startup data. The embedder only needs to
* invoke this method when external startup data was enabled in a build.
*
* If V8 was compiled with the startup data in an external file, then
* V8 needs to be given those external files during startup. There are
* three ways to do this:
* - InitializeExternalStartupData(const char*)
* This will look in the given directory for files "natives_blob.bin"
* and "snapshot_blob.bin" - which is what the default build calls them.
* - InitializeExternalStartupData(const char*, const char*)
* As above, but will directly use the two given file names.
* - Call SetNativesDataBlob, SetNativesDataBlob.
* This will read the blobs from the given data structures and will
* not perform any file IO.
*/
static void InitializeExternalStartupData(const char* directory_path);
static void InitializeExternalStartupData(const char* natives_blob,
const char* snapshot_blob);
/**
* Sets the v8::Platform to use. This should be invoked before V8 is
* initialized.
*/
static void InitializePlatform(Platform* platform);
/**
* Clears all references to the v8::Platform. This should be invoked after
* V8 was disposed.
*/
static void ShutdownPlatform();
#if V8_OS_POSIX
/**
* Give the V8 signal handler a chance to handle a fault.
*
* This function determines whether a memory access violation can be recovered
* by V8. If so, it will return true and modify context to return to a code
* fragment that can recover from the fault. Otherwise, TryHandleSignal will
* return false.
*
* The parameters to this function correspond to those passed to a Linux
* signal handler.
*
* \param signal_number The signal number.
*
* \param info A pointer to the siginfo_t structure provided to the signal
* handler.
*
* \param context The third argument passed to the Linux signal handler, which
* points to a ucontext_t structure.
*/
static bool TryHandleSignal(int signal_number, void* info, void* context);
#endif // V8_OS_POSIX
/**
* Enable the default signal handler rather than using one provided by the
* embedder.
*/
V8_DEPRECATE_SOON("Use EnableWebAssemblyTrapHandler",
static bool RegisterDefaultSignalHandler());
/**
* Activate trap-based bounds checking for WebAssembly.
*
* \param use_v8_signal_handler Whether V8 should install its own signal
* handler or rely on the embedder's.
*/
static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler);
private:
V8();
static internal::Object** GlobalizeReference(internal::Isolate* isolate,
internal::Object** handle);
static internal::Object** CopyPersistent(internal::Object** handle);
static void DisposeGlobal(internal::Object** global_handle);
static void MakeWeak(internal::Object** location, void* data,
WeakCallbackInfo<void>::Callback weak_callback,
WeakCallbackType type);
static void MakeWeak(internal::Object** location, void* data,
// Must be 0 or -1.
int internal_field_index1,
// Must be 1 or -1.
int internal_field_index2,
WeakCallbackInfo<void>::Callback weak_callback);
static void MakeWeak(internal::Object*** location_addr);
static void* ClearWeak(internal::Object** location);
static void AnnotateStrongRetainer(internal::Object** location,
const char* label);
static Value* Eternalize(Isolate* isolate, Value* handle);
static void RegisterExternallyReferencedObject(internal::Object** object,
internal::Isolate* isolate);
template <class K, class V, class T>
friend class PersistentValueMapBase;
static void FromJustIsNothing();
static void ToLocalEmpty();
static void InternalFieldOutOfBounds(int index);
template <class T> friend class Local;
template <class T>
friend class MaybeLocal;
template <class T>
friend class Maybe;
template <class T>
friend class WeakCallbackInfo;
template <class T> friend class Eternal;
template <class T> friend class PersistentBase;
template <class T, class M> friend class Persistent;
friend class Context;
};
/**
* Helper class to create a snapshot data blob.
*/
class V8_EXPORT SnapshotCreator {
public:
enum class FunctionCodeHandling { kClear, kKeep };
/**
* Initialize and enter an isolate, and set it up for serialization.
* The isolate is either created from scratch or from an existing snapshot.
* The caller keeps ownership of the argument snapshot.
* \param existing_blob existing snapshot from which to create this one.
* \param external_references a null-terminated array of external references
* that must be equivalent to CreateParams::external_references.
*/
SnapshotCreator(Isolate* isolate,
const intptr_t* external_references = nullptr,
StartupData* existing_blob = nullptr);
/**
* Create and enter an isolate, and set it up for serialization.
* The isolate is either created from scratch or from an existing snapshot.
* The caller keeps ownership of the argument snapshot.
* \param existing_blob existing snapshot from which to create this one.
* \param external_references a null-terminated array of external references
* that must be equivalent to CreateParams::external_references.
*/
SnapshotCreator(const intptr_t* external_references = nullptr,
StartupData* existing_blob = nullptr);
~SnapshotCreator();
/**
* \returns the isolate prepared by the snapshot creator.
*/
Isolate* GetIsolate();
/**
* Set the default context to be included in the snapshot blob.
* The snapshot will not contain the global proxy, and we expect one or a
* global object template to create one, to be provided upon deserialization.
*
* \param callback optional callback to serialize internal fields.
*/
void SetDefaultContext(Local<Context> context,
SerializeInternalFieldsCallback callback =
SerializeInternalFieldsCallback());
/**
* Add additional context to be included in the snapshot blob.
* The snapshot will include the global proxy.
*
* \param callback optional callback to serialize internal fields.
*
* \returns the index of the context in the snapshot blob.
*/
size_t AddContext(Local<Context> context,
SerializeInternalFieldsCallback callback =
SerializeInternalFieldsCallback());
/**
* Add a template to be included in the snapshot blob.
* \returns the index of the template in the snapshot blob.
*/
size_t AddTemplate(Local<Template> template_obj);
/**
* Attach arbitrary V8::Data to the context snapshot, which can be retrieved
* via Context::GetDataFromSnapshot after deserialization. This data does not
* survive when a new snapshot is created from an existing snapshot.
* \returns the index for retrieval.
*/
template <class T>
V8_INLINE size_t AddData(Local<Context> context, Local<T> object);
/**
* Attach arbitrary V8::Data to the isolate snapshot, which can be retrieved
* via Isolate::GetDataFromSnapshot after deserialization. This data does not
* survive when a new snapshot is created from an existing snapshot.
* \returns the index for retrieval.
*/
template <class T>
V8_INLINE size_t AddData(Local<T> object);
/**
* Created a snapshot data blob.
* This must not be called from within a handle scope.
* \param function_code_handling whether to include compiled function code
* in the snapshot.
* \returns { nullptr, 0 } on failure, and a startup snapshot on success. The
* caller acquires ownership of the data array in the return value.
*/
StartupData CreateBlob(FunctionCodeHandling function_code_handling);
// Disallow copying and assigning.
SnapshotCreator(const SnapshotCreator&) = delete;
void operator=(const SnapshotCreator&) = delete;
private:
size_t AddData(Local<Context> context, internal::Object* object);
size_t AddData(internal::Object* object);
void* data_;
};
/**
* A simple Maybe type, representing an object which may or may not have a
* value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
*
* If an API method returns a Maybe<>, the API method can potentially fail
* either because an exception is thrown, or because an exception is pending,
* e.g. because a previous API call threw an exception that hasn't been caught
* yet, or because a TerminateExecution exception was thrown. In that case, a
* "Nothing" value is returned.
*/
template <class T>
class Maybe {
public:
V8_INLINE bool IsNothing() const { return !has_value_; }
V8_INLINE bool IsJust() const { return has_value_; }
/**
* An alias for |FromJust|. Will crash if the Maybe<> is nothing.
*/
V8_INLINE T ToChecked() const { return FromJust(); }
/**
* Converts this Maybe<> to a value of type T. If this Maybe<> is
* nothing (empty), |false| is returned and |out| is left untouched.
*/
V8_WARN_UNUSED_RESULT V8_INLINE bool To(T* out) const {
if (V8_LIKELY(IsJust())) *out = value_;
return IsJust();
}
/**
* Converts this Maybe<> to a value of type T. If this Maybe<> is
* nothing (empty), V8 will crash the process.
*/
V8_INLINE T FromJust() const {
if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
return value_;
}
/**
* Converts this Maybe<> to a value of type T, using a default value if this
* Maybe<> is nothing (empty).
*/
V8_INLINE T FromMaybe(const T& default_value) const {
return has_value_ ? value_ : default_value;
}
V8_INLINE bool operator==(const Maybe& other) const {
return (IsJust() == other.IsJust()) &&
(!IsJust() || FromJust() == other.FromJust());
}
V8_INLINE bool operator!=(const Maybe& other) const {
return !operator==(other);
}
private:
Maybe() : has_value_(false) {}
explicit Maybe(const T& t) : has_value_(true), value_(t) {}
bool has_value_;
T value_;
template <class U>
friend Maybe<U> Nothing();
template <class U>
friend Maybe<U> Just(const U& u);
};
template <class T>
inline Maybe<T> Nothing() {
return Maybe<T>();
}
template <class T>
inline Maybe<T> Just(const T& t) {
return Maybe<T>(t);
}
// A template specialization of Maybe<T> for the case of T = void.
template <>
class Maybe<void> {
public:
V8_INLINE bool IsNothing() const { return !is_valid_; }
V8_INLINE bool IsJust() const { return is_valid_; }
V8_INLINE bool operator==(const Maybe& other) const {
return IsJust() == other.IsJust();
}
V8_INLINE bool operator!=(const Maybe& other) const {
return !operator==(other);
}
private:
struct JustTag {};
Maybe() : is_valid_(false) {}
explicit Maybe(JustTag) : is_valid_(true) {}
bool is_valid_;
template <class U>
friend Maybe<U> Nothing();
friend Maybe<void> JustVoid();
};
inline Maybe<void> JustVoid() { return Maybe<void>(Maybe<void>::JustTag()); }
/**
* An external exception handler.
*/
class V8_EXPORT TryCatch {
public:
/**
* Creates a new try/catch block and registers it with v8. Note that
* all TryCatch blocks should be stack allocated because the memory
* location itself is compared against JavaScript try/catch blocks.
*/
explicit TryCatch(Isolate* isolate);
/**
* Unregisters and deletes this try/catch block.
*/
~TryCatch();
/**
* Returns true if an exception has been caught by this try/catch block.
*/
bool HasCaught() const;
/**
* For certain types of exceptions, it makes no sense to continue execution.
*
* If CanContinue returns false, the correct action is to perform any C++
* cleanup needed and then return. If CanContinue returns false and
* HasTerminated returns true, it is possible to call
* CancelTerminateExecution in order to continue calling into the engine.
*/
bool CanContinue() const;
/**
* Returns true if an exception has been caught due to script execution
* being terminated.
*
* There is no JavaScript representation of an execution termination
* exception. Such exceptions are thrown when the TerminateExecution
* methods are called to terminate a long-running script.
*
* If such an exception has been thrown, HasTerminated will return true,
* indicating that it is possible to call CancelTerminateExecution in order
* to continue calling into the engine.
*/
bool HasTerminated() const;
/**
* Throws the exception caught by this TryCatch in a way that avoids
* it being caught again by this same TryCatch. As with ThrowException
* it is illegal to execute any JavaScript operations after calling
* ReThrow; the caller must return immediately to where the exception
* is caught.
*/
Local<Value> ReThrow();
/**
* Returns the exception caught by this try/catch block. If no exception has
* been caught an empty handle is returned.
*
* The returned handle is valid until this TryCatch block has been destroyed.
*/
Local<Value> Exception() const;
/**
* Returns the .stack property of the thrown object. If no .stack
* property is present an empty handle is returned.
*/
V8_DEPRECATED("Use maybe version.", Local<Value> StackTrace() const);
V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace(
Local<Context> context) const;
/**
* Returns the message associated with this exception. If there is
* no message associated an empty handle is returned.
*
* The returned handle is valid until this TryCatch block has been
* destroyed.
*/
Local<v8::Message> Message() const;
/**
* Clears any exceptions that may have been caught by this try/catch block.
* After this method has been called, HasCaught() will return false. Cancels
* the scheduled exception if it is caught and ReThrow() is not called before.
*
* It is not necessary to clear a try/catch block before using it again; if
* another exception is thrown the previously caught exception will just be
* overwritten. However, it is often a good idea since it makes it easier
* to determine which operation threw a given exception.
*/
void Reset();
/**
* Set verbosity of the external exception handler.
*
* By default, exceptions that are caught by an external exception
* handler are not reported. Call SetVerbose with true on an
* external exception handler to have exceptions caught by the
* handler reported as if they were not caught.
*/
void SetVerbose(bool value);
/**
* Returns true if verbosity is enabled.
*/
bool IsVerbose() const;
/**
* Set whether or not this TryCatch should capture a Message object
* which holds source information about where the exception
* occurred. True by default.
*/
void SetCaptureMessage(bool value);
/**
* There are cases when the raw address of C++ TryCatch object cannot be
* used for comparisons with addresses into the JS stack. The cases are:
* 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
* 2) Address sanitizer allocates local C++ object in the heap when
* UseAfterReturn mode is enabled.
* This method returns address that can be used for comparisons with
* addresses into the JS stack. When neither simulator nor ASAN's
* UseAfterReturn is enabled, then the address returned will be the address
* of the C++ try catch handler itself.
*/
static void* JSStackComparableAddress(TryCatch* handler) {
if (handler == NULL) return NULL;
return handler->js_stack_comparable_address_;
}
TryCatch(const TryCatch&) = delete;
void operator=(const TryCatch&) = delete;
private:
// Declaring operator new and delete as deleted is not spec compliant.
// Therefore declare them private instead to disable dynamic alloc
void* operator new(size_t size);
void* operator new[](size_t size);
void operator delete(void*, size_t);
void operator delete[](void*, size_t);
void ResetInternal();
internal::Isolate* isolate_;
TryCatch* next_;
void* exception_;
void* message_obj_;
void* js_stack_comparable_address_;
bool is_verbose_ : 1;
bool can_continue_ : 1;
bool capture_message_ : 1;
bool rethrow_ : 1;
bool has_terminated_ : 1;
friend class internal::Isolate;
};
// --- Context ---
/**
* A container for extension names.
*/
class V8_EXPORT ExtensionConfiguration {
public:
ExtensionConfiguration() : name_count_(0), names_(NULL) { }
ExtensionConfiguration(int name_count, const char* names[])
: name_count_(name_count), names_(names) { }
const char** begin() const { return &names_[0]; }
const char** end() const { return &names_[name_count_]; }
private:
const int name_count_;
const char** names_;
};
/**
* A sandboxed execution context with its own set of built-in objects
* and functions.
*/
class V8_EXPORT Context {
public:
/**
* Returns the global proxy object.
*
* Global proxy object is a thin wrapper whose prototype points to actual
* context's global object with the properties like Object, etc. This is done
* that way for security reasons (for more details see
* https://wiki.mozilla.org/Gecko:SplitWindow).
*
* Please note that changes to global proxy object prototype most probably
* would break VM---v8 expects only global object as a prototype of global
* proxy object.
*/
Local<Object> Global();
/**
* Detaches the global object from its context before
* the global object can be reused to create a new context.
*/
void DetachGlobal();
/**
* Creates a new context and returns a handle to the newly allocated
* context.
*
* \param isolate The isolate in which to create the context.
*
* \param extensions An optional extension configuration containing
* the extensions to be installed in the newly created context.
*
* \param global_template An optional object template from which the
* global object for the newly created context will be created.
*
* \param global_object An optional global object to be reused for
* the newly created context. This global object must have been
* created by a previous call to Context::New with the same global
* template. The state of the global object will be completely reset
* and only object identify will remain.
*/
static Local<Context> New(
Isolate* isolate, ExtensionConfiguration* extensions = NULL,
MaybeLocal<ObjectTemplate> global_template = MaybeLocal<ObjectTemplate>(),
MaybeLocal<Value> global_object = MaybeLocal<Value>(),
DeserializeInternalFieldsCallback internal_fields_deserializer =
DeserializeInternalFieldsCallback());
/**
* Create a new context from a (non-default) context snapshot. There
* is no way to provide a global object template since we do not create
* a new global object from template, but we can reuse a global object.
*
* \param isolate See v8::Context::New.
*
* \param context_snapshot_index The index of the context snapshot to
* deserialize from. Use v8::Context::New for the default snapshot.
*
* \param embedder_fields_deserializer Optional callback to deserialize
* internal fields. It should match the SerializeInternalFieldCallback used
* to serialize.
*
* \param extensions See v8::Context::New.
*
* \param global_object See v8::Context::New.
*/
static MaybeLocal<Context> FromSnapshot(
Isolate* isolate, size_t context_snapshot_index,
DeserializeInternalFieldsCallback embedder_fields_deserializer =
DeserializeInternalFieldsCallback(),
ExtensionConfiguration* extensions = nullptr,
MaybeLocal<Value> global_object = MaybeLocal<Value>());
/**
* Returns an global object that isn't backed by an actual context.
*
* The global template needs to have access checks with handlers installed.
* If an existing global object is passed in, the global object is detached
* from its context.
*
* Note that this is different from a detached context where all accesses to
* the global proxy will fail. Instead, the access check handlers are invoked.
*
* It is also not possible to detach an object returned by this method.
* Instead, the access check handlers need to return nothing to achieve the
* same effect.
*
* It is possible, however, to create a new context from the global object
* returned by this method.
*/
static MaybeLocal<Object> NewRemoteContext(
Isolate* isolate, Local<ObjectTemplate> global_template,
MaybeLocal<Value> global_object = MaybeLocal<Value>());
/**
* Sets the security token for the context. To access an object in
* another context, the security tokens must match.
*/
void SetSecurityToken(Local<Value> token);
/** Restores the security token to the default value. */
void UseDefaultSecurityToken();
/** Returns the security token of this context.*/
Local<Value> GetSecurityToken();
/**
* Enter this context. After entering a context, all code compiled
* and run is compiled and run in this context. If another context
* is already entered, this old context is saved so it can be
* restored when the new context is exited.
*/
void Enter();
/**
* Exit this context. Exiting the current context restores the
* context that was in place when entering the current context.
*/
void Exit();
/** Returns an isolate associated with a current context. */
Isolate* GetIsolate();
/**
* The field at kDebugIdIndex used to be reserved for the inspector.
* It now serves no purpose.
*/
enum EmbedderDataFields { kDebugIdIndex = 0 };
/**
* Return the number of fields allocated for embedder data.
*/
uint32_t GetNumberOfEmbedderDataFields();
/**
* Gets the embedder data with the given index, which must have been set by a
* previous call to SetEmbedderData with the same index.
*/
V8_INLINE Local<Value> GetEmbedderData(int index);
/**
* Gets the binding object used by V8 extras. Extra natives get a reference
* to this object and can use it to "export" functionality by adding
* properties. Extra natives can also "import" functionality by accessing
* properties added by the embedder using the V8 API.
*/
Local<Object> GetExtrasBindingObject();
/**
* Sets the embedder data with the given index, growing the data as
* needed. Note that index 0 currently has a special meaning for Chrome's
* debugger.
*/
void SetEmbedderData(int index, Local<Value> value);
/**
* Gets a 2-byte-aligned native pointer from the embedder data with the given
* index, which must have been set by a previous call to
* SetAlignedPointerInEmbedderData with the same index. Note that index 0
* currently has a special meaning for Chrome's debugger.
*/
V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
/**
* Sets a 2-byte-aligned native pointer in the embedder data with the given
* index, growing the data as needed. Note that index 0 currently has a
* special meaning for Chrome's debugger.
*/
void SetAlignedPointerInEmbedderData(int index, void* value);
/**
* Control whether code generation from strings is allowed. Calling
* this method with false will disable 'eval' and the 'Function'
* constructor for code running in this context. If 'eval' or the
* 'Function' constructor are used an exception will be thrown.
*
* If code generation from strings is not allowed the
* V8::AllowCodeGenerationFromStrings callback will be invoked if
* set before blocking the call to 'eval' or the 'Function'
* constructor. If that callback returns true, the call will be
* allowed, otherwise an exception will be thrown. If no callback is
* set an exception will be thrown.
*/
void AllowCodeGenerationFromStrings(bool allow);
/**
* Returns true if code generation from strings is allowed for the context.
* For more details see AllowCodeGenerationFromStrings(bool) documentation.
*/
bool IsCodeGenerationFromStringsAllowed();
/**
* Sets the error description for the exception that is thrown when
* code generation from strings is not allowed and 'eval' or the 'Function'
* constructor are called.
*/
void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
/**
* Return data that was previously attached to the context snapshot via
* SnapshotCreator, and removes the reference to it.
* Repeated call with the same index returns an empty MaybeLocal.
*/
template <class T>
V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
/**
* Stack-allocated class which sets the execution context for all
* operations executed within a local scope.
*/
class Scope {
public:
explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
context_->Enter();
}
V8_INLINE ~Scope() { context_->Exit(); }
private:
Local<Context> context_;
};
/**
* Stack-allocated class to support the backup incumbent settings object
* stack.
* https://html.spec.whatwg.org/multipage/webappapis.html#backup-incumbent-settings-object-stack
*/
class V8_EXPORT BackupIncumbentScope {
public:
/**
* |backup_incumbent_context| is pushed onto the backup incumbent settings
* object stack.
*/
explicit BackupIncumbentScope(Local<Context> backup_incumbent_context);
~BackupIncumbentScope();
private:
friend class internal::Isolate;
Local<Context> backup_incumbent_context_;
const BackupIncumbentScope* prev_ = nullptr;
};
private:
friend class Value;
friend class Script;
friend class Object;
friend class Function;
internal::Object** GetDataFromSnapshotOnce(size_t index);
Local<Value> SlowGetEmbedderData(int index);
void* SlowGetAlignedPointerFromEmbedderData(int index);
};
/**
* Multiple threads in V8 are allowed, but only one thread at a time is allowed
* to use any given V8 isolate, see the comments in the Isolate class. The
* definition of 'using a V8 isolate' includes accessing handles or holding onto
* object pointers obtained from V8 handles while in the particular V8 isolate.
* It is up to the user of V8 to ensure, perhaps with locking, that this
* constraint is not violated. In addition to any other synchronization
* mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
* used to signal thread switches to V8.
*
* v8::Locker is a scoped lock object. While it's active, i.e. between its
* construction and destruction, the current thread is allowed to use the locked
* isolate. V8 guarantees that an isolate can be locked by at most one thread at
* any time. In other words, the scope of a v8::Locker is a critical section.
*
* Sample usage:
* \code
* ...
* {
* v8::Locker locker(isolate);
* v8::Isolate::Scope isolate_scope(isolate);
* ...
* // Code using V8 and isolate goes here.
* ...
* } // Destructor called here
* \endcode
*
* If you wish to stop using V8 in a thread A you can do this either by
* destroying the v8::Locker object as above or by constructing a v8::Unlocker
* object:
*
* \code
* {
* isolate->Exit();
* v8::Unlocker unlocker(isolate);
* ...
* // Code not using V8 goes here while V8 can run in another thread.
* ...
* } // Destructor called here.
* isolate->Enter();
* \endcode
*
* The Unlocker object is intended for use in a long-running callback from V8,
* where you want to release the V8 lock for other threads to use.
*
* The v8::Locker is a recursive lock, i.e. you can lock more than once in a
* given thread. This can be useful if you have code that can be called either
* from code that holds the lock or from code that does not. The Unlocker is
* not recursive so you can not have several Unlockers on the stack at once, and
* you can not use an Unlocker in a thread that is not inside a Locker's scope.
*
* An unlocker will unlock several lockers if it has to and reinstate the
* correct depth of locking on its destruction, e.g.:
*
* \code
* // V8 not locked.
* {
* v8::Locker locker(isolate);
* Isolate::Scope isolate_scope(isolate);
* // V8 locked.
* {
* v8::Locker another_locker(isolate);
* // V8 still locked (2 levels).
* {
* isolate->Exit();
* v8::Unlocker unlocker(isolate);
* // V8 not locked.
* }
* isolate->Enter();
* // V8 locked again (2 levels).
* }
* // V8 still locked (1 level).
* }
* // V8 Now no longer locked.
* \endcode
*/
class V8_EXPORT Unlocker {
public:
/**
* Initialize Unlocker for a given Isolate.
*/
V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
~Unlocker();
private:
void Initialize(Isolate* isolate);
internal::Isolate* isolate_;
};
class V8_EXPORT Locker {
public:
/**
* Initialize Locker for a given Isolate.
*/
V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
~Locker();
/**
* Returns whether or not the locker for a given isolate, is locked by the
* current thread.
*/
static bool IsLocked(Isolate* isolate);
/**
* Returns whether v8::Locker is being used by this V8 instance.
*/
static bool IsActive();
// Disallow copying and assigning.
Locker(const Locker&) = delete;
void operator=(const Locker&) = delete;
private:
void Initialize(Isolate* isolate);
bool has_lock_;
bool top_level_;
internal::Isolate* isolate_;
};
// --- Implementation ---
namespace internal {
const int kApiPointerSize = sizeof(void*); // NOLINT
const int kApiIntSize = sizeof(int); // NOLINT
const int kApiInt64Size = sizeof(int64_t); // NOLINT
// Tag information for HeapObject.
const int kHeapObjectTag = 1;
const int kWeakHeapObjectTag = 3;
const int kHeapObjectTagSize = 2;
const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
// Tag information for Smi.
const int kSmiTag = 0;
const int kSmiTagSize = 1;
const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
template <size_t ptr_size> struct SmiTagging;
template<int kSmiShiftSize>
V8_INLINE internal::Object* IntToSmi(int value) {
int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
uintptr_t tagged_value =
(static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
return reinterpret_cast<internal::Object*>(tagged_value);
}
// Smi constants for 32-bit systems.
template <> struct SmiTagging<4> {
enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
static int SmiShiftSize() { return kSmiShiftSize; }
static int SmiValueSize() { return kSmiValueSize; }
V8_INLINE static int SmiToInt(const internal::Object* value) {
int shift_bits = kSmiTagSize + kSmiShiftSize;
// Throw away top 32 bits and shift down (requires >> to be sign extending).
return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
}
V8_INLINE static internal::Object* IntToSmi(int value) {
return internal::IntToSmi<kSmiShiftSize>(value);
}
V8_INLINE static bool IsValidSmi(intptr_t value) {
// To be representable as an tagged small integer, the two
// most-significant bits of 'value' must be either 00 or 11 due to
// sign-extension. To check this we add 01 to the two
// most-significant bits, and check if the most-significant bit is 0
//
// CAUTION: The original code below:
// bool result = ((value + 0x40000000) & 0x80000000) == 0;
// may lead to incorrect results according to the C language spec, and
// in fact doesn't work correctly with gcc4.1.1 in some cases: The
// compiler may produce undefined results in case of signed integer
// overflow. The computation must be done w/ unsigned ints.
return static_cast<uintptr_t>(value) + 0x40000000U < 0x80000000U;
}
};
// Smi constants for 64-bit systems.
template <> struct SmiTagging<8> {
enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
static int SmiShiftSize() { return kSmiShiftSize; }
static int SmiValueSize() { return kSmiValueSize; }
V8_INLINE static int SmiToInt(const internal::Object* value) {
int shift_bits = kSmiTagSize + kSmiShiftSize;
// Shift down and throw away top 32 bits.
return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
}
V8_INLINE static internal::Object* IntToSmi(int value) {
return internal::IntToSmi<kSmiShiftSize>(value);
}
V8_INLINE static bool IsValidSmi(intptr_t value) {
// To be representable as a long smi, the value must be a 32-bit integer.
return (value == static_cast<int32_t>(value));
}
};
typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
/**
* This class exports constants and functionality from within v8 that
* is necessary to implement inline functions in the v8 api. Don't
* depend on functions and constants defined here.
*/
class Internals {
public:
// These values match non-compiler-dependent values defined within
// the implementation of v8.
static const int kHeapObjectMapOffset = 0;
static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
static const int kStringResourceOffset = 3 * kApiPointerSize;
static const int kOddballKindOffset = 4 * kApiPointerSize + sizeof(double);
static const int kForeignAddressOffset = kApiPointerSize;
static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
static const int kContextHeaderSize = 2 * kApiPointerSize;
static const int kContextEmbedderDataIndex = 5;
static const int kFullStringRepresentationMask = 0x0f;
static const int kStringEncodingMask = 0x8;
static const int kExternalTwoByteRepresentationTag = 0x02;
static const int kExternalOneByteRepresentationTag = 0x0a;
static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
static const int kExternalMemoryOffset = 4 * kApiPointerSize;
static const int kExternalMemoryLimitOffset =
kExternalMemoryOffset + kApiInt64Size;
static const int kExternalMemoryAtLastMarkCompactOffset =
kExternalMemoryLimitOffset + kApiInt64Size;
static const int kIsolateRootsOffset = kExternalMemoryLimitOffset +
kApiInt64Size + kApiInt64Size +
kApiPointerSize + kApiPointerSize;
static const int kUndefinedValueRootIndex = 4;
static const int kTheHoleValueRootIndex = 5;
static const int kNullValueRootIndex = 6;
static const int kTrueValueRootIndex = 7;
static const int kFalseValueRootIndex = 8;
static const int kEmptyStringRootIndex = 9;
static const int kNodeClassIdOffset = 1 * kApiPointerSize;
static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
static const int kNodeStateMask = 0x7;
static const int kNodeStateIsWeakValue = 2;
static const int kNodeStateIsPendingValue = 3;
static const int kNodeStateIsNearDeathValue = 4;
static const int kNodeIsIndependentShift = 3;
static const int kNodeIsActiveShift = 4;
static const int kFirstNonstringType = 0x80;
static const int kOddballType = 0x83;
static const int kForeignType = 0x87;
static const int kJSSpecialApiObjectType = 0x410;
static const int kJSApiObjectType = 0x420;
static const int kJSObjectType = 0x421;
static const int kUndefinedOddballKind = 5;
static const int kNullOddballKind = 3;
static const uint32_t kNumIsolateDataSlots = 4;
V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
#ifdef V8_ENABLE_CHECKS
CheckInitializedImpl(isolate);
#endif
}
V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
kHeapObjectTag);
}
V8_INLINE static int SmiValue(const internal::Object* value) {
return PlatformSmiTagging::SmiToInt(value);
}
V8_INLINE static internal::Object* IntToSmi(int value) {
return PlatformSmiTagging::IntToSmi(value);
}
V8_INLINE static bool IsValidSmi(intptr_t value) {
return PlatformSmiTagging::IsValidSmi(value);
}
V8_INLINE static int GetInstanceType(const internal::Object* obj) {
typedef internal::Object O;
O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
return ReadField<uint16_t>(map, kMapInstanceTypeOffset);
}
V8_INLINE static int GetOddballKind(const internal::Object* obj) {
typedef internal::Object O;
return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
}
V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
int representation = (instance_type & kFullStringRepresentationMask);
return representation == kExternalTwoByteRepresentationTag;
}
V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
return *addr & static_cast<uint8_t>(1U << shift);
}
V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
bool value, int shift) {
uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
uint8_t mask = static_cast<uint8_t>(1U << shift);
*addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
}
V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
return *addr & kNodeStateMask;
}
V8_INLINE static void UpdateNodeState(internal::Object** obj,
uint8_t value) {
uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
*addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
}
V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
uint32_t slot,
void* data) {
uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
kIsolateEmbedderDataOffset + slot * kApiPointerSize;
*reinterpret_cast<void**>(addr) = data;
}
V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
uint32_t slot) {
const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
kIsolateEmbedderDataOffset + slot * kApiPointerSize;
return *reinterpret_cast<void* const*>(addr);
}
V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
int index) {
uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
}
template <typename T>
V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
const uint8_t* addr =
reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
return *reinterpret_cast<const T*>(addr);
}
template <typename T>
V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
typedef internal::Object O;
typedef internal::Internals I;
O* ctx = *reinterpret_cast<O* const*>(context);
int embedder_data_offset = I::kContextHeaderSize +
(internal::kApiPointerSize * I::kContextEmbedderDataIndex);
O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
int value_offset =
I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
return I::ReadField<T>(embedder_data, value_offset);
}
};
// Only perform cast check for types derived from v8::Data since
// other types do not implement the Cast method.
template <bool PerformCheck>
struct CastCheck {
template <class T>
static void Perform(T* data);
};
template <>
template <class T>
void CastCheck<true>::Perform(T* data) {
T::Cast(data);
}
template <>
template <class T>
void CastCheck<false>::Perform(T* data) {}
template <class T>
V8_INLINE void PerformCastCheck(T* data) {
CastCheck<std::is_base_of<Data, T>::value>::Perform(data);
}
} // namespace internal
template <class T>
Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
return New(isolate, that.val_);
}
template <class T>
Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
return New(isolate, that.val_);
}
template <class T>
Local<T> Local<T>::New(Isolate* isolate, T* that) {
if (that == NULL) return Local<T>();
T* that_ptr = that;
internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
reinterpret_cast<internal::Isolate*>(isolate), *p)));
}
template<class T>
template<class S>
void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
TYPE_CHECK(T, S);
val_ = reinterpret_cast<T*>(
V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle)));
}
template <class T>
Local<T> Eternal<T>::Get(Isolate* isolate) const {
// The eternal handle will never go away, so as with the roots, we don't even
// need to open a handle.
return Local<T>(val_);
}
template <class T>
Local<T> MaybeLocal<T>::ToLocalChecked() {
if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
return Local<T>(val_);
}
template <class T>
void* WeakCallbackInfo<T>::GetInternalField(int index) const {
#ifdef V8_ENABLE_CHECKS
if (index < 0 || index >= kEmbedderFieldsInWeakCallback) {
V8::InternalFieldOutOfBounds(index);
}
#endif
return embedder_fields_[index];
}
template <class T>
T* PersistentBase<T>::New(Isolate* isolate, T* that) {
if (that == NULL) return NULL;
internal::Object** p = reinterpret_cast<internal::Object**>(that);
return reinterpret_cast<T*>(
V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
p));
}
template <class T, class M>
template <class S, class M2>
void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
TYPE_CHECK(T, S);
this->Reset();
if (that.IsEmpty()) return;
internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
M::Copy(that, this);
}
template <class T>
bool PersistentBase<T>::IsIndependent() const {
typedef internal::Internals I;
if (this->IsEmpty()) return false;
return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
I::kNodeIsIndependentShift);
}
template <class T>
bool PersistentBase<T>::IsNearDeath() const {
typedef internal::Internals I;
if (this->IsEmpty()) return false;
uint8_t node_state =
I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
return node_state == I::kNodeStateIsNearDeathValue ||
node_state == I::kNodeStateIsPendingValue;
}
template <class T>
bool PersistentBase<T>::IsWeak() const {
typedef internal::Internals I;
if (this->IsEmpty()) return false;
return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
I::kNodeStateIsWeakValue;
}
template <class T>
void PersistentBase<T>::Reset() {
if (this->IsEmpty()) return;
V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
val_ = 0;
}
template <class T>
template <class S>
void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
TYPE_CHECK(T, S);
Reset();
if (other.IsEmpty()) return;
this->val_ = New(isolate, other.val_);
}
template <class T>
template <class S>
void PersistentBase<T>::Reset(Isolate* isolate,
const PersistentBase<S>& other) {
TYPE_CHECK(T, S);
Reset();
if (other.IsEmpty()) return;
this->val_ = New(isolate, other.val_);
}
template <class T>
template <typename P>
V8_INLINE void PersistentBase<T>::SetWeak(
P* parameter, typename WeakCallbackInfo<P>::Callback callback,
WeakCallbackType type) {
typedef typename WeakCallbackInfo<void>::Callback Callback;
V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
reinterpret_cast<Callback>(callback), type);
}
template <class T>
void PersistentBase<T>::SetWeak() {
V8::MakeWeak(reinterpret_cast<internal::Object***>(&this->val_));
}
template <class T>
template <typename P>
P* PersistentBase<T>::ClearWeak() {
return reinterpret_cast<P*>(
V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
}
template <class T>
void PersistentBase<T>::AnnotateStrongRetainer(const char* label) {
V8::AnnotateStrongRetainer(reinterpret_cast<internal::Object**>(this->val_),
label);
}
template <class T>
void PersistentBase<T>::RegisterExternalReference(Isolate* isolate) const {
if (IsEmpty()) return;
V8::RegisterExternallyReferencedObject(
reinterpret_cast<internal::Object**>(this->val_),
reinterpret_cast<internal::Isolate*>(isolate));
}
template <class T>
void PersistentBase<T>::MarkIndependent() {
typedef internal::Internals I;
if (this->IsEmpty()) return;
I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_), true,
I::kNodeIsIndependentShift);
}
template <class T>
void PersistentBase<T>::MarkActive() {
typedef internal::Internals I;
if (this->IsEmpty()) return;
I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_), true,
I::kNodeIsActiveShift);
}
template <class T>
void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
typedef internal::Internals I;
if (this->IsEmpty()) return;
internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
*reinterpret_cast<uint16_t*>(addr) = class_id;
}
template <class T>
uint16_t PersistentBase<T>::WrapperClassId() const {
typedef internal::Internals I;
if (this->IsEmpty()) return 0;
internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
return *reinterpret_cast<uint16_t*>(addr);
}
template<typename T>
ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
template<typename T>
template<typename S>
void ReturnValue<T>::Set(const Persistent<S>& handle) {
TYPE_CHECK(T, S);
if (V8_UNLIKELY(handle.IsEmpty())) {
*value_ = GetDefaultValue();
} else {
*value_ = *reinterpret_cast<internal::Object**>(*handle);
}
}
template <typename T>
template <typename S>
void ReturnValue<T>::Set(const Global<S>& handle) {
TYPE_CHECK(T, S);
if (V8_UNLIKELY(handle.IsEmpty())) {
*value_ = GetDefaultValue();
} else {
*value_ = *reinterpret_cast<internal::Object**>(*handle);
}
}
template <typename T>
template <typename S>
void ReturnValue<T>::Set(const Local<S> handle) {
TYPE_CHECK(T, S);
if (V8_UNLIKELY(handle.IsEmpty())) {
*value_ = GetDefaultValue();
} else {
*value_ = *reinterpret_cast<internal::Object**>(*handle);
}
}
template<typename T>
void ReturnValue<T>::Set(double i) {
TYPE_CHECK(T, Number);
Set(Number::New(GetIsolate(), i));
}
template<typename T>
void ReturnValue<T>::Set(int32_t i) {
TYPE_CHECK(T, Integer);
typedef internal::Internals I;
if (V8_LIKELY(I::IsValidSmi(i))) {
*value_ = I::IntToSmi(i);
return;
}
Set(Integer::New(GetIsolate(), i));
}
template<typename T>
void ReturnValue<T>::Set(uint32_t i) {
TYPE_CHECK(T, Integer);
// Can't simply use INT32_MAX here for whatever reason.
bool fits_into_int32_t = (i & (1U << 31)) == 0;
if (V8_LIKELY(fits_into_int32_t)) {
Set(static_cast<int32_t>(i));
return;
}
Set(Integer::NewFromUnsigned(GetIsolate(), i));
}
template<typename T>
void ReturnValue<T>::Set(bool value) {
TYPE_CHECK(T, Boolean);
typedef internal::Internals I;
int root_index;
if (value) {
root_index = I::kTrueValueRootIndex;
} else {
root_index = I::kFalseValueRootIndex;
}
*value_ = *I::GetRoot(GetIsolate(), root_index);
}
template<typename T>
void ReturnValue<T>::SetNull() {
TYPE_CHECK(T, Primitive);
typedef internal::Internals I;
*value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
}
template<typename T>
void ReturnValue<T>::SetUndefined() {
TYPE_CHECK(T, Primitive);
typedef internal::Internals I;
*value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
}
template<typename T>
void ReturnValue<T>::SetEmptyString() {
TYPE_CHECK(T, String);
typedef internal::Internals I;
*value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
}
template <typename T>
Isolate* ReturnValue<T>::GetIsolate() const {
// Isolate is always the pointer below the default value on the stack.
return *reinterpret_cast<Isolate**>(&value_[-2]);
}
template <typename T>
Local<Value> ReturnValue<T>::Get() const {
typedef internal::Internals I;
if (*value_ == *I::GetRoot(GetIsolate(), I::kTheHoleValueRootIndex))
return Local<Value>(*Undefined(GetIsolate()));
return Local<Value>::New(GetIsolate(), reinterpret_cast<Value*>(value_));
}
template <typename T>
template <typename S>
void ReturnValue<T>::Set(S* whatever) {
// Uncompilable to prevent inadvertent misuse.
TYPE_CHECK(S*, Primitive);
}
template<typename T>
internal::Object* ReturnValue<T>::GetDefaultValue() {
// Default value is always the pointer below value_ on the stack.
return value_[-1];
}
template <typename T>
FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
internal::Object** values,
int length)
: implicit_args_(implicit_args), values_(values), length_(length) {}
template<typename T>
Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
return Local<Value>(reinterpret_cast<Value*>(values_ - i));
}
template<typename T>
Local<Object> FunctionCallbackInfo<T>::This() const {
return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
}
template<typename T>
Local<Object> FunctionCallbackInfo<T>::Holder() const {
return Local<Object>(reinterpret_cast<Object*>(
&implicit_args_[kHolderIndex]));
}
template <typename T>
Local<Value> FunctionCallbackInfo<T>::NewTarget() const {
return Local<Value>(
reinterpret_cast<Value*>(&implicit_args_[kNewTargetIndex]));
}
template <typename T>
Local<Value> FunctionCallbackInfo<T>::Data() const {
return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
}
template<typename T>
Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
}
template<typename T>
ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
}
template<typename T>
bool FunctionCallbackInfo<T>::IsConstructCall() const {
return !NewTarget()->IsUndefined();
}
template<typename T>
int FunctionCallbackInfo<T>::Length() const {
return length_;
}
ScriptOrigin::ScriptOrigin(Local<Value> resource_name,
Local<Integer> resource_line_offset,
Local<Integer> resource_column_offset,
Local<Boolean> resource_is_shared_cross_origin,
Local<Integer> script_id,
Local<Value> source_map_url,
Local<Boolean> resource_is_opaque,
Local<Boolean> is_wasm, Local<Boolean> is_module,
Local<PrimitiveArray> host_defined_options)
: resource_name_(resource_name),
resource_line_offset_(resource_line_offset),
resource_column_offset_(resource_column_offset),
options_(!resource_is_shared_cross_origin.IsEmpty() &&
resource_is_shared_cross_origin->IsTrue(),
!resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue(),
!is_wasm.IsEmpty() && is_wasm->IsTrue(),
!is_module.IsEmpty() && is_module->IsTrue()),
script_id_(script_id),
source_map_url_(source_map_url),
host_defined_options_(host_defined_options) {}
Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
Local<PrimitiveArray> ScriptOrigin::HostDefinedOptions() const {
return host_defined_options_;
}
Local<Integer> ScriptOrigin::ResourceLineOffset() const {
return resource_line_offset_;
}
Local<Integer> ScriptOrigin::ResourceColumnOffset() const {
return resource_column_offset_;
}
Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
CachedData* data)
: source_string(string),
resource_name(origin.ResourceName()),
resource_line_offset(origin.ResourceLineOffset()),
resource_column_offset(origin.ResourceColumnOffset()),
resource_options(origin.Options()),
source_map_url(origin.SourceMapUrl()),
host_defined_options(origin.HostDefinedOptions()),
cached_data(data) {}
ScriptCompiler::Source::Source(Local<String> string,
CachedData* data)
: source_string(string), cached_data(data) {}
ScriptCompiler::Source::~Source() {
delete cached_data;
}
const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
const {
return cached_data;
}
const ScriptOriginOptions& ScriptCompiler::Source::GetResourceOptions() const {
return resource_options;
}
Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
return value ? True(isolate) : False(isolate);
}
void Template::Set(Isolate* isolate, const char* name, Local<Data> value) {
Set(String::NewFromUtf8(isolate, name, NewStringType::kInternalized)
.ToLocalChecked(),
value);
}
FunctionTemplate* FunctionTemplate::Cast(Data* data) {
#ifdef V8_ENABLE_CHECKS
CheckCast(data);
#endif
return reinterpret_cast<FunctionTemplate*>(data);
}
ObjectTemplate* ObjectTemplate::Cast(Data* data) {
#ifdef V8_ENABLE_CHECKS
CheckCast(data);
#endif
return reinterpret_cast<ObjectTemplate*>(data);
}
Signature* Signature::Cast(Data* data) {
#ifdef V8_ENABLE_CHECKS
CheckCast(data);
#endif
return reinterpret_cast<Signature*>(data);
}
AccessorSignature* AccessorSignature::Cast(Data* data) {
#ifdef V8_ENABLE_CHECKS
CheckCast(data);
#endif
return reinterpret_cast<AccessorSignature*>(data);
}
Local<Value> Object::GetInternalField(int index) {
#ifndef V8_ENABLE_CHECKS
typedef internal::Object O;
typedef internal::HeapObject HO;
typedef internal::Internals I;
O* obj = *reinterpret_cast<O**>(this);
// Fast path: If the object is a plain JSObject, which is the common case, we
// know where to find the internal fields and can return the value directly.
auto instance_type = I::GetInstanceType(obj);
if (instance_type == I::kJSObjectType ||
instance_type == I::kJSApiObjectType ||
instance_type == I::kJSSpecialApiObjectType) {
int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
O* value = I::ReadField<O*>(obj, offset);
O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
return Local<Value>(reinterpret_cast<Value*>(result));
}
#endif
return SlowGetInternalField(index);
}
void* Object::GetAlignedPointerFromInternalField(int index) {
#ifndef V8_ENABLE_CHECKS
typedef internal::Object O;
typedef internal::Internals I;
O* obj = *reinterpret_cast<O**>(this);
// Fast path: If the object is a plain JSObject, which is the common case, we
// know where to find the internal fields and can return the value directly.
auto instance_type = I::GetInstanceType(obj);
if (V8_LIKELY(instance_type == I::kJSObjectType ||
instance_type == I::kJSApiObjectType ||
instance_type == I::kJSSpecialApiObjectType)) {
int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
return I::ReadField<void*>(obj, offset);
}
#endif
return SlowGetAlignedPointerFromInternalField(index);
}
String* String::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<String*>(value);
}
Local<String> String::Empty(Isolate* isolate) {
typedef internal::Object* S;
typedef internal::Internals I;
I::CheckInitialized(isolate);
S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
return Local<String>(reinterpret_cast<String*>(slot));
}
String::ExternalStringResource* String::GetExternalStringResource() const {
typedef internal::Object O;
typedef internal::Internals I;
O* obj = *reinterpret_cast<O* const*>(this);
String::ExternalStringResource* result;
if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
result = reinterpret_cast<String::ExternalStringResource*>(value);
} else {
result = NULL;
}
#ifdef V8_ENABLE_CHECKS
VerifyExternalStringResource(result);
#endif
return result;
}
String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
String::Encoding* encoding_out) const {
typedef internal::Object O;
typedef internal::Internals I;
O* obj = *reinterpret_cast<O* const*>(this);
int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
*encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
ExternalStringResourceBase* resource = NULL;
if (type == I::kExternalOneByteRepresentationTag ||
type == I::kExternalTwoByteRepresentationTag) {
void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
resource = static_cast<ExternalStringResourceBase*>(value);
}
#ifdef V8_ENABLE_CHECKS
VerifyExternalStringResourceBase(resource, *encoding_out);
#endif
return resource;
}
bool Value::IsUndefined() const {
#ifdef V8_ENABLE_CHECKS
return FullIsUndefined();
#else
return QuickIsUndefined();
#endif
}
bool Value::QuickIsUndefined() const {
typedef internal::Object O;
typedef internal::Internals I;
O* obj = *reinterpret_cast<O* const*>(this);
if (!I::HasHeapObjectTag(obj)) return false;
if (I::GetInstanceType(obj) != I::kOddballType) return false;
return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
}
bool Value::IsNull() const {
#ifdef V8_ENABLE_CHECKS
return FullIsNull();
#else
return QuickIsNull();
#endif
}
bool Value::QuickIsNull() const {
typedef internal::Object O;
typedef internal::Internals I;
O* obj = *reinterpret_cast<O* const*>(this);
if (!I::HasHeapObjectTag(obj)) return false;
if (I::GetInstanceType(obj) != I::kOddballType) return false;
return (I::GetOddballKind(obj) == I::kNullOddballKind);
}
bool Value::IsNullOrUndefined() const {
#ifdef V8_ENABLE_CHECKS
return FullIsNull() || FullIsUndefined();
#else
return QuickIsNullOrUndefined();
#endif
}
bool Value::QuickIsNullOrUndefined() const {
typedef internal::Object O;
typedef internal::Internals I;
O* obj = *reinterpret_cast<O* const*>(this);
if (!I::HasHeapObjectTag(obj)) return false;
if (I::GetInstanceType(obj) != I::kOddballType) return false;
int kind = I::GetOddballKind(obj);
return kind == I::kNullOddballKind || kind == I::kUndefinedOddballKind;
}
bool Value::IsString() const {
#ifdef V8_ENABLE_CHECKS
return FullIsString();
#else
return QuickIsString();
#endif
}
bool Value::QuickIsString() const {
typedef internal::Object O;
typedef internal::Internals I;
O* obj = *reinterpret_cast<O* const*>(this);
if (!I::HasHeapObjectTag(obj)) return false;
return (I::GetInstanceType(obj) < I::kFirstNonstringType);
}
template <class T> Value* Value::Cast(T* value) {
return static_cast<Value*>(value);
}
Local<Boolean> Value::ToBoolean() const {
return ToBoolean(Isolate::GetCurrent()->GetCurrentContext())
.FromMaybe(Local<Boolean>());
}
Local<String> Value::ToString() const {
return ToString(Isolate::GetCurrent()->GetCurrentContext())
.FromMaybe(Local<String>());
}
Local<Object> Value::ToObject() const {
return ToObject(Isolate::GetCurrent()->GetCurrentContext())
.FromMaybe(Local<Object>());
}
Local<Integer> Value::ToInteger() const {
return ToInteger(Isolate::GetCurrent()->GetCurrentContext())
.FromMaybe(Local<Integer>());
}
Boolean* Boolean::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Boolean*>(value);
}
Name* Name::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Name*>(value);
}
Symbol* Symbol::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Symbol*>(value);
}
Private* Private::Cast(Data* data) {
#ifdef V8_ENABLE_CHECKS
CheckCast(data);
#endif
return reinterpret_cast<Private*>(data);
}
Number* Number::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Number*>(value);
}
Integer* Integer::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Integer*>(value);
}
Int32* Int32::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Int32*>(value);
}
Uint32* Uint32::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Uint32*>(value);
}
BigInt* BigInt::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<BigInt*>(value);
}
Date* Date::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Date*>(value);
}
StringObject* StringObject::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<StringObject*>(value);
}
SymbolObject* SymbolObject::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<SymbolObject*>(value);
}
NumberObject* NumberObject::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<NumberObject*>(value);
}
BigIntObject* BigIntObject::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<BigIntObject*>(value);
}
BooleanObject* BooleanObject::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<BooleanObject*>(value);
}
RegExp* RegExp::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<RegExp*>(value);
}
Object* Object::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Object*>(value);
}
Array* Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Array*>(value);
}
Map* Map::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Map*>(value);
}
Set* Set::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Set*>(value);
}
Promise* Promise::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Promise*>(value);
}
Proxy* Proxy::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Proxy*>(value);
}
WasmCompiledModule* WasmCompiledModule::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<WasmCompiledModule*>(value);
}
Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Promise::Resolver*>(value);
}
ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<ArrayBuffer*>(value);
}
ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<ArrayBufferView*>(value);
}
TypedArray* TypedArray::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<TypedArray*>(value);
}
Uint8Array* Uint8Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Uint8Array*>(value);
}
Int8Array* Int8Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Int8Array*>(value);
}
Uint16Array* Uint16Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Uint16Array*>(value);
}
Int16Array* Int16Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Int16Array*>(value);
}
Uint32Array* Uint32Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Uint32Array*>(value);
}
Int32Array* Int32Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Int32Array*>(value);
}
Float32Array* Float32Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Float32Array*>(value);
}
Float64Array* Float64Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Float64Array*>(value);
}
BigInt64Array* BigInt64Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<BigInt64Array*>(value);
}
BigUint64Array* BigUint64Array::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<BigUint64Array*>(value);
}
Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Uint8ClampedArray*>(value);
}
DataView* DataView::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<DataView*>(value);
}
SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<SharedArrayBuffer*>(value);
}
Function* Function::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<Function*>(value);
}
External* External::Cast(v8::Value* value) {
#ifdef V8_ENABLE_CHECKS
CheckCast(value);
#endif
return static_cast<External*>(value);
}
template<typename T>
Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
}
template<typename T>
Local<Value> PropertyCallbackInfo<T>::Data() const {
return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
}
template<typename T>
Local<Object> PropertyCallbackInfo<T>::This() const {
return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
}
template<typename T>
Local<Object> PropertyCallbackInfo<T>::Holder() const {
return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
}
template<typename T>
ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
return ReturnValue<T>(&args_[kReturnValueIndex]);
}
template <typename T>
bool PropertyCallbackInfo<T>::ShouldThrowOnError() const {
typedef internal::Internals I;
return args_[kShouldThrowOnErrorIndex] != I::IntToSmi(0);
}
Local<Primitive> Undefined(Isolate* isolate) {
typedef internal::Object* S;
typedef internal::Internals I;
I::CheckInitialized(isolate);
S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
}
Local<Primitive> Null(Isolate* isolate) {
typedef internal::Object* S;
typedef internal::Internals I;
I::CheckInitialized(isolate);
S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
}
Local<Boolean> True(Isolate* isolate) {
typedef internal::Object* S;
typedef internal::Internals I;
I::CheckInitialized(isolate);
S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
}
Local<Boolean> False(Isolate* isolate) {
typedef internal::Object* S;
typedef internal::Internals I;
I::CheckInitialized(isolate);
S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
}
void Isolate::SetData(uint32_t slot, void* data) {
typedef internal::Internals I;
I::SetEmbedderData(this, slot, data);
}
void* Isolate::GetData(uint32_t slot) {
typedef internal::Internals I;
return I::GetEmbedderData(this, slot);
}
uint32_t Isolate::GetNumberOfDataSlots() {
typedef internal::Internals I;
return I::kNumIsolateDataSlots;
}
template <class T>
MaybeLocal<T> Isolate::GetDataFromSnapshotOnce(size_t index) {
T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
if (data) internal::PerformCastCheck(data);
return Local<T>(data);
}
int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
int64_t change_in_bytes) {
typedef internal::Internals I;
const int64_t kMemoryReducerActivationLimit = 32 * 1024 * 1024;
int64_t* external_memory = reinterpret_cast<int64_t*>(
reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryOffset);
int64_t* external_memory_limit = reinterpret_cast<int64_t*>(
reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryLimitOffset);
int64_t* external_memory_at_last_mc =
reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
I::kExternalMemoryAtLastMarkCompactOffset);
const int64_t amount = *external_memory + change_in_bytes;
*external_memory = amount;
int64_t allocation_diff_since_last_mc =
*external_memory_at_last_mc - *external_memory;
allocation_diff_since_last_mc = allocation_diff_since_last_mc < 0
? -allocation_diff_since_last_mc
: allocation_diff_since_last_mc;
if (allocation_diff_since_last_mc > kMemoryReducerActivationLimit) {
CheckMemoryPressure();
}
if (change_in_bytes < 0) {
*external_memory_limit += change_in_bytes;
}
if (change_in_bytes > 0 && amount > *external_memory_limit) {
ReportExternalAllocationLimitReached();
}
return *external_memory;
}
Local<Value> Context::GetEmbedderData(int index) {
#ifndef V8_ENABLE_CHECKS
typedef internal::Object O;
typedef internal::HeapObject HO;
typedef internal::Internals I;
HO* context = *reinterpret_cast<HO**>(this);
O** result =
HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
return Local<Value>(reinterpret_cast<Value*>(result));
#else
return SlowGetEmbedderData(index);
#endif
}
void* Context::GetAlignedPointerFromEmbedderData(int index) {
#ifndef V8_ENABLE_CHECKS
typedef internal::Internals I;
return I::ReadEmbedderData<void*>(this, index);
#else
return SlowGetAlignedPointerFromEmbedderData(index);
#endif
}
template <class T>
MaybeLocal<T> Context::GetDataFromSnapshotOnce(size_t index) {
T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
if (data) internal::PerformCastCheck(data);
return Local<T>(data);
}
template <class T>
size_t SnapshotCreator::AddData(Local<Context> context, Local<T> object) {
T* object_ptr = *object;
internal::Object** p = reinterpret_cast<internal::Object**>(object_ptr);
return AddData(context, *p);
}
template <class T>
size_t SnapshotCreator::AddData(Local<T> object) {
T* object_ptr = *object;
internal::Object** p = reinterpret_cast<internal::Object**>(object_ptr);
return AddData(*p);
}
/**
* \example shell.cc
* A simple shell that takes a list of expressions on the
* command-line and executes them.
*/
/**
* \example process.cc
*/
} // namespace v8
#undef TYPE_CHECK
#endif // INCLUDE_V8_H_
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
9fc98d8ae2b127c0fd244b115d87f531af7aa35f | 9f25d05ee233701f6a192d8a75e3badd6998d979 | /release/moc_config.cpp | 21d86e0da92d6587af2750faeb5357aef36157d5 | [] | no_license | algogr/hourglass | 314356f43c36fef8b6729b328ae9cb736a9c83cb | d24ef15e5dbf769f74bb6b0edd8342e36233973a | refs/heads/master | 2021-01-21T02:28:19.509236 | 2014-01-09T20:09:45 | 2014-01-09T20:09:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,346 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'config.h'
**
** Created: Wed May 2 22:27:42 2012
** by: The Qt Meta Object Compiler version 62 (Qt 4.6.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../config.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'config.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.6.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_Config[] = {
// content:
4, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
8, 7, 7, 7, 0x08,
20, 7, 7, 7, 0x08,
0 // eod
};
static const char qt_meta_stringdata_Config[] = {
"Config\0\0okPressed()\0cancelPressed()\0"
};
const QMetaObject Config::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_Config,
qt_meta_data_Config, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &Config::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *Config::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *Config::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_Config))
return static_cast<void*>(const_cast< Config*>(this));
return QDialog::qt_metacast(_clname);
}
int Config::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: okPressed(); break;
case 1: cancelPressed(); break;
default: ;
}
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"jimpar@algo.gr"
] | jimpar@algo.gr |
74c01f6c39f7bbdb4b4acf19516c36bcfecb7e9f | 105ac3f78122b133b632c29ed0cf8648f315bf94 | /src/liblogger/LogCallBack.h | 07e226839451d18ec3388d2ee7adf308c3e7a522 | [
"MIT"
] | permissive | mistralol/liblogger | cb85c53bcb4753280b6f265e77ef6d9c2caf726c | b9b81bd707a9c83e6ec9a7f802a6fff138bed2ec | refs/heads/master | 2020-12-18T13:49:10.833190 | 2020-02-04T15:41:02 | 2020-02-04T15:41:02 | 11,122,237 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 442 | h |
namespace liblogger
{
class LogCallBack : public ILogger
{
public:
LogCallBack(void *arg, void (*CallBack) (void *arg, const LogType Type, const std::string &str));
virtual ~LogCallBack() { };
std::string GetName() const;
std::string GetDesc() const;
void Log(const LogType Type, const std::string &str);
private:
void (*m_CallBack) (void *arg, const LogType Type, const std::string &str);
void *m_arg;
};
};
| [
"james@stev.org"
] | james@stev.org |
740eb9c0adb229733b2994dbe7ce8f811c87a550 | 056341d8631451096731007ee213c1cec91b7386 | /src/floor_plane_extract.cpp | ce404a3872a9c5ba6d04fe2d3664977a402b851c | [] | no_license | qifanz/floor_plane_deep | 8c51e08180baab80aaafd134208108abcdcda068 | 16b5304f548f497929f5fe48e0e95abe26e4b806 | refs/heads/master | 2020-04-02T17:50:16.986008 | 2018-10-25T13:20:33 | 2018-10-25T13:20:33 | 154,674,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,769 | cpp | #include <ros/ros.h>
#include <visualization_msgs/Marker.h>
#include <geometry_msgs/Pose2D.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_ros/point_cloud.h>
#include <pcl_ros/transforms.h>
#include <pcl/point_types.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <sensor_msgs/Image.h>
#include <opencv2/opencv.hpp>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <image_transport/transport_hints.h>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <Eigen/Core>
#include <Eigen/Cholesky>
class FloorPlaneExtract {
protected:
ros::NodeHandle nh_;
image_transport::ImageTransport it_;
image_transport::Subscriber image_sub_;
image_transport::Publisher image_pub_;
ros::Subscriber info_sub_;
ros::Subscriber scan_sub_;
tf::TransformListener listener_;
boost::shared_ptr< message_filters::Subscriber<sensor_msgs::Image> > imgSub;
boost::shared_ptr< message_filters::Subscriber<sensor_msgs::PointCloud2> > pclSub;
typedef message_filters::TimeSynchronizer<sensor_msgs::PointCloud2,sensor_msgs::Image> TS;
boost::shared_ptr<TS> sync;
std::string base_frame_;
std::string world_frame_;
std::string outdir_;
double max_range_;
double height_threshold_;
double min_displacement_;
double min_rotation_;
int thumb_size_;
int max_image_per_type_;
unsigned long image_counter_;
unsigned long traversable_counter_;
unsigned long untraversable_counter_;
bool has_info;
double fx,fy,cx,cy;
geometry_msgs::Pose2D last_pose;
typedef enum {
UNUSABLE,
UNTRAVERSABLE,
TRAVERSABLE
} ThumbType;
ThumbType check_thumb(const cv::Mat_<cv::Vec3b> & thumb,
const cv::Mat_<float> & thumb_z) {
// TODO: Modify this function to take a decision on the traversability of the patch of ground
// corresponding to this image.
int counter=0;
for (int r=0;r<thumb_z.rows;r++) {
for (int c=0;c<thumb_z.cols;c++) {
if (std::isnan(thumb_z(r,c))) {
// ignore this point, it has not been observed from the kinect
return UNUSABLE;
}
else if (thumb_z(r,c)>=0.1) {
counter++;
}
}
}
if (counter>=4) return UNTRAVERSABLE;
else return TRAVERSABLE;
}
protected: // ROS Callbacks
void calibration_callback(const sensor_msgs::CameraInfoConstPtr msg) {
fx=msg->K[0]; cx=msg->K[2];
fy=msg->K[4]; cy=msg->K[5];
has_info = true;
}
void sync_callback(const sensor_msgs::PointCloud2ConstPtr pcl_msg, const sensor_msgs::ImageConstPtr img_msg) {
if (!has_info) return;
tf::StampedTransform tfw;
listener_.waitForTransform(base_frame_,world_frame_,pcl_msg->header.stamp,ros::Duration(1.0));
listener_.lookupTransform(base_frame_,world_frame_,pcl_msg->header.stamp,tfw);
// Check if we moved
if ((hypot(last_pose.x-tfw.getOrigin().x(),last_pose.y-tfw.getOrigin().y())<min_displacement_) &&
(fabs(remainder(last_pose.theta-tf::getYaw(tfw.getRotation()),2*M_PI))<min_rotation_)) {
return;
}
last_pose.x=tfw.getOrigin().x();
last_pose.y=tfw.getOrigin().y();
last_pose.theta=tf::getYaw(tfw.getRotation());
cv::Mat img(cv_bridge::toCvShare(img_msg,"bgr8")->image);
pcl::PointCloud<pcl::PointXYZ> pc_sensor, pc_base;
pcl::fromROSMsg(*pcl_msg, pc_sensor);
// Make sure the point cloud is in the base-frame
listener_.waitForTransform(base_frame_,pcl_msg->header.frame_id,pcl_msg->header.stamp,ros::Duration(1.0));
pcl_ros::transformPointCloud(base_frame_,pcl_msg->header.stamp, pc_sensor, pcl_msg->header.frame_id, pc_base, listener_);
cv::Mat_<float> img_z(img.size(),NAN);
// First build an image of ground height
unsigned int n = pc_sensor.size();
for (unsigned int i=0;i<n;i++) {
float x = pc_sensor[i].x;
float y = pc_sensor[i].y;
float z = pc_sensor[i].z;
if (z > max_range_) {
// Ignoring points too far out.
continue;
}
int ix = round(cx - x*fx/z);
int iy = round(cy - y*fy/z);
if ((ix < 0) || (ix >= img_z.cols) || (iy < 0) || (iy >= img_z.rows)) {
// Outside of the image. This is not possible, but may
// happen due to numerical uncertainties.
continue;
}
img_z(iy,ix) = pc_base[i].z;
}
for (int r=0;r<img.rows;r+=thumb_size_) {
if (r+thumb_size_>img.rows) { continue; }
for (int c=0;c<img.cols;c+=thumb_size_) {
// printf("r %d c %d\n",r,c);
if (c+thumb_size_>img.cols) { continue; }
cv::Rect roi(c,r,thumb_size_,thumb_size_);
cv::Mat thumb = img(roi);
cv::Mat_<float> thumb_z = img_z(roi);
ThumbType type = check_thumb(thumb,thumb_z);
//printf("type : %d\n",type);
if ((type == TRAVERSABLE) && (traversable_counter_>=(unsigned)max_image_per_type_)) {
// We have enough images of this type
type = UNUSABLE;
}
if ((type == UNTRAVERSABLE) && (untraversable_counter_>=(unsigned)max_image_per_type_)) {
// We have enough images of this type
type = UNUSABLE;
}
if (type != UNUSABLE) {
// Old fashion formatting
char dirname[1024],filename[1024],labelname[1024];
sprintf(dirname,"%s/%04ld",outdir_.c_str(),image_counter_/1000);
mkdir(dirname,0700);// may already exist but it is OK
sprintf(filename,"%s/%04ld/%04ld.png",outdir_.c_str(),image_counter_/1000,image_counter_%1000);
cv::imwrite(filename,thumb);
sprintf(labelname,"%s/labels.txt",outdir_.c_str());
FILE * fp = fopen(labelname,"a");
fprintf(fp,"%04ld/%04ld.png %d\n",image_counter_/1000,image_counter_%1000,(type==TRAVERSABLE)?1:0);
fclose(fp);
image_counter_ ++ ;
if (type == TRAVERSABLE) {
traversable_counter_ ++;
} else {
untraversable_counter_ ++;
}
}
// Now for display (could be disabled to save CPU)
int mark = 0;
switch (type) {
case UNTRAVERSABLE:
mark = 2; break;
case TRAVERSABLE:
mark = 1; break;
case UNUSABLE:
default:
mark = 0; break;
}
for (int tr=0;tr<thumb.rows;tr++) {
for (int tc=0;tc<thumb.cols;tc++) {
thumb.at<cv::Vec3b>(tr,tc)[mark] = 255;
}
}
// getchar();
}
}
printf("Image counter at %ld (%ld / %ld)\n",image_counter_,traversable_counter_,untraversable_counter_);
cv_bridge::CvImage br(img_msg->header,"bgr8",img);
image_pub_.publish(br.toImageMsg());
}
public:
FloorPlaneExtract() : nh_("~"), it_(nh_) {
has_info = false;
nh_.param("world_frame",world_frame_,std::string("/world"));
nh_.param("base_frame",base_frame_,std::string("/body"));
nh_.param("max_range",max_range_,5.0);
nh_.param("thumb_size",thumb_size_,32);
nh_.param("out_dir",outdir_,std::string("."));
nh_.param("height_threshold",height_threshold_,0.02);
nh_.param("min_displacement",min_displacement_,0.1);
nh_.param("min_rotation",min_rotation_,0.1);
nh_.param("max_image_per_type",max_image_per_type_,1000);
std::string transport = "raw";
nh_.param("transport",transport,transport);
// Reset label file
char labelname[1024];
sprintf(labelname,"%s/labels.txt",outdir_.c_str());
FILE * fp = fopen(labelname,"w");
assert(fp);
fclose (fp);
image_counter_ = 0;
traversable_counter_ = 0;
untraversable_counter_ = 0;
// Make sure TF is ready
ros::Duration(0.5).sleep();
tf::StampedTransform tfw;
listener_.lookupTransform(base_frame_,world_frame_,ros::Time(0),tfw);
last_pose.x=tfw.getOrigin().x()-1.0;
last_pose.y=tfw.getOrigin().y()-1.0;
last_pose.theta=tf::getYaw(tfw.getRotation());
image_pub_ = it_.advertise("image_label",1);
info_sub_ = nh_.subscribe("info",1,&FloorPlaneExtract::calibration_callback,this);
// scan_sub_ = nh_.subscribe("scans",1,&FloorPlaneExtract::pc_callback,this);
// image_sub_ = it_.subscribe<FloorPlaneExtract>("image",1, &FloorPlaneExtract::image_callback,this,transport);
// Created a synchronized subscriber for point cloud and image. The
// need for pointer is suspicious, but it works this way.
imgSub.reset(new message_filters::Subscriber<sensor_msgs::Image>(nh_,"image",1));
pclSub.reset(new message_filters::Subscriber<sensor_msgs::PointCloud2>(nh_,"pointcloud",1));
sync.reset(new TS(*pclSub,*imgSub,50));
sync->registerCallback(boost::bind(&FloorPlaneExtract::sync_callback,this,_1,_2));
}
};
int main(int argc, char * argv[])
{
ros::init(argc,argv,"floor_plane_Extract");
FloorPlaneExtract fp;
ros::spin();
return 0;
}
| [
"qzhang@gtlpc120.georgiatech-metz.fr"
] | qzhang@gtlpc120.georgiatech-metz.fr |
486dbebe1dc9aa2d97b495caed443f9617d92f48 | cb3e816a281e49aff1b7a72e71db21eb64a3fe77 | /agc022/a.cpp | 0be4b998bbb9f1f666878d75f2160aa4a5365238 | [] | no_license | noy72/atcoder | 2a8cf4f7ad085e0e48cb1b3b71db055fa8b4a893 | 6b601f7631a9a61d3c5bcdd9e6ab1e4932134293 | refs/heads/master | 2018-12-27T11:33:54.285973 | 2018-10-24T07:44:56 | 2018-10-24T07:44:56 | 115,201,645 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 920 | cpp | #include<bits/stdc++.h>
#define range(i,a,b) for(int i = (a); i < (b); i++)
#define rep(i,b) for(int i = 0; i < (b); i++)
#define all(a) (a).begin(), (a).end()
#define show(x) cerr << #x << " = " << (x) << endl;
using namespace std;
template<typename T>
ostream& operator << (ostream& os, vector<T>& v){
rep(i,v.size()){ os << v[i] << (i == v.size() - 1 ? "" : " "); } return os;
}
template<typename T>
istream& operator >> (istream& is, vector<T>& v){
for(T& x: v){ is >> x; } return is;
}
int main(){
string s;
cin >> s;
set<char> st(all(s));
if(st.size() == 26){
int i = 25;
while(i != 0 and s[i - 1] > s[i]){
i--;
}
if(i == 0){
cout << -1 << endl;
return 0;
}
char c = 127;
range(j,i,s.size()){
if(s[i - 1] > s[j]) continue;
c = min(c, s[j]);
}
cout << s.substr(0,i - 1) + c << endl;
}else{
char i = 'a';
while(st.count(i)){
i++;
}
cout << s + i << endl;
}
}
| [
"kuma.tola3@gmail.com"
] | kuma.tola3@gmail.com |
03ec000179bd5391a11dee7d05827ce16712ccdc | 572470cc048dbc02756b589debc1853d55acc32d | /game.cpp | e74d89f84e943780bb873884e71942947f19be8a | [] | no_license | 1VermaRahul/Qtgame | 20b208ce3409ecde2ebad2a4400672e1092351eb | f0975a67fc5eb16f6ece6fc314b4d9f6b1d9fc9e | refs/heads/master | 2021-06-23T22:49:46.689527 | 2017-08-14T06:55:53 | 2017-08-14T06:55:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,386 | cpp | #include"game.h"
#include<QGraphicsPixmapItem>
#include <QGraphicsScene>
#include "myrect.h"
#include <QGraphicsView>
#include<QTimer>
#include"score.h"
#include"bullet.h"
#include<QMediaPlayer>
#include"myrect.h"
#include<QImage>
Game::Game(QWidget *parent)
{
QGraphicsScene *scene=new QGraphicsScene();
QGraphicsView *view=new QGraphicsView(scene);
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->show();
view->setFixedSize(800,600);
scene->setSceneRect(0,0,800,600);
setBackgroundBrush(QBrush(QImage(":/images/bg2.jpg")));
// rect->setPos(view->width()/2,view->height());
rect=new myrect();
rect->setPixmap(QPixmap(":/images/player1.jpg"));
rect->setPos(400,500);
//adding score to that
rect->setFlag(QGraphicsItem::ItemIsFocusable);
rect->setFocus();
scene->addItem(rect);
Score=new score();
scene->addItem(Score);
//adding health
Hlth=new health();
Hlth->setPos(Hlth->x(),Hlth->y()+25);
scene->addItem(Hlth);
//spawn enemy
QTimer *timer = new QTimer();
QObject::connect(timer,SIGNAL(timeout()),rect,SLOT(spawn()));
timer->start(2000);
QMediaPlayer *music=new QMediaPlayer();
music->setMedia(QUrl("qrc:/sounds/asla.mp3"));
music->play();
}
| [
"noreply@github.com"
] | noreply@github.com |
5ea6dd5070ef2ba1fee896acabfad16ad50be186 | 910946e8f76f8467f32dd6a5cebfbf4803121dd9 | /dialogpersonalreport.cpp | 738ac4e29cb24d703c902bd6e71b76e86bfedad5 | [] | no_license | doctarhyf/busManager | acbc90e7a35c6eb34ed197781e1fea2d5e0ebebe | 447c962e990063aa41a0f65ac4fd163a89b5b823 | refs/heads/master | 2021-08-06T16:07:26.316778 | 2021-06-30T19:14:19 | 2021-06-30T19:14:19 | 131,071,991 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | cpp | #include "dialogpersonalreport.h"
#include "ui_dialogpersonalreport.h"
DialogPersonalReport::DialogPersonalReport(QWidget *parent, int newTicketerID) :
QDialog(parent),
ui(new Ui::DialogPersonalReport)
{
ticketerID = newTicketerID;
ui->setupUi(this);
setWindowTitle("Mon Rapport de Vente");
dbManager = new DBManager;
model = new QSqlQueryModel;
model->setQuery("SELECT * FROM ticket WHERE ticketer_id = " + QString::number(ticketerID));
ui->tableView->setModel(model);
//setup();
qDebug() << "PERS REP TKTR ID : " << ticketerID;
}
void DialogPersonalReport::setup()
{
}
DialogPersonalReport::~DialogPersonalReport()
{
delete ui;
}
int DialogPersonalReport::getTicketerID() const
{
return ticketerID;
}
void DialogPersonalReport::setTicketerID(int value)
{
ticketerID = value;
}
void DialogPersonalReport::closeEvent(QCloseEvent *e)
{
//qDebug() << "emited ... signal closeevent";
emit onWindowClosed(e);
}
| [
"drrhyf@gmail.com"
] | drrhyf@gmail.com |
adfbceebbbe1799abdcf9621815966cdb49693b5 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-gamelift/source/model/DescribeFleetLocationAttributesRequest.cpp | 78693e9a72e228e1ef17ac187b58b6cfd60e93ef | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 1,634 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/gamelift/model/DescribeFleetLocationAttributesRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::GameLift::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeFleetLocationAttributesRequest::DescribeFleetLocationAttributesRequest() :
m_fleetIdHasBeenSet(false),
m_locationsHasBeenSet(false),
m_limit(0),
m_limitHasBeenSet(false),
m_nextTokenHasBeenSet(false)
{
}
Aws::String DescribeFleetLocationAttributesRequest::SerializePayload() const
{
JsonValue payload;
if(m_fleetIdHasBeenSet)
{
payload.WithString("FleetId", m_fleetId);
}
if(m_locationsHasBeenSet)
{
Aws::Utils::Array<JsonValue> locationsJsonList(m_locations.size());
for(unsigned locationsIndex = 0; locationsIndex < locationsJsonList.GetLength(); ++locationsIndex)
{
locationsJsonList[locationsIndex].AsString(m_locations[locationsIndex]);
}
payload.WithArray("Locations", std::move(locationsJsonList));
}
if(m_limitHasBeenSet)
{
payload.WithInteger("Limit", m_limit);
}
if(m_nextTokenHasBeenSet)
{
payload.WithString("NextToken", m_nextToken);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DescribeFleetLocationAttributesRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "GameLift.DescribeFleetLocationAttributes"));
return headers;
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
e1856cefce6b6ca975e409ddfa81935b26f786fd | d464982fb70ef555188a7d79df55f6282f2912de | /ggNtuplesAnalyzer/plugins/ggNtuplesFilesReader.h | 259a76dc41d23253bf908e589c828b1f3bf89694 | [] | no_license | elizamelo/EstagiodeVerao2018 | 31b41a08fadc7b794799f37b280ab719629a4d88 | b9db8c332425a0a0eb3dfcd0bf37abcd9819cacc | refs/heads/master | 2020-03-23T13:03:46.109666 | 2018-08-10T13:19:34 | 2018-08-10T13:19:34 | 141,563,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 668 | h | // #################################################
// -- reads the ggNtuples
// -- loads then into a TChain
// -- returns a TTreeReader for the TChain
// #################################################
#include "TChain.h"
#include "TTreeReader.h"
using namespace std;
TTreeReader * ggNtuplesFilesReader(vector<string> ggNtuplesFiles, string treeName)
{
TChain * chain = new TChain(treeName.c_str());
for(unsigned int i = 0; i < ggNtuplesFiles.size(); i++) {
// cout << "Adding file: " << ggNtuplesFiles[i] << endl;
chain->AddFile( ggNtuplesFiles[i].c_str() );
}
// chain->Print();
TTreeReader * reader = new TTreeReader(chain);
return reader;
}
| [
"eliza@cern.ch"
] | eliza@cern.ch |
be3c327f83c4da1786bc0df50cae01defe57826c | 1b0dc7977794738e5a4779b8b6e68dad0cd2a479 | /20150912MCA/MCA/CommunicationPortDlg.cpp | e76f422f92f4f196e3c820bf45669d7cc330707c | [] | no_license | Cangjr10/Specified-MCA-for-DPP-Protocol | 43b22b959c7f79d66da7dbb563c34349fa54f508 | 46be9a47df6eebb2d3252a2cb43e849f0be0eadf | refs/heads/master | 2021-01-22T14:39:30.193707 | 2015-09-30T04:25:24 | 2015-09-30T04:25:24 | 32,555,286 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,372 | cpp | // CommunicationPortDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "MCA.h"
#include "CommunicationPortDlg.h"
#include "afxdialogex.h"
#include "MCADoc.h"
// CCommunicationPortDlg 对话框
IMPLEMENT_DYNAMIC(CCommunicationPortDlg, CDialogEx)
CCommunicationPortDlg::CCommunicationPortDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CCommunicationPortDlg::IDD, pParent)
, m_nCommDlg(2)
, m_nBaudrateDlg(0)
, m_nTimeRequestDlg(3000)
, m_RS232(TRUE)
,m_nPortFlag(FALSE)
{
pFrame = (CMainFrame*)AfxGetMainWnd();
CMCADoc* pDoc = (CMCADoc*)pFrame->GetActiveDocument();
pDoc->GetActiveCommunicationDlg(this);
}
CCommunicationPortDlg::~CCommunicationPortDlg()
{
CMCADoc* pDoc = (CMCADoc*)pFrame->GetActiveDocument();
pDoc->SetCommandFlag(S_NULL);
}
void CCommunicationPortDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_CBIndex(pDX, IDC_COMBO_COM, m_nCommDlg);
DDX_CBIndex(pDX, IDC_COMBO_BAUD, m_nBaudrateDlg);
DDX_Text(pDX, IDC_EDIT_REQUESRTIME, m_nTimeRequestDlg);
DDX_Control(pDX, IDC_COMBO_COM, m_CommDlg);
DDX_Control(pDX, IDC_COMBO_BAUD, m_BaudDlg);
DDX_Control(pDX, IDC_EDIT_DEVICEINFO, m_DeviceInfo);
}
BEGIN_MESSAGE_MAP(CCommunicationPortDlg, CDialogEx)
ON_BN_CLICKED(IDCONNECT, &CCommunicationPortDlg::OnBnClickedConnect)
ON_BN_CLICKED(IDC_BUTTON_SETDEFAULTTIME, &CCommunicationPortDlg::OnBnClickedButtonSetdefaulttime)
ON_BN_CLICKED(IDC_BUTTON_OpenPort, &CCommunicationPortDlg::OnBnClickedButtonOpenport)
ON_BN_CLICKED(IDC_BUTTON_FINDDEVICE, &CCommunicationPortDlg::OnBnClickedButtonFinddevice)
// ON_WM_SETTINGCHANGE()
ON_BN_CLICKED(IDCANCEL, &CCommunicationPortDlg::OnBnClickedCancel)
END_MESSAGE_MAP()
// CCommunicationPortDlg 消息处理程序
BOOL CCommunicationPortDlg::OnInitDialog()
{
try{
CDialogEx::OnInitDialog();
CString str;
for (int i=1;i<25;i++)
{
//查询可用串口
// try
// {
// pFrame->m_SCIModule.put__CommPort(i);//选择com口
// pFrame->m_SCIModule.put_PortOpen(1);
// if(pFrame->m_SCIModule.get_PortOpen())
// {
// CString strtemp;
// strtemp.Format(_T("串口%d打开成功"),i);
// AfxMessageBox(strtemp);
// CString strtemp1;
// strtemp1.Format(_T("com%d"),i);
// m_CommDlg.AddString(strtemp1);
// pFrame->m_SCIModule.put_PortOpen(0);
// }
// }
// catch(...)
// {
// }
str.Format(_T("COM%d"),i);
m_CommDlg.AddString(str);
}
str_baudrate.push_back(_T("4800"));
str_baudrate.push_back(_T("9600"));
str_baudrate.push_back(_T("19200"));
str_baudrate.push_back(_T("38400"));
str_baudrate.push_back(_T("57600"));
str_baudrate.push_back(_T("115200"));//CString类型存储的是string变量的首地址,每个元素占四个字节
for (int i=0;i < static_cast<int>(str_baudrate.size());i++)
{
m_BaudDlg.AddString(str_baudrate[i]);
}
//m_nBaudrateDlg = str_baudrate.size()-1;
CheckDlgButton(IDC_RADIO_RS232, 1);
CMCADoc* pMCADoc = (CMCADoc*)pFrame->GetActiveDocument();
pMCADoc->UpdateCommunicationDlgInfo(m_nCommDlg,m_nBaudrateDlg,m_nTimeRequestDlg,FALSE);
UpdateData(FALSE);
}
catch(...)
{
AfxMessageBox(_T("CCommunicationPortDlg::OnInitDialog!"));
}
return TRUE;
// 异常: OCX 属性页应返回 FALSE
}
void CCommunicationPortDlg::OnBnClickedButtonSetdefaulttime()
{
// TODO: 在此添加控件通知处理程序代码
m_nTimeRequestDlg = 5000;
UpdateData(FALSE);
}
void CCommunicationPortDlg::OnBnClickedButtonOpenport()
{
// TODO: 在此添加控件通知处理程序代码
try{
UpdateData(TRUE);
CString Com_Config=_T("");
Com_Config += str_baudrate[m_nBaudrateDlg];
Com_Config += _T(",n,8,1");
m_nPortFlag=pFrame->m_SCIModule.get_PortOpen();
if (m_nPortFlag == FALSE)
{
pFrame->m_SCIModule.put__CommPort(m_nCommDlg+1);//选择com口
pFrame->m_SCIModule.put_InputMode(1);//输入方式为二进制方式
pFrame->m_SCIModule.put_InBufferSize(30000);//输入缓冲区大小为1024byte
pFrame->m_SCIModule.put_OutBufferSize(512);//输出缓冲区大小为512byte
pFrame->m_SCIModule.put_Settings(Com_Config);//设置串口参数:9600波特率,无奇偶校验,8个数据位,1个停止位
if(!pFrame->m_SCIModule.get_PortOpen() )//获取串口的当前状态
{
pFrame->m_SCIModule.put_PortOpen(1);//打开串口
m_nPortFlag = TRUE;
}
pFrame->m_SCIModule.put_RThreshold(6);//每当串口接收缓冲区有多余或等于1个字符时将引发一个接收数据的oncomm事件
pFrame->m_SCIModule.put_InputLen(0);//设置当前接收区数据长度为0
pFrame->m_SCIModule.get_Input();//预读缓冲区以清空残留数据
SetDlgItemTextW(IDC_BUTTON_OpenPort,_T("Close Port"));
}
else
{
pFrame->m_SCIModule.put_PortOpen(0);//关闭串口
m_nPortFlag = FALSE;
SetDlgItemTextW(IDC_BUTTON_OpenPort,_T("Open Port"));
}
}
catch(...)
{
AfxMessageBox(_T("CCommunicationPortDlg::OnBnClickedButtonOpenport!"));
}
}
void CCommunicationPortDlg::OnBnClickedButtonFinddevice()
{
// TODO: 在此添加控件通知处理程序代码
try{
byte Connect_Command[] ={0xF5, 0xFA, 0x03, 0x07, 0x00, 0x00, 0xFE, 0x07};
pFrame->m_SCIModule.SendArray(Connect_Command,sizeof(Connect_Command));
//设置CommandFlag标志
CMCADoc* pDoc = (CMCADoc*)pFrame->GetActiveDocument();
pDoc->SetCommandFlag(S_Connection);
}
catch(...)
{
AfxMessageBox(_T("CCommunicationPortDlg::OnBnClickedButtonFinddevice!"));
}
/* pDoc->UpdateCommunicationDlgInfo(m_nCommDlg , m_nBaudrateDlg, m_nTimeRequestDlg,TRUE);*/
}
void CCommunicationPortDlg::OnBnClickedConnect()
{
// TODO: 在此添加控件通知处理程序代码
//保存串口配置信息
try{
UpdateData(TRUE);
CMCADoc* pDoc = (CMCADoc*)pFrame->GetActiveDocument();
pDoc->UpdateCommunicationDlgInfo(m_nCommDlg , m_nBaudrateDlg, m_nTimeRequestDlg,TRUE);
}
catch(...)
{
AfxMessageBox(_T("CCommunicationPortDlg::OnBnClickedConnect!"));
}
CDialogEx::OnOK();
}
void CCommunicationPortDlg::OnBnClickedCancel()
{
// TODO: 在此添加控件通知处理程序代码
try{
if (pFrame->m_SCIModule.get_PortOpen())
{
pFrame->m_SCIModule.put_PortOpen(0);//关闭串口
}
UpdateData(TRUE);
CMCADoc* pDoc = (CMCADoc*)pFrame->GetActiveDocument();
pDoc->UpdateCommunicationDlgInfo(m_nCommDlg , m_nBaudrateDlg, m_nTimeRequestDlg,TRUE);
m_nPortFlag = FALSE;
}
catch(...)
{
AfxMessageBox(_T("CCommunicationPortDlg::OnBnClickedCancel!"));
}
CDialogEx::OnCancel();
}
| [
"cangjr14@mails.tsinghua.edu.cn"
] | cangjr14@mails.tsinghua.edu.cn |
6820b80954935162a17b6231fcba67d13db47a3b | 320539b279df7a086b294ca3311febedfa37926c | /svg/beziercurve.cpp | ed4d4273b9ed46f82fa8e50588fc56b8aa085c2d | [] | no_license | ZackMisso/ZGUI | 2cc2f6dd0eb9b18c1042bda8ab9a0408400554cd | 719e46ba8ffe6052123e2b7d5aec580abc3cc04e | refs/heads/master | 2021-01-17T12:44:12.340023 | 2016-07-04T22:00:51 | 2016-07-04T22:00:51 | 59,065,510 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,105 | cpp | #include "beziercurve.h"
BezierCurve::BezierCurve() {
controlPoints = new Array<vec2>();
curve = new Array<vec2>();
continuous = true;
wrapAround = true;
dirty = true;
}
BezierCurve::BezierCurve(Array<vec2>* pts) {
controlPoints = pts;
curve = new Array<vec2>();
continuous = true;
wrapAround = true;
dirty = true;
}
BezierCurve::~BezierCurve() {
delete controlPoints;
delete curve;
}
Array<vec2>* BezierCurve::getCurve() {
if(dirty) {
evaluateCurve();
dirty = false;
}
return curve;
}
void BezierCurve::setProperties(bool wrap,bool cont) {
wrapAround = wrap;
continuous = cont;
}
void BezierCurve::copyIntoCurve(const Array<vec2>* control,const Array<vec2>* pts,BezierCurve* bCurve) {
bCurve->controlPoints->clear();
bCurve->curve->clear();
for(int i=0;i<control->getSize();i++) bCurve->controlPoints->add(control->get(i));
for(int i=0;i<pts->getSize();i++) bCurve->curve->add(pts->get(i));
}
Array<vec2>* BezierCurve::getControlPoints() { return controlPoints; }
void BezierCurve::setControlPoints(Array<vec2>* param) { controlPoints = param; }
| [
"zack441@mac.com"
] | zack441@mac.com |
63ee5a433828610c33744e6ccd847d0ee4be1a91 | 1dd8a2d1a5e85c90d94a6011c09a0bf13dd431de | /HopStep/HopStep/Timer.cpp | f01548d16cae0ef8ffa6b109e90cc4ec8ab6f510 | [] | no_license | highfence/HopStep_Prev | 64b254c3c0b1188f88991d578ebaaacaa98a0e05 | 80827312cffc4afe7a759c7c9b8255a89b91057f | refs/heads/master | 2022-03-26T16:36:05.789051 | 2020-02-03T03:31:22 | 2020-02-03T03:31:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 787 | cpp | #include "stdafx.h"
#include "Timer.h"
namespace HopStep
{
GameTimer::GameTimer()
: m_UseQPF(false), m_ElapsedTime(0.f), m_QPFTicksPerSec(0), m_LastElapsedTime(0)
{
}
GameTimer::~GameTimer()
{
}
void GameTimer::InitTimer()
{
LARGE_INTEGER qwTicksPerSec, qwTime;
m_UseQPF = (bool)(QueryPerformanceFrequency(&qwTicksPerSec) != 0);
if (m_UseQPF == false)
return;
m_QPFTicksPerSec = qwTicksPerSec.QuadPart;
QueryPerformanceCounter(&qwTime);
m_LastElapsedTime = qwTime.QuadPart;
}
void GameTimer::ProcessTime()
{
if (m_UseQPF == false)
return;
LARGE_INTEGER qwTime;
QueryPerformanceCounter(&qwTime);
m_ElapsedTime = (float)((double)(qwTime.QuadPart - m_LastElapsedTime) / (double)m_QPFTicksPerSec);
m_LastElapsedTime = qwTime.QuadPart;
}
}
| [
"highfence@naver.com"
] | highfence@naver.com |
2ea6dac6fcddc576715a3d8206c80b00c403b374 | 1bd5821ed4a202ca429750a762b17f48cb8d2559 | /commonthings.h | db5cb4f5f133102718af7a63698c0db18e48cec1 | [] | no_license | anphan2410/edctuCanBusWorker | e35327711cabc0ed3f81557c59048f8cd69907f4 | 4998f6b5ad8d00322f76489ac9845b09578de0a3 | refs/heads/master | 2021-01-23T15:27:39.233367 | 2017-09-08T05:15:56 | 2017-09-08T05:15:56 | 102,711,053 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,968 | h | #ifndef COMMONTHINGS_H
#define COMMONTHINGS_H
#include <QHash>
#include <QByteArray>
inline QByteArray &operator <<(QByteArray &QBArr, const quint8 Data)
{
QBArr.append(Data);
return QBArr;
}
inline QByteArray &operator <<(QByteArray &QBArr, const quint16 Data)
{
return QBArr<<quint8(Data>>8)<<quint8(Data);
}
inline QByteArray &operator <<(QByteArray &QBArr, const quint32 Data)
{
return QBArr<<quint16(Data>>16)<<quint16(Data);
}
inline QByteArray &operator <<(QByteArray &QBArr, const quint64 Data)
{
return QBArr<<quint32(Data>>32)<<quint32(Data);
}
inline QByteArray &operator <<(QByteArray &QBArr, const QByteArray &Data)
{
QBArr.append(Data);
return QBArr;
}
template <typename TN>
const QHash<TN, QString> SwapKeyValOnOneToOneQHash(const QHash<QString, TN> &AQHashKeyValset)
{
QHash<TN, QString> &tmp = * new QHash<TN, QString>();
QString tmp2 = "";
auto KeyItr = AQHashKeyValset.keyBegin();
for (; KeyItr!=AQHashKeyValset.keyEnd(); KeyItr++)
{
tmp2 = *KeyItr;
tmp.insert(AQHashKeyValset.value(tmp2), tmp2);
}
return tmp;
}
inline static quint8 XORofAllBytesInQByteArr(const QByteArray &QBArr)
{
if (!(QBArr.isNull() || QBArr.isEmpty()))
{
QByteArray::const_iterator ConstItr = QBArr.constBegin();
quint8 IntTmp = *(ConstItr++);
for (;ConstItr!=QBArr.cend(); ConstItr++)
{
IntTmp ^=*ConstItr;
}
return IntTmp;
}
else
return 0;
}
///
/// \brief IntStr2QBArr0Pad
/// \param Num
/// \param SizeInByte
/// \return QByteArray contains a hex number
/// representing an integer number encoded by Ascii code
///
inline static const QByteArray IntStr2QBArr0Pad(const quint32 Num, const quint8 SizeInByte, char padChar = '0')
{
QString QStrTmp = QString::number(Num);
return QStrTmp.prepend(QString("").fill(padChar,SizeInByte-QStrTmp.size())).toLocal8Bit();
}
#endif // COMMONTHINGS_H
| [
"an.phan@ascenx.com"
] | an.phan@ascenx.com |
7165d583b7ac2824cca80684b66a2cb2f5f69f1e | 6f0f0faa9be4219b2aee36ccbe2130bc012d4aac | /src/XMPP/StringList.h | 18ba41741678ea4e866cd01a85ee30ccd9d59305 | [] | no_license | remko/beautiful-xmpp-testing | b0e476782f647a75f36f4883c8481a1ef77f359c | e6f04dca811bc3ee1cae423ccc3ec6afec384bae | refs/heads/master | 2021-01-10T05:04:42.215188 | 2013-02-24T13:32:32 | 2013-02-24T13:32:32 | 8,390,946 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 158 | h | #pragma once
class StringList {
public:
StringList() {
}
bool contains(const std::string&) {
return true;
}
int size() {
return 2;
}
};
| [
"git@el-tramo.be"
] | git@el-tramo.be |
21f1c66ca8a164bb71910fb8debf9f7c5a7e1076 | 7278f41df35abadd396dc172b27593f90ff02407 | /include/mesh_motion/FrameReference.h | fd12b66950436985f7decbdcf6d11fe7c9d83bf6 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | wilsonrvornlgov/nalu-wind | 2721082645033dde5d058df4ae10cbbb3df06fa1 | a44b7a30d79277329495e43b89e4d968ad3fc9c8 | refs/heads/main | 2022-01-30T03:28:57.043911 | 2022-01-18T20:24:03 | 2022-01-18T20:24:03 | 206,165,061 | 2 | 0 | NOASSERTION | 2019-09-03T20:19:17 | 2019-09-03T20:19:17 | null | UTF-8 | C++ | false | false | 570 | h | #ifndef FRAMEREFERENCE_H
#define FRAMEREFERENCE_H
#include "FrameBase.h"
#include "yaml-cpp/yaml.h"
#include <cassert>
#include <float.h>
namespace sierra{
namespace nalu{
class FrameReference : public FrameBase
{
public:
FrameReference(
stk::mesh::BulkData& bulk,
const YAML::Node& node
) : FrameBase(bulk,node)
{
}
virtual ~FrameReference()
{
}
void update_coordinates(const double time);
private:
FrameReference() = delete;
FrameReference(const FrameReference&) = delete;
};
} // nalu
} // sierra
#endif /* FRAMEREFERENCE_H */
| [
"noreply@github.com"
] | noreply@github.com |
6bfab86c084c4af1d6768143c7c1e16b2510797f | edef4a359d91e6d849480dce6852a133ee2a9dea | /Programacion-II/I Parcial/PROGRAMA 1/main.cpp | df19327e3ac4f724cf6b1b0bea1703bad92dc59e | [] | no_license | Oseas1995/Programacion-II | b0614cd8de035f34359357bb9e96b925e53ea6ba | 345e342d5f9fff608e8cf2cf2d5e10aa819bccf0 | refs/heads/master | 2020-03-22T15:00:51.708008 | 2018-07-09T03:25:02 | 2018-07-09T03:25:02 | 140,221,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,568 | cpp | #include <iostream>
using namespace std;
class complejo{
friend complejo operator-(const complejo&,const complejo&);
private:
float real, imaginario;
public:
complejo();
complejo(float,float);
void imprimir()const;
complejo *suma(const complejo &)const;
complejo operator+(const complejo&)const;
bool operator==(const complejo&)const;
};
int main()
{
complejo z;
z.imprimir();
complejo z1(1,-2);
z1.imprimir();
complejo*z3=z.suma(z1);
z3->imprimir();
//complejo*z4=z+z1;
//z4->imprimir();
complejo z5=z+z1;
if(z5==z)
cout<<"SOn iguales";
else
cout<<"NO son iguales";
z5.imprimir();
complejo z6=z-z1;
z6.imprimir();
return 0;
}
complejo::complejo(){
real=0;
imaginario=0;
}
complejo::complejo(float a, float b){
real=a;
imaginario=b;
}
void complejo::imprimir()const{
if(imaginario>=0)
cout << real << "+" << imaginario << "i" << endl << endl;
else
cout << real << imaginario << "i" << endl;
}
complejo *complejo::suma(const complejo &z1)const{
complejo z3;
z3.real =real + z1.real;
z3.imaginario =real + z1.imaginario;
return &z3;
}
complejo complejo::operator +(const complejo&w)const{
complejo s;
s.real=this->real+w.real;
s.imaginario=imaginario+w.imaginario;
return s;
}
complejo operator-(const complejo&z,const complejo&w){
complejo r;
r.real=z.real-w.real;
r.imaginario=z.imaginario-w.imaginario;
return r;
}
bool complejo::operator==(const complejo&w)const{
return (real==w.real)&&(imaginario==w.imaginario);
}
| [
"oseasmejia95@yahoo.es"
] | oseasmejia95@yahoo.es |
0b507d8db568449d966ec44fe969fe6e4506335a | bc82865ffb1caf191a5b1537d5c6fa1f33a81fa5 | /src/serializer/Reshape.h | 743dde3e0c2f202779aa66745cdf144f8fe55240 | [
"Apache-2.0"
] | permissive | yytdfc/cpp-torch | de64f3d7cc332e36ab843aca14a1f26c27e2e75b | 8eebba4bece2811079d61a20f51f56b14094a729 | refs/heads/master | 2021-01-19T10:54:27.253638 | 2017-08-07T06:06:41 | 2017-08-07T06:06:41 | 99,531,797 | 4 | 1 | null | 2017-08-07T03:11:29 | 2017-08-07T03:11:29 | null | UTF-8 | C++ | false | false | 787 | h | #pragma once
#include "../../include/nn/Reshape.h"
namespace cpptorch
{
namespace serializer
{
template<typename T, GPUFlag F>
class Reshape : public nn::Reshape<T, F>
{
public:
void unserialize(const object_torch *obj, object_reader<T, F> *mb)
{
const object_table *obj_tbl = obj->data_->to_table();
this->nelement_ = *obj_tbl->get("nelement");
mb->build_from_size_storage(obj_tbl->get("size"), this->size_);
mb->build_from_size_storage(obj_tbl->get("batchsize"), this->batchsize_);
const object *batch_mode = obj_tbl->get("batchMode");
this->batch_mode_ = batch_mode ? *batch_mode : false;
}
};
}
}
| [
"tuotuoxp@gmail.com"
] | tuotuoxp@gmail.com |
acf0d5d1ee15e79663ab9d19c40aa7d9b0dd243e | b78a6aeefa4e46f9d8a3ad56e22bf7034de913e8 | /hc/pratice/algorithm/dp_All_Backpack.cpp | 310af2128524a499a54b2ff08a66dd3474ae6f10 | [] | no_license | hchc32/TeamC | c12589d2fb78f46d53b0adaf49b32e05476e454e | d137de654ef8f9ea6750c2d79221dfd1a98a3a7a | refs/heads/master | 2020-12-11T10:28:44.013750 | 2020-07-14T09:53:47 | 2020-07-14T09:53:47 | 233,823,773 | 0 | 0 | null | 2020-01-14T11:13:49 | 2020-01-14T11:13:49 | null | UTF-8 | C++ | false | false | 511 | cpp | /*
f[i] 表示总体积是i的情况下,最大价值是多少
result = max{F[0...m]}
状态转移方程(从前往后考虑每个物品)
*/
#include <iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int n,m;
int w[1050],v[1050],f[1050];
int i,j;
int main()
{
cin >> n >> m;
for(i = 1 ;i <= n ; i++ )
cin >> w[i] >> v[i];
for(i = 1; i <= n; i++)
for(j = w[i];j <= m;j++ )
f[j]=max(f[j],f[j-w[i]]+v[i]);
cout << f[m] <<endl;
return 0;
}
| [
"1844382037@qq.com"
] | 1844382037@qq.com |
374778112b71bcca12c18ba1d1fccf29980e1f83 | 6752911b53c17ad5d1d20707dc099c88ef0c8e13 | /backup/nachos-scheduling-master/userprog/addrspace.cc | 7db314145627ea8e74a3bbf9b0351de3a3ad9ff6 | [] | no_license | luckysahani/Operating-System-Assignments | 6644435e24f26037b2bd9bc92f1dacf234d19fba | 8cba923e66bfe2f3c64c4eec970573fe7d199fae | refs/heads/master | 2023-08-08T15:10:48.500278 | 2023-07-20T11:40:45 | 2023-07-20T11:40:45 | 23,835,995 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,395 | cc | // addrspace.cc
// Routines to manage address spaces (executing user programs).
//
// In order to run a user program, you must:
//
// 1. link with the -N -T 0 option
// 2. run coff2noff to convert the object file to Nachos format
// (Nachos object code format is essentially just a simpler
// version of the UNIX executable object code format)
// 3. load the NOFF file into the Nachos file system
// (if you haven't implemented the file system yet, you
// don't need to do this last step)
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "system.h"
#include "addrspace.h"
#include "noff.h"
//----------------------------------------------------------------------
// SwapHeader
// Do little endian to big endian conversion on the bytes in the
// object file header, in case the file was generated on a little
// endian machine, and we're now running on a big endian machine.
//----------------------------------------------------------------------
static void
SwapHeader (NoffHeader *noffH)
{
noffH->noffMagic = WordToHost(noffH->noffMagic);
noffH->code.size = WordToHost(noffH->code.size);
noffH->code.virtualAddr = WordToHost(noffH->code.virtualAddr);
noffH->code.inFileAddr = WordToHost(noffH->code.inFileAddr);
noffH->initData.size = WordToHost(noffH->initData.size);
noffH->initData.virtualAddr = WordToHost(noffH->initData.virtualAddr);
noffH->initData.inFileAddr = WordToHost(noffH->initData.inFileAddr);
noffH->uninitData.size = WordToHost(noffH->uninitData.size);
noffH->uninitData.virtualAddr = WordToHost(noffH->uninitData.virtualAddr);
noffH->uninitData.inFileAddr = WordToHost(noffH->uninitData.inFileAddr);
}
//----------------------------------------------------------------------
// AddrSpace::AddrSpace
// Create an address space to run a user program.
// Load the program from a file "executable", and set everything
// up so that we can start executing user instructions.
//
// Assumes that the object code file is in NOFF format.
//
// First, set up the translation from program memory to physical
// memory. For now, this is really simple (1:1), since we are
// only uniprogramming, and we have a single unsegmented page table
//
// "executable" is the file containing the object code to load into memory
//----------------------------------------------------------------------
AddrSpace::AddrSpace(OpenFile *executable)
{
NoffHeader noffH;
unsigned int i, size;
unsigned vpn, offset;
TranslationEntry *entry;
unsigned int pageFrame;
executable->ReadAt((char *)&noffH, sizeof(noffH), 0);
if ((noffH.noffMagic != NOFFMAGIC) &&
(WordToHost(noffH.noffMagic) == NOFFMAGIC))
SwapHeader(&noffH);
ASSERT(noffH.noffMagic == NOFFMAGIC);
// how big is address space?
size = noffH.code.size + noffH.initData.size + noffH.uninitData.size
+ UserStackSize; // we need to increase the size
// to leave room for the stack
numPages = divRoundUp(size, PageSize);
size = numPages * PageSize;
ASSERT(numPages+numPagesAllocated <= NumPhysPages); // check we're not trying
// to run anything too big --
// at least until we have
// virtual memory
DEBUG('a', "Initializing address space, num pages %d, size %d\n",
numPages, size);
// first, set up the translation
pageTable = new TranslationEntry[numPages];
for (i = 0; i < numPages; i++) {
pageTable[i].virtualPage = i;
pageTable[i].physicalPage = i+numPagesAllocated;
pageTable[i].valid = TRUE;
pageTable[i].use = FALSE;
pageTable[i].dirty = FALSE;
pageTable[i].readOnly = FALSE; // if the code segment was entirely on
// a separate page, we could set its
// pages to be read-only
}
// zero out the entire address space, to zero the unitialized data segment
// and the stack segment
bzero(&machine->mainMemory[numPagesAllocated*PageSize], size);
numPagesAllocated += numPages;
// then, copy in the code and data segments into memory
if (noffH.code.size > 0) {
DEBUG('a', "Initializing code segment, at 0x%x, size %d\n",
noffH.code.virtualAddr, noffH.code.size);
vpn = noffH.code.virtualAddr/PageSize;
offset = noffH.code.virtualAddr%PageSize;
entry = &pageTable[vpn];
pageFrame = entry->physicalPage;
executable->ReadAt(&(machine->mainMemory[pageFrame * PageSize + offset]),
noffH.code.size, noffH.code.inFileAddr);
}
if (noffH.initData.size > 0) {
DEBUG('a', "Initializing data segment, at 0x%x, size %d\n",
noffH.initData.virtualAddr, noffH.initData.size);
vpn = noffH.initData.virtualAddr/PageSize;
offset = noffH.initData.virtualAddr%PageSize;
entry = &pageTable[vpn];
pageFrame = entry->physicalPage;
executable->ReadAt(&(machine->mainMemory[pageFrame * PageSize + offset]),
noffH.initData.size, noffH.initData.inFileAddr);
}
}
//----------------------------------------------------------------------
// AddrSpace::AddrSpace (AddrSpace*) is called by a forked thread.
// We need to duplicate the address space of the parent.
//----------------------------------------------------------------------
AddrSpace::AddrSpace(AddrSpace *parentSpace)
{
numPages = parentSpace->GetNumPages();
unsigned i, size = numPages * PageSize;
ASSERT(numPages+numPagesAllocated <= NumPhysPages); // check we're not trying
// to run anything too big --
// at least until we have
// virtual memory
DEBUG('a', "Initializing address space, num pages %d, size %d\n",
numPages, size);
// first, set up the translation
TranslationEntry* parentPageTable = parentSpace->GetPageTable();
pageTable = new TranslationEntry[numPages];
for (i = 0; i < numPages; i++) {
pageTable[i].virtualPage = i;
pageTable[i].physicalPage = i+numPagesAllocated;
pageTable[i].valid = parentPageTable[i].valid;
pageTable[i].use = parentPageTable[i].use;
pageTable[i].dirty = parentPageTable[i].dirty;
pageTable[i].readOnly = parentPageTable[i].readOnly; // if the code segment was entirely on
// a separate page, we could set its
// pages to be read-only
}
// Copy the contents
unsigned startAddrParent = parentPageTable[0].physicalPage*PageSize;
unsigned startAddrChild = numPagesAllocated*PageSize;
for (i=0; i<size; i++) {
machine->mainMemory[startAddrChild+i] = machine->mainMemory[startAddrParent+i];
}
numPagesAllocated += numPages;
}
//----------------------------------------------------------------------
// AddrSpace::~AddrSpace
// Dealloate an address space. Nothing for now!
//----------------------------------------------------------------------
AddrSpace::~AddrSpace()
{
delete pageTable;
}
//----------------------------------------------------------------------
// AddrSpace::InitRegisters
// Set the initial values for the user-level register set.
//
// We write these directly into the "machine" registers, so
// that we can immediately jump to user code. Note that these
// will be saved/restored into the currentThread->userRegisters
// when this thread is context switched out.
//----------------------------------------------------------------------
void
AddrSpace::InitRegisters()
{
int i;
for (i = 0; i < NumTotalRegs; i++)
machine->WriteRegister(i, 0);
// Initial program counter -- must be location of "Start"
machine->WriteRegister(PCReg, 0);
// Need to also tell MIPS where next instruction is, because
// of branch delay possibility
machine->WriteRegister(NextPCReg, 4);
// Set the stack register to the end of the address space, where we
// allocated the stack; but subtract off a bit, to make sure we don't
// accidentally reference off the end!
machine->WriteRegister(StackReg, numPages * PageSize - 16);
DEBUG('a', "Initializing stack register to %d\n", numPages * PageSize - 16);
}
//----------------------------------------------------------------------
// AddrSpace::SaveState
// On a context switch, save any machine state, specific
// to this address space, that needs saving.
//
// For now, nothing!
//----------------------------------------------------------------------
void AddrSpace::SaveState()
{}
//----------------------------------------------------------------------
// AddrSpace::RestoreState
// On a context switch, restore the machine state so that
// this address space can run.
//
// For now, tell the machine where to find the page table.
//----------------------------------------------------------------------
void AddrSpace::RestoreState()
{
machine->pageTable = pageTable;
machine->pageTableSize = numPages;
}
unsigned
AddrSpace::GetNumPages()
{
return numPages;
}
TranslationEntry*
AddrSpace::GetPageTable()
{
return pageTable;
}
| [
"luckythegreat4@gmail.com"
] | luckythegreat4@gmail.com |
dbc39ae52c7f690cba2b345ff49af771c430628c | 63774df7f1ff41d0980506f4255163d64028a763 | /List.hpp | 591f35598145f5cf62294f6818ed489c55a0b16a | [] | no_license | jdc011/Tracker | 1c0937d480f72b9f40fe67406a980fd96fbe898e | e4712a3955e479b1ac4f06e488dac516f72c0097 | refs/heads/master | 2020-04-06T06:59:19.857900 | 2016-09-11T05:42:11 | 2016-09-11T05:42:11 | 62,351,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | hpp | #ifndef LIST_HPP
#define LIST_HPP
#include "LNode.hpp"
class List
{
private:
LNode * tail;
LNode * head;
unsigned int occupancy;
LNode * set_head(LNode *);
LNode * set_tail(LNode *);
long equals(Entry &, Entry &, Entry &);
public:
List(void);
long insert(Entry &, const std :: string &, Entry &);
long remove(Entry &, const std :: string &, Entry &);
long find(Entry &, const std :: string &, const std :: string &);
long empty(void);
void print_list(void);
};
#endif
| [
"jeremy_cruz519@yahoo.com"
] | jeremy_cruz519@yahoo.com |
8d013b2f87fa535c9c6598f77d056ae0b47271d6 | ad99ccb4c26fbea7bd4c841be20b4a5830695b6f | /src/cost.cpp | a3fa72926559ec65cad6e0348e7d7fff314e388f | [
"MIT"
] | permissive | hd-chuong/CarND-Path-Planning-Project | b98c62b1a9849ad4bf4692d8565a4e84c0c44c57 | 966bb630daaa4680c6ac1ef1240dd6b57c449a86 | refs/heads/master | 2021-04-02T01:24:32.796430 | 2020-05-10T04:17:49 | 2020-05-10T04:17:49 | 248,229,108 | 0 | 0 | MIT | 2020-03-18T12:44:37 | 2020-03-18T12:44:36 | null | UTF-8 | C++ | false | false | 6,308 | cpp | #include <string>
#include <vector>
#include "vehicle.h"
#include <cmath>
#include <map>
#include <functional>
#include <iostream>
using std::string;
using std::vector;
using std::map;
const double EFFICIENCY = 1;
const double ADVANCE = 10;
const double REACH_GOAL = 0;
const double STABILITY = 1;
// float lane_speed(const map<int, vector<Vehicle>> &predictions, int lane)
// {
// for (auto it = predictions.begin(); it != predictions.end(); ++it)
// {
// int key = it->first;
// Vehicle vehicle = it->second[0];
// if (vehicle.lane == lane && key != -1)
// {
// return vehicle.v;
// }
// }
// return -1;
// }
// place an expensive penalty if the vehicle does not move or move backwards
float advance_cost(const Vehicle & vehicle,
const vector<Vehicle> & trajectory,
const map<int, vector<Vehicle>> & predictions,
map<string, float> & data)
{
double cur_s = vehicle.s;
double expected_s = trajectory[0].s;
double future_s = trajectory[1].s;
//double distance = fabs(expected_s - cur_s) + fabs(future_s - cur_s);
double distance = 0.0;
if (expected_s < cur_s) distance += 1;
if (future_s < cur_s) distance += 1;
return distance / 2;
//return distance < 1e-3 ? 1e3 : 1 / distance;
}
float inefficiency_cost(const Vehicle &vehicle,
const vector<Vehicle> & trajectory,
const map<int, vector<Vehicle>> & predictions,
map<string, float> & data
)
{
// cost becomes higher for trajectories with intended lane and final lane that have traffic slower than vehicle's target speed.
//You can use the lane_speed function to determine the speed for a lane.
//This function is very similar to what you have already implemented in the "Implement a Second Cost Function in C++" quiz
// float proposed_speed_intended = lane_speed(predictions, data["intended_lane"]);
// if (proposed_speed_intended < 0)
// {
// proposed_speed_intended = vehicle.target_speed;
// }
// float proposed_speed_final = lane_speed(predictions, data["final_lane"]);
// if (proposed_speed_final < 0)
// {
// proposed_speed_final = vehicle.target_speed;
// }
// float cost = (2.0 * vehicle.target_speed - proposed_speed_intended - proposed_speed_final) / vehicle.target_speed;
// std::cout << "Target speed " << vehicle.target_speed << " . Intended speed " << proposed_speed_intended << ". Final speed " << proposed_speed_final;
// std::cout << ". Inefficient cost " << cost << std::endl;
float possible_speed = trajectory[1].v;
//std::cout << "Possible speed = " << possible_speed;
float cost = 2 * vehicle.target_speed - possible_speed - trajectory[0].v;
//std::cout << "cur lane " << vehicle.lane << " target speed " << vehicle.target_speed << " . possible speed " << possible_speed << " current speed " << trajectory[0].v << std::endl;
return cost;
}
float goal_distance_cost(const Vehicle & vehicle,
const vector<Vehicle> &trajectory,
const map<int, vector<Vehicle>> &predictions,
map<string, float> &data
)
{
// Cost increases based on distance of intended lane (for planning a lane change) and final lane of trajectory.
// Cost of being out of goal lane also becomes larger as vehicle approaches goal distance.
// This function is very similar to what you have already implemented in th "Implement a Cost Function in C++" quiz.
float cost;
float distance = data["distance_to_goal"];
if (distance > 0)
{
cost = 1 - 2*exp(-(fabs(2.0 * vehicle.goal_lane - data["intended_lane"] - data["final_lane"]) / distance));
}
else
{
cost = 1;
}
return cost;
}
float stability_cost(const Vehicle & vehicle,
const vector<Vehicle> &trajectory,
const map<int, vector<Vehicle>> &predictions,
map<string, float> &data)
{
double cost = 0;
//if (trajectory[1].state.compare("KL") == 0) return 0;
if (trajectory[1].state.compare("PLCR") == 0) cost = 0.5;
if (trajectory[1].state.compare("PLCL") == 0) cost = 0.5;
if (trajectory[1].state.compare("LCL") == 0) cost = 1;
if (trajectory[1].state.compare("LCR") == 0) cost = 1;
//std::cout << "Stability " << trajectory[1].state << " " << cost << std::endl;
return cost;
}
map<string, float> get_helper_data(const Vehicle & vehicle,
const vector<Vehicle> & trajectory,
const map<int, vector<Vehicle>> &predictions)
{
map<string, float> trajectory_data;
Vehicle trajectory_last = trajectory[1];
float intended_lane;
if (trajectory_last.state.compare("PLCL") == 0)
{
intended_lane = trajectory_last.lane + 1;
} else if (trajectory_last.state.compare("PLCR") == 0)
{
intended_lane = trajectory_last.lane - 1;
} else
{
intended_lane = trajectory_last.lane;
}
float distance_to_goal = vehicle.goal_s - trajectory_last.s;
float final_lane = trajectory_last.lane;
trajectory_data["intended_lane"] = intended_lane;
trajectory_data["final_lane"] = final_lane;
trajectory_data["distance_to_goal"] = distance_to_goal;
return trajectory_data;
}
float calculate_cost(const Vehicle & vehicle,
const map<int, vector<Vehicle>> & predictions,
const vector<Vehicle> & trajectory)
{
map<string, float> trajectory_data = get_helper_data(vehicle, trajectory, predictions);
float cost = 0.0;
vector<std::function<float(const Vehicle &, const vector<Vehicle> &, const map<int, vector<Vehicle>> &,
map<string, float> &)>> cf_list = {goal_distance_cost, inefficiency_cost, advance_cost, stability_cost};
vector<double> weight_list = {REACH_GOAL, EFFICIENCY, ADVANCE, STABILITY};
for (int i = 0; i < cf_list.size(); ++i)
{
float new_cost = weight_list[i]*cf_list[i](vehicle, trajectory, predictions, trajectory_data);
cost += new_cost;
}
return cost;
} | [
"chuong.git@gmail.com"
] | chuong.git@gmail.com |
ade14715d53b75824c505b28e7e49ccdf2357fac | 862a37cfd4e2c8882e36c5c003e5d299253ddc06 | /ui/views/animation/ink_drop_host_view.h | 8f8b8ea59c35ce4c704239c4cec4c74a5f708fd3 | [
"BSD-3-Clause"
] | permissive | lingyfh/chromium | 8b9dd66999bdeebf52c36b910f454cc422899692 | f533f52963fd4a7e6eb30bd94b758b7a88caf0b3 | refs/heads/master | 2023-01-09T01:48:25.525319 | 2018-11-28T10:39:21 | 2018-11-28T10:39:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,753 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ANIMATION_INK_DROP_HOST_VIEW_H_
#define UI_VIEWS_ANIMATION_INK_DROP_HOST_VIEW_H_
#include <memory>
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/view.h"
namespace gfx {
class PointF;
} // namespace gfx
namespace ui {
class Layer;
class LocatedEvent;
} // namespace ui
namespace views {
class InkDrop;
class InkDropHighlight;
class InkDropImpl;
class InkDropMask;
class InkDropRipple;
enum class InkDropState;
namespace test {
class InkDropHostViewTestApi;
} // namespace test
// A view that provides InkDropHost functionality.
class VIEWS_EXPORT InkDropHostView : public View {
public:
// Used in SetInkDropMode() to specify whether the ink drop effect is enabled
// or not for the view. In case of having an ink drop, it also specifies
// whether the default gesture event handler for the ink drop should be
// installed or the subclass will handle gesture events itself.
enum class InkDropMode {
OFF,
ON,
ON_NO_GESTURE_HANDLER,
};
InkDropHostView();
~InkDropHostView() override;
// Adds the |ink_drop_layer| in to a visible layer tree.
virtual void AddInkDropLayer(ui::Layer* ink_drop_layer);
// Removes |ink_drop_layer| from the layer tree.
virtual void RemoveInkDropLayer(ui::Layer* ink_drop_layer);
// Returns a configured InkDrop. In general subclasses will return an
// InkDropImpl instance that will use the CreateInkDropRipple() and
// CreateInkDropHighlight() methods to create the visual effects.
//
// Subclasses should override this if they need to configure any properties
// specific to the InkDrop instance. e.g. the AutoHighlightMode of an
// InkDropImpl instance.
virtual std::unique_ptr<InkDrop> CreateInkDrop();
// Creates and returns the visual effect used for press. Used by InkDropImpl
// instances.
virtual std::unique_ptr<InkDropRipple> CreateInkDropRipple() const;
// Creates and returns the visual effect used for hover and focus. Used by
// InkDropImpl instances.
virtual std::unique_ptr<InkDropHighlight> CreateInkDropHighlight() const;
// Subclasses can override to return a mask for the ink drop. By default,
// returns nullptr (i.e no mask).
// TODO(bruthig): InkDropMasks do not currently work on Windows. See
// https://crbug.com/713359.
virtual std::unique_ptr<views::InkDropMask> CreateInkDropMask() const;
// Returns the base color for the ink drop.
virtual SkColor GetInkDropBaseColor() const;
// Toggle to enable/disable an InkDrop on this View. Descendants can override
// CreateInkDropHighlight() and CreateInkDropRipple() to change the look/feel
// of the InkDrop.
//
// TODO(bruthig): Add an easier mechanism than overriding functions to allow
// subclasses/clients to specify the flavor of ink drop.
void SetInkDropMode(InkDropMode ink_drop_mode);
void set_ink_drop_visible_opacity(float visible_opacity) {
ink_drop_visible_opacity_ = visible_opacity;
}
float ink_drop_visible_opacity() const { return ink_drop_visible_opacity_; }
void set_ink_drop_corner_radii(int small_radius, int large_radius) {
ink_drop_small_corner_radius_ = small_radius;
ink_drop_large_corner_radius_ = large_radius;
}
int ink_drop_small_corner_radius() const {
return ink_drop_small_corner_radius_;
}
int ink_drop_large_corner_radius() const {
return ink_drop_large_corner_radius_;
}
// Animates |ink_drop_| to the desired |ink_drop_state|. Caches |event| as the
// last_ripple_triggering_event().
//
// *** NOTE ***: |event| has been plumbed through on a best effort basis for
// the purposes of centering ink drop ripples on located Events. Thus nullptr
// has been used by clients who do not have an Event instance available to
// them.
void AnimateInkDrop(InkDropState state, const ui::LocatedEvent* event);
protected:
// Size used for the default SquareInkDropRipple.
static constexpr int kDefaultInkDropSize = 24;
// Called after a new InkDrop instance is created.
virtual void OnInkDropCreated() {}
// View:
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
void OnBoundsChanged(const gfx::Rect& previous_bounds) override;
void VisibilityChanged(View* starting_from, bool is_visible) override;
void OnFocus() override;
void OnBlur() override;
void OnMouseEvent(ui::MouseEvent* event) override;
// Returns an InkDropImpl with default configuration. The base implementation
// of CreateInkDrop() delegates to this function.
std::unique_ptr<InkDropImpl> CreateDefaultInkDropImpl();
// Returns an InkDropImpl configured to work well with a
// flood-fill ink drop ripple.
std::unique_ptr<InkDropImpl> CreateDefaultFloodFillInkDropImpl();
// Returns the default InkDropRipple centered on |center_point|.
std::unique_ptr<InkDropRipple> CreateDefaultInkDropRipple(
const gfx::Point& center_point,
const gfx::Size& size = gfx::Size(kDefaultInkDropSize,
kDefaultInkDropSize)) const;
// Returns the default InkDropHighlight centered on |center_point|.
std::unique_ptr<InkDropHighlight> CreateDefaultInkDropHighlight(
const gfx::PointF& center_point,
const gfx::Size& size = gfx::Size(kDefaultInkDropSize,
kDefaultInkDropSize)) const;
// Returns true if an ink drop instance has been created.
bool HasInkDrop() const;
// Provides access to |ink_drop_|. Implements lazy initialization of
// |ink_drop_| so as to avoid virtual method calls during construction since
// subclasses should be able to call SetInkDropMode() during construction.
InkDrop* GetInkDrop();
// Returns the point of the |last_ripple_triggering_event_| if it was a
// LocatedEvent, otherwise the center point of the local bounds is returned.
gfx::Point GetInkDropCenterBasedOnLastEvent() const;
// Initializes and sets a mask on |ink_drop_layer|. No-op if
// CreateInkDropMask() returns null.
void InstallInkDropMask(ui::Layer* ink_drop_layer);
void ResetInkDropMask();
// Returns a large ink drop size based on the |small_size| that works well
// with the SquareInkDropRipple animation durations.
static gfx::Size CalculateLargeInkDropSize(const gfx::Size& small_size);
private:
class InkDropGestureHandler;
friend class InkDropGestureHandler;
friend class test::InkDropHostViewTestApi;
// The last user Event to trigger an ink drop ripple animation.
std::unique_ptr<ui::LocatedEvent> last_ripple_triggering_event_;
// Defines what type of |ink_drop_| to create.
InkDropMode ink_drop_mode_ = InkDropMode::OFF;
// Should not be accessed directly. Use GetInkDrop() instead.
std::unique_ptr<InkDrop> ink_drop_;
// Intentionally declared after |ink_drop_| so that it doesn't access a
// destroyed |ink_drop_| during destruction.
std::unique_ptr<InkDropGestureHandler> gesture_handler_;
float ink_drop_visible_opacity_ = 0.175f;
// Radii used for the SquareInkDropRipple.
int ink_drop_small_corner_radius_ = 2;
int ink_drop_large_corner_radius_ = 4;
// Determines whether the view was already painting to layer before adding ink
// drop layer.
bool old_paint_to_layer_ = false;
bool destroying_ = false;
std::unique_ptr<views::InkDropMask> ink_drop_mask_;
base::WeakPtrFactory<InkDropHostView> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(InkDropHostView);
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_HOST_VIEW_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
0336427cad662f62daea1c918e9f6d515a28bcdb | df75a4ba88ebd4863da0e573245955209051c369 | /DataAccess/StringComparer.h | ee6dbf9e5828ebbc43616ee285ad1daeac2db2d7 | [] | no_license | Wideweb/PhoneBook_OSISP_4 | e7f328b37ee8bb4eb7fd67fc3c870eba93bc7f24 | 198a600923d03637924546f73c78cbaf8b3515fa | refs/heads/master | 2016-08-12T09:53:38.624627 | 2015-11-14T20:09:14 | 2015-11-14T20:09:14 | 46,193,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | h | #pragma once
#include <string>
class StringComparer
{
public:
static BOOL iequal(std::string a, std::string b);
static int icompare(std::string a, std::string b);
StringComparer();
~StringComparer();
private:
static int icompare_pred(unsigned char a, unsigned char b);
static BOOL iequal_pred(unsigned char a, unsigned char b);
};
| [
"alckevich@yandex.ru"
] | alckevich@yandex.ru |
b4393e65e8af406f6d6d3857df667873e682c083 | f8fc2f1d7d717f6078faf99d46241165e594dd30 | /mimikatz/modules/Security Packages/tspkg.cpp | 26bf7d8e7ca445dd2a76213115d4a11cc70a7a5d | [] | no_license | thomhastings/mimikatz | 5704dd4dee57a8607df319beddf92e4c06b28ebd | 8a834da435711b77932c18919cfbe664fbae5d23 | refs/heads/master | 2021-01-13T02:29:59.112769 | 2013-01-22T00:46:19 | 2013-01-22T00:46:19 | 8,246,896 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,775 | cpp | /* Benjamin DELPY `gentilkiwi`
http://blog.gentilkiwi.com
benjamin@gentilkiwi.com
Licence : http://creativecommons.org/licenses/by-nc-sa/3.0/fr/
Ce fichier : http://creativecommons.org/licenses/by/3.0/fr/
*/
#include "tspkg.h"
mod_process::PKIWI_VERY_BASIC_MODULEENTRY mod_mimikatz_sekurlsa_tspkg::pModTSPKG = NULL;
PRTL_AVL_TABLE mod_mimikatz_sekurlsa_tspkg::TSGlobalCredTable = NULL; //reinterpret_cast<PRTL_AVL_TABLE>(NULL);
bool mod_mimikatz_sekurlsa_tspkg::getTsPkg(vector<wstring> * arguments)
{
vector<pair<mod_mimikatz_sekurlsa::PFN_ENUM_BY_LUID, wstring>> monProvider;
monProvider.push_back(make_pair<mod_mimikatz_sekurlsa::PFN_ENUM_BY_LUID, wstring>(getTsPkgLogonData, wstring(L"tspkg")));
return mod_mimikatz_sekurlsa::getLogonData(arguments, &monProvider);
}
bool mod_mimikatz_sekurlsa_tspkg::searchTSPKGFuncs()
{
#ifdef _M_X64
BYTE PTRN_WALL_TSGlobalCredTable[] = {0x48, 0x83, 0xec, 0x20, 0x48, 0x8d, 0x0d};
LONG OFFS_WALL_TSGlobalCredTable = sizeof(PTRN_WALL_TSGlobalCredTable);
#elif defined _M_IX86
BYTE PTRN_WNO8_TSGlobalCredTable[] = {0x8b, 0xff, 0x55, 0x8b, 0xec, 0x51, 0x56, 0xbe};
LONG OFFS_WNO8_TSGlobalCredTable = sizeof(PTRN_WNO8_TSGlobalCredTable);
BYTE PTRN_WIN8_TSGlobalCredTable[] = {0x8b, 0xff, 0x53, 0xbb};
LONG OFFS_WIN8_TSGlobalCredTable = sizeof(PTRN_WIN8_TSGlobalCredTable);
#endif
if(mod_mimikatz_sekurlsa::searchLSASSDatas() && pModTSPKG && !TSGlobalCredTable)
{
PBYTE *pointeur = NULL; PBYTE pattern = NULL; ULONG taille = 0; LONG offset = 0;
pointeur= reinterpret_cast<PBYTE *>(&TSGlobalCredTable);
#ifdef _M_X64
pattern = PTRN_WALL_TSGlobalCredTable;
taille = sizeof(PTRN_WALL_TSGlobalCredTable);
offset = OFFS_WALL_TSGlobalCredTable;
#elif defined _M_IX86
if(mod_system::GLOB_Version.dwBuildNumber < 8000)
{
pattern = PTRN_WNO8_TSGlobalCredTable;
taille = sizeof(PTRN_WNO8_TSGlobalCredTable);
offset = OFFS_WNO8_TSGlobalCredTable;
}
else
{
pattern = PTRN_WIN8_TSGlobalCredTable;
taille = sizeof(PTRN_WIN8_TSGlobalCredTable);
offset = OFFS_WIN8_TSGlobalCredTable;
}
#endif
if(HMODULE monModule = LoadLibrary(L"tspkg"))
{
MODULEINFO mesInfos;
if(GetModuleInformation(GetCurrentProcess(), monModule, &mesInfos, sizeof(MODULEINFO)))
{
mod_memory::genericPatternSearch(pointeur, L"tspkg", pattern, taille, offset);
*pointeur += pModTSPKG->modBaseAddr - reinterpret_cast<PBYTE>(mesInfos.lpBaseOfDll);
}
FreeLibrary(monModule);
}
}
return (pModTSPKG && TSGlobalCredTable);
}
bool WINAPI mod_mimikatz_sekurlsa_tspkg::getTsPkgLogonData(__in PLUID logId, __in bool justSecurity)
{
if(searchTSPKGFuncs())
{
PKIWI_GENERIC_PRIMARY_CREDENTIAL mesCreds = NULL;
BYTE * monBuffP = new BYTE[sizeof(KIWI_TS_CREDENTIAL)], * monBuffC = new BYTE[sizeof(KIWI_TS_PRIMARY_CREDENTIAL)];
if(PKIWI_TS_CREDENTIAL pLogSession = reinterpret_cast<PKIWI_TS_CREDENTIAL>(mod_mimikatz_sekurlsa::getPtrFromAVLByLuid(TSGlobalCredTable, FIELD_OFFSET(KIWI_TS_CREDENTIAL, LocallyUniqueIdentifier), logId)))
{
if(mod_memory::readMemory(pLogSession, monBuffP, sizeof(KIWI_TS_CREDENTIAL), mod_mimikatz_sekurlsa::hLSASS))
{
pLogSession = reinterpret_cast<PKIWI_TS_CREDENTIAL>(monBuffP);
if(pLogSession->pTsPrimary)
{
if(mod_memory::readMemory(pLogSession->pTsPrimary, monBuffC, sizeof(KIWI_TS_PRIMARY_CREDENTIAL), mod_mimikatz_sekurlsa::hLSASS))
mesCreds = &(reinterpret_cast<PKIWI_TS_PRIMARY_CREDENTIAL>(monBuffC)->credentials);
}
else wcout << L"n.s. (SuppCred KO) / ";
}
}
mod_mimikatz_sekurlsa::genericCredsToStream(mesCreds, justSecurity, true);
delete [] monBuffC, monBuffP;
}
else wcout << L"n.a. (tspkg KO)";
return true;
}
| [
"gentilkiwi@gmail.com@bf4862f3-4bc5-fd6b-1798-8191b2233e11"
] | gentilkiwi@gmail.com@bf4862f3-4bc5-fd6b-1798-8191b2233e11 |
1fc40c33a3cdb1bff3304d327c4fd27a97c6c683 | a878a9e9fabe8538fef85a3eb90f05751db97713 | /src/Hpipe/CbQueue.h | ec31092f5902345a04783cfec596a76f66cfcc0a | [
"Apache-2.0"
] | permissive | hleclerc/Hpipe | 7ba638e7db8cf8709f61e9f3adf2b00ca0cc712c | 5ac7fa1fa2a2a4aaf2826ae793c799ddd828ac6c | refs/heads/master | 2020-05-21T19:14:22.645379 | 2017-06-01T22:15:52 | 2017-06-01T22:15:52 | 60,592,056 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,898 | h | #pragma once
#include "Buffer.h"
#include "Assert.h"
#include "DaSi.h"
#include <functional>
#include <string>
namespace Hpipe {
class CbStringPtr;
class CbString;
class CmString;
/**
Buffer sequence. Write to the end. Read from the beginning.
*/
class CbQueue {
public:
CbQueue( CbQueue &&cq );
CbQueue();
~CbQueue();
CbQueue( const CmString &bs );
CbQueue( const DaSi &bs );
CbQueue &operator=( CbQueue &&cq );
// error
// operator bool() const { return not error(); }
bool error() const { return not end; } ///< works after at least a first read (and before free or clear): if no error, `end` is not cleared
bool ack_error() { free(); end = 0; return false; } ///< set error flag to true, and return false
// size
bool empty() const { return not beg; }
PT size () const { PT res = 0; for( Buffer *b = beg; b; b = b->next ) res += b->used; return res - off; }
PT nbuf () const { PT res = 0; for( Buffer *b = beg; b; b = b->next ) ++res; return res; }
void clear(); ///< set size( 0 ), and tries to keep the first Buffer if not shared
void free (); ///< set size( 0 ), and free all the data
// writers
void write_some( const void *data, PT size ); ///< append raw binary data
void write_some( const CbStringPtr &s );
void write_some( const CbString &s );
void write_some( const CbQueue &s );
void write_some( const std::string &s );
void write_some( CbQueue &&cq );
void write_byte( PI8 val ) {
if ( not beg ) init_beg(); else if ( not end->room() ) end = Buffer::New( Buffer::default_size, end );
end->data[ end->used++ ] = val;
}
void write_byte_wo_beg_test( PI8 val ) { ///< can be used after a first write( len != 0 ) or a first write_byte
if ( not end->room() ) end = Buffer::New( Buffer::default_size, end );
end->data[ end->used++ ] = val;
}
void add_buff( IKnowWhatIDo, Buffer *buff, unsigned offset_in_buff = 0 ); ///< after that, buff should not be reused elsewhere
void insert_some( PT pos, const void *data, PT size );
// contiguous writers
template<class T>
T *write_cont( const T &data ) { ///< write contiguous
return reinterpret_cast<T *>( write_cont( &data, sizeof( T ) ) );
}
void *write_cont( const void *data, PT size ); ///< write contiguous
void *make_room( PT size ); ///< make contiguous room
void sub_used( PT size ); ///< after make contiguous room, we can say how much data have not been used
void *ptr( PT offset );
const PI8 *ptr() const { return beg->data + off; }
void new_buff( PT size = Buffer::default_size ) { if ( not beg ) init_beg(); else end = Buffer::New( size, end ); } ///< should not be called manually (expected for test purpose)
CbQueue splitted( PT n ) const; ///< for test purpose. Make a newCbQueue with a copy of the content, splitted by chunks of size n
// readers. Beware there are no checks in these methods
void read_some( void *data, PT size );
void skip_some( PT size );
void skip_some_sr( ssize_t &size );
PI8 read_byte() {
PI8 res = beg->data[ off++ ];
if ( off == beg->used ) {
const Buffer *o = beg;
beg = beg->next;
Buffer::dec_ref( o );
off = 0;
}
return res;
}
// checkings for readers that save a signal (that will give error() != 0) if not ok. To be done before each read.
bool ack_read_byte() { ///< return true if ok to read a byte. Else, set end to 0 (to signal an error) and return false.
if ( not beg )
return ack_error();
return true;
}
bool ack_read_some( ST len ) { ///< return true if ok to `len` bytes. Else, set end to 0 (to signal an error) and return false.
len += off;
for( Buffer *b = beg; b; b = b->next ) {
len -= b->used;
if ( len <= 0 )
return true;
}
return ack_error();
}
//
std::pair<const void *,PT> contiguous_data_at_the_beginning() {
return beg ? std::pair<const void *,PT>( beg->data + off, beg->used - off ) : std::pair<const void *,PT>( 0, 0 );
}
//
void data_visitor( std::function<void(const PI8 *,const PI8 *)> func ) const { ///< op must return true to continue to read
visitor( [ &func ]( const Buffer *b, PT bb, PT eb ) {
func( b->data + bb, b->data + eb );
return true;
} );
}
// display
void write_to_stream( std::ostream &os ) const;
operator std::string() const;
//
template<class TV0,class TV1>
void remove_chunks( const TV0 &positions, const TV1 &sizes ) {
Buffer *buf_writer = beg;
unsigned off_writer = off;
PT acc_pos = 0;
PT cur_pos = 0;
PT avoid = 0;
visitor( [ & ]( const Buffer *b, PT bd, PT ed ) { // buf_writer, &off_writer, &acc_pos, &cur_pos, &avoid, &positions, &sizes
// TODO: optimize
for( ; bd < ed; ++bd, ++acc_pos ) {
if ( cur_pos < positions.size() and acc_pos == positions[ cur_pos ] )
avoid = sizes[ cur_pos++ ];
if ( not avoid ) {
buf_writer->data[ off_writer++ ] = b->data[ bd ];
if ( off_writer >= buf_writer->used ) {
buf_writer = buf_writer->next;
off_writer = 0;
}
} else
--avoid;
}
return true;
} );
// dec_ref unused buffers
for( const Buffer *n = buf_writer->next; n; ) {
const Buffer *o = n;
n = n->next;
Buffer::dec_ref( o );
}
// update the last one
buf_writer->used = off_writer;
buf_writer->next = 0;
}
protected:
friend class CbStringPtr;
friend class CbString;
void init_beg() {
beg = Buffer::New();
end = beg;
off = 0;
}
template<class Op>
bool visitor( const Op &op ) const { ///< op must return true to continue to read
if ( const Buffer *b = beg ) {
// first buff
const Buffer *n = b->next;
if ( not op( b, off, b->used ) )
return false;
// next ones, 2x unrolled
while ( n ) {
b = n->next;
if ( not op( n, 0, n->used ) )
return false;
if ( not b )
break;
n = b->next;
if ( not op( b, 0, b->used ) )
return false;
}
}
return true;
}
public:
Buffer *beg; ///< first item
Buffer *end; ///< last item
unsigned off; ///< offset in bytes (< Buffer::size)
};
}
| [
"hugal.leclerc@gmail.com"
] | hugal.leclerc@gmail.com |
ee6e360ce7b19e73287ca4cfed9e8b1fae820840 | 3187dd3c1186cf97781987e455f5d11244f90aec | /src/sysc/communication/sc_mutex_if.h | ebb93d6057f3c60ba2d32b065bad280aedda952d | [
"Apache-2.0"
] | permissive | Muriukidavid/systemc-2.3.2 | fe5d9d57636025cfdc0dee7eb9c8114ca19628ad | c5d203ac014277b9d2c2af895edc43537a15674e | refs/heads/master | 2020-03-13T13:17:48.813825 | 2018-04-26T09:48:42 | 2018-04-26T09:48:42 | 131,135,420 | 0 | 1 | Apache-2.0 | 2018-06-28T15:17:19 | 2018-04-26T09:51:26 | C++ | UTF-8 | C++ | false | false | 3,875 | h | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera 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.
*****************************************************************************/
/*****************************************************************************
sc_mutex_if.h -- The sc_mutex_if interface class.
Original Author: Martin Janssen, Synopsys, Inc., 2001-05-21
CHANGE LOG IS AT THE END OF THE FILE
*****************************************************************************/
#ifndef SC_MUTEX_IF_H
#define SC_MUTEX_IF_H
#include "sysc/communication/sc_interface.h"
namespace sc_core {
// ----------------------------------------------------------------------------
// CLASS : sc_mutex_if
//
// The sc_mutex_if interface class.
// ----------------------------------------------------------------------------
class SC_API sc_mutex_if
: virtual public sc_interface
{
public:
// the classical operations: lock(), trylock(), and unlock()
// blocks until mutex could be locked
virtual int lock() = 0;
// returns -1 if mutex could not be locked
virtual int trylock() = 0;
// returns -1 if mutex was not locked by caller
virtual int unlock() = 0;
protected:
// constructor
sc_mutex_if()
{}
private:
// disabled
sc_mutex_if( const sc_mutex_if& );
sc_mutex_if& operator = ( const sc_mutex_if& );
};
// ----------------------------------------------------------------------------
// CLASS : sc_scoped_lock
//
// The sc_scoped_lock class to lock (and automatically release) a mutex.
// ----------------------------------------------------------------------------
//template< typename Lockable = sc_mutex_if >
class SC_API sc_scoped_lock
{
public:
//typedef Lockable lockable_type;
typedef sc_mutex_if lockable_type;
explicit
sc_scoped_lock( lockable_type& mtx )
: m_ref(mtx)
, m_active(true)
{
m_ref.lock();
}
bool release()
{
if( m_active )
{
m_ref.unlock();
m_active = false;
return true;
}
return false;
}
~sc_scoped_lock()
{
release();
}
private:
// disabled
sc_scoped_lock( const sc_scoped_lock& );
sc_scoped_lock& operator=( const sc_scoped_lock& );
lockable_type& m_ref;
bool m_active;
};
} // namespace sc_core
//$Log: sc_mutex_if.h,v $
//Revision 1.4 2011/08/26 20:45:41 acg
// Andy Goodrich: moved the modification log to the end of the file to
// eliminate source line number skew when check-ins are done.
//
//Revision 1.3 2011/04/19 02:36:26 acg
// Philipp A. Hartmann: new aysnc_update and mutex support.
//
//Revision 1.2 2011/02/18 20:23:45 acg
// Andy Goodrich: Copyright update.
//
//Revision 1.1.1.1 2006/12/15 20:20:04 acg
//SystemC 2.3
//
//Revision 1.2 2006/01/03 23:18:26 acg
//Changed copyright to include 2006.
//
//Revision 1.1.1.1 2005/12/19 23:16:43 acg
//First check in of SystemC 2.1 into its own archive.
//
//Revision 1.8 2005/06/10 22:43:55 acg
//Added CVS change log annotation.
//
#endif
// Taf!
| [
"karfes@gmail.com"
] | karfes@gmail.com |
309cbee4ddf0e458611732580537ccfd3e57e674 | cc9aaf54eb999849550a9d60791ade202aa4383e | /Code/Game/GameMeshes.hpp | dab920fb2f9a6b863238042b70e345d06f2c533d | [] | no_license | jamesmdale/ProtoGame3D | d21122edf9fa42c8faa319e7fbcd36236dfcba13 | d0b9f4cb4c6151d307a7381ceb9c9438c90fc9e6 | refs/heads/master | 2020-04-21T22:14:00.321179 | 2019-02-09T19:30:14 | 2019-02-09T19:30:14 | 169,904,239 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 127 | hpp | #pragma once
#include "Engine\Renderer\Mesh.hpp"
extern Mesh* MakeBlock(const Vector3& center);
extern Mesh* MakeChunk();
| [
"jmdale@smu.edu"
] | jmdale@smu.edu |
be36ceb4dea6071f26853ff52cb76f15f7c2656c | dc65a9bb0da31b8959d353befb4b90c606a0680a | /vertex.h | 40c91d7bc0122b7162ac03f74ca146cc567334fc | [] | no_license | takayaman/GraphCut | 75169f0248484cdfb5b4f3728ad7549961e71ec8 | d6467818bdbaa676718ac283a4ffe8397aee71b6 | refs/heads/master | 2021-01-15T16:29:35.685270 | 2014-11-29T11:01:40 | 2014-11-29T11:01:40 | 27,300,112 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,273 | h | /*=============================================================================
* Project : GraphCut
* Code : vertex.h
* Written : N.Takayama, UEC
* Date : 2014/11/26
* Copyright (c) 2014 N.Takayama <takayaman@uec.ac.jp>
* Definition of graphcut_base::Vertex
* Vertex for graphcut
*===========================================================================*/
#ifndef _HOME_TAKAYAMAN_DOCUMENTS_PROGRAMMING_GENERAL_GRAPHCUT_GRAPHCUT_VERTEX_H_
#define _HOME_TAKAYAMAN_DOCUMENTS_PROGRAMMING_GENERAL_GRAPHCUT_GRAPHCUT_VERTEX_H_
/*=== Include ===============================================================*/
#include <stdint.h>
#include <glog/logging.h>
#include <vector>
#include "edge.h"
/*=== Define ================================================================*/
/*=== Class Definition =====================================================*/
namespace graphcut_base {
class Edge;
class Vertex {
public:
/*!
* Defoult constructor
*/
Vertex(void);
Vertex(std::string name);
/*!
* Default destructor
*/
~Vertex(void);
/*!
* Copy constructor
*/
Vertex(const Vertex& rhs);
/*!
* Assignment operator
* @param rhs Right hand side
* @return pointer of this object
*/
Vertex& operator=(const Vertex& rhs);
bool operator ==(Vertex& rhs);
/*! 自身を始点として終点との間に双方向エッジを張り,容量を設定する
* ここで,始点->終点のエッジ容量 : size
* 終点->始点のエッジ容量 : -size
*/
void addFlowPath(Vertex *endvertex, double size);
void visit(void);
void reset(void);
void setValue(double value);
double getValue(void);
void setName(std::string name);
bool isVisited(void);
public:
std::vector<Edge*> m_vectorflowpath;
Vertex* m_parent;
Edge* m_parentpath;
std::string m_name;
private:
double m_value;
bool is_visited;
};
/*!
* Log output operator
* @param lhs Left hand side
* @param rhs Right hand side
* @return Pointer of google::LogSink object
*/
google::LogMessage& operator<<(google::LogMessage& lhs, const Vertex& rhs);
} // namespace graphcut_base
#endif // _HOME_TAKAYAMAN_DOCUMENTS_PROGRAMMING_GENERAL_GRAPHCUT_GRAPHCUT_VERTEX_H_
| [
"takayaman@uec.ac.jp"
] | takayaman@uec.ac.jp |
b9fdca17c9e23433a1ad55f0ef0fff5297a2848d | 780f7c992c53de027b349e8495a97145de63c5a5 | /BattleTank/Source/BattleTank/Private/TankMovementComponent.cpp | d94f578818ab0d3237821fc84b7e76be00f727b0 | [] | no_license | tamurajunichi/My-Unreal-Engine-Tutorial-code | 287eb252263399ed1b298b4e24d695de5991e6d8 | 78361561db58d16cfa5ad730e9f5d3deda245d7c | refs/heads/master | 2022-10-19T06:55:54.114040 | 2020-05-31T09:25:23 | 2020-05-31T09:25:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,136 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankMovementComponent.h"
#include "TankTrack.h"
void UTankMovementComponent::Initialise(UTankTrack* LeftTrackToSet, UTankTrack* RightTrackToSet)
{
if (!LeftTrackToSet || !RightTrackToSet) { return; }
LeftTrack = LeftTrackToSet;
RightTrack = RightTrackToSet;
}
void UTankMovementComponent::RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed)
{
auto TankForward = GetOwner()->GetActorForwardVector().GetSafeNormal();
auto AIForwardIntention = MoveVelocity.GetSafeNormal();
auto ForwardThrow = FVector::DotProduct(TankForward, AIForwardIntention);
IntendMoveForward(ForwardThrow);
//UE_LOG(LogTemp, Warning, TEXT("%s vectoring to %s"), *TankName, *MoveVelocityString)
}
void UTankMovementComponent::IntendMoveForward(float Throw)
{
if (!LeftTrack || !RightTrack) { return; }
LeftTrack->SetThrottle(Throw);
RightTrack->SetThrottle(Throw);
}
void UTankMovementComponent::IntendTurnRight(float Throw)
{
if (!LeftTrack || !RightTrack) { return; }
LeftTrack->SetThrottle(Throw);
RightTrack->SetThrottle(-Throw);
}
| [
"r201603849je@jindai.jp"
] | r201603849je@jindai.jp |
4613d9bbbca196f02e3d2509fe22711868c26dde | e97522ff5d9c1f51da835f82984da5ae41b424d5 | /libraries/AGS02MA/examples/AGS02MA_UGM3/AGS02MA_UGM3.ino | 56f09399c7652ccdb4b09c8d609ae42b21db7fb1 | [
"MIT"
] | permissive | Spitfaer/Arduino | 1f61d95601350d1825b5d26d9cb68f69d45ccb56 | ad3cf039916342524e7a7caffe168ffac65a1dcc | refs/heads/master | 2023-09-05T11:36:28.246871 | 2021-11-11T19:36:58 | 2021-11-11T19:36:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,241 | ino | //
// FILE: AGS02MA_UGM3.ino
// AUTHOR: Rob Tillaart
// VERSION: 0.1.0
// PURPOSE: test application
// DATE: 2021-08-12
// URL: https://github.com/RobTillaart/AGS02MA
//
#include "AGS02MA.h"
AGS02MA AGS(26);
void setup()
{
Serial.begin(115200);
Serial.println(__FILE__);
Wire.begin();
Serial.print("AGS02MA_LIB_VERSION: ");
Serial.println(AGS02MA_LIB_VERSION);
Serial.println();
bool b = AGS.begin();
Serial.print("BEGIN:\t");
Serial.println(b);
// pre-heating improves measurement quality
// can be skipped
Serial.println("\nWarming up (120 seconds = 24 dots)");
while (AGS.isHeated() == false)
{
delay(5000);
Serial.print(".");
}
Serial.println();
b = AGS.setUGM3Mode();
uint8_t m = AGS.getMode();
Serial.print("MODE:\t");
Serial.print(b);
Serial.print("\t");
Serial.println(m);
uint8_t version = AGS.getSensorVersion();
Serial.print("VERS:\t");
Serial.println(version);
}
void loop()
{
delay(3000);
uint32_t value = AGS.readUGM3();
Serial.print("UGM3:\t");
Serial.print(value);
Serial.print("\t");
Serial.print(AGS.lastStatus(), HEX);
Serial.print("\t");
Serial.print(AGS.lastError(), HEX);
Serial.println();
}
// -- END OF FILE --
| [
"rob.tillaart@gmail.com"
] | rob.tillaart@gmail.com |
898ce67361bfe1476fe802670ee9ba8f0fef2aaa | 86908a017b44cd07963eedd4325c99d410f02395 | /Algorithm/TestRc/ShowImg.cpp | c6aea985ad955f666d86a3b7071596591ea7ba64 | [] | no_license | laoniu2020/MedicalTile | a8ebf9604f2f76cef7740d07e6d20419127950dd | 6d0f172ae863c9d1a3176d2933ff0a5440888f50 | refs/heads/master | 2021-05-29T06:03:36.556875 | 2015-10-04T15:10:05 | 2015-10-04T15:10:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,518 | cpp | #include"ShowImg.h"
#include<QLabel>
#include<QDialog>
#include<QVBoxLayout>
#include<QGraphicsView>
#include<QGraphicsLineItem>
#include<QVector>
#include<QApplication>
DLL_IMPL_BEGIN(1)
DLL_ALGO(ShowImg,0)
DLL_IMPL_END
class amyAxisItem:public QGraphicsItem
{
public:
amyAxisItem()
{
m_MarginWidth=50;
}
void SetBound(float low,float high,float pos,Qt::Orientation o)
{
//this->setTransform(this->transform().rotate(-90));
m_Low=low;
m_High=high;
m_Pos=pos;
m_Orientation=o;
}
void paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0 )
{
//painter->drawText(boundingRect (),Qt::AlignCenter,"AAA");
//painter->save();
//painter->setMatrix(this->matrix());
//painter->drawLine(-50,0,0,100);
painter->drawLine(0,0,50,100);
//painter->restore();
}
QRectF boundingRect () const
{
QPointF p1;
QPointF p2;
if(m_Orientation==Qt::Vertical)
{
p1=QPointF(m_Pos-m_MarginWidth,m_Low);
p2=QPointF(m_Pos,m_High);
}
else if(m_Orientation==Qt::Horizontal)
{
p1=QPointF(m_Low,m_Pos-m_MarginWidth);
p2=QPointF(m_High,m_Pos);
}
return QRectF(p1,p2);
}
private:
float m_Low;
float m_High;
float m_Pos;
Qt::Orientation m_Orientation;
float m_MarginWidth;
};
#include"amyDoubleThresholdWidget.h"
class A
{
public:
operator int()
{
return 1;
}
};
void ShowImg::Run()
{
A mm;
int kk=mm;
Wraper a;
a.moveToThread(QCoreApplication::instance()->thread());
a.func();
this->PostError("KKKK");
this->PostWarning("BBB");
} | [
"1132743253@qq.com"
] | 1132743253@qq.com |
c0bb5f94e44997e6160b5491977780513dd7a2ce | e5b9e08ab97b4c29abf1153d68f55941786696a5 | /Impartial Offerings.cpp | 3b7461ca323a41f3feb1f69f6dd97a104e0d6115 | [] | no_license | aman503/100-Days-of-Code | 244b3a37a50a121f6ce010542c4cffd54b25f8b0 | 249d41c72e7117feb51dc62b96da16106c42f645 | refs/heads/main | 2023-04-29T02:26:22.098829 | 2021-05-16T17:59:21 | 2021-05-16T17:59:21 | 348,445,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 400 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int t,j=1;
cin>>t;
while(t--)
{
int n,ct=1;
cin>>n;
int arr[n];
for(int i=0;i<n;++i) cin>>arr[i];
sort(arr,arr+n);
int temp = 1;
for(int i=1;i<n;++i)
{
if(arr[i-1]==arr[i]) ct+=temp;
else {temp++;ct+=temp;}
}
cout<<"case #"<<j++<<": "<<ct<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
4909188c2812849c486126bd613c1bc311e9a725 | e04f3bebf39ff6ea8be005182e0d98d395b15337 | /org.xtext.alma.enumeration/generated/include/CCalDataOrigin.h | 13aa78ea2a45180c5934a2950bf69b58af68b4f5 | [] | no_license | loriebi/SDMDSL | edb457caf440baa6638ba6997be3d81c613a0049 | 0a41e8d2c1b7c3f1eef1fbc39c793b347f7e9b2b | refs/heads/master | 2021-01-23T20:32:13.222533 | 2017-09-08T14:05:53 | 2017-09-08T14:05:53 | 102,865,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,062 | h | #ifndef CCalDataOrigin_H
#define CCalDataOrigin_H
/*
* ALMA - Atacama Large Millimeter Array
* (c) European Southern Observatory, 2002
* (c) Associated Universities Inc., 2002
* Copyright by ESO (in the framework of the ALMA collaboration),
* Copyright by AUI (in the framework of the ALMA collaboration),
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY, without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* /////////////////////////////////////////////////////////////////
* // WARNING! DO NOT MODIFY THIS FILE! //
* // --------------------------------------------------------- //
* // | This is generated code! Do not modify this file. | //
* // | Any changes will be lost when the file is re-generated. | //
* // --------------------------------------------------------- //
* /////////////////////////////////////////////////////////////////
*
* File CCalDataOrigin.h
*/
#ifndef __cplusplus
#error This is a C++ include file and cannot be used from plain C
#endif
#include <iostream>
#include <string>
#include <vector>
/**
* A namespace to encapsulate the CalDataOrigin enumeration.
*/
#ifndef WITHOUT_ACS
#include <almaEnumerations_IFC.h>
#else
// This part mimics the behaviour of
namespace CalDataOriginMod
{
//! CalDataOrigin
//!
const char *const revision = "1";
const int version = 1;
enum CalDataOrigin{
TOTAL_POWER !< Total Power data (from detectors) ,
WVR !< Water vapour radiometrers ,
CHANNEL_AVERAGE_AUTO !< Autocorrelations from channel average data ,
CHANNEL_AVERAGE_CROSS !< Crosscorrelations from channel average data ,
FULL_RESOLUTION_AUTO !< Autocorrelations from full-resolution data ,
FULL_RESOLUTION_CROSS !< Cross correlations from full-resolution data ,
OPTICAL_POINTING !< Optical pointing data ,
HOLOGRAPHY !< data from holography receivers ,
NONE !< Not applicable
};
typedef CalDataOrigin &CalDataOrigin_out;
}
#endif
namespace CalDataOriginMod {
std::ostream & operator << ( std::ostream & out, const CalDataOrigin& value);
std::istream & operator >> ( std::istream & in , CalDataOrigin& value );
}
/**
* A helper class for the enumeration CalDataOrigin.
*
*/
class CCalDataOrigin {
public:
/**
* Enumerators as strings.
*/
static const std::string& sTOTAL_POWER; /*!< A const string equal to "TOTAL_POWER" .*/
static const std::string& sWVR; /*!< A const string equal to "WVR" .*/
static const std::string& sCHANNEL_AVERAGE_AUTO; /*!< A const string equal to "CHANNEL_AVERAGE_AUTO" .*/
static const std::string& sCHANNEL_AVERAGE_CROSS; /*!< A const string equal to "CHANNEL_AVERAGE_CROSS" .*/
static const std::string& sFULL_RESOLUTION_AUTO; /*!< A const string equal to "FULL_RESOLUTION_AUTO" .*/
static const std::string& sFULL_RESOLUTION_CROSS; /*!< A const string equal to "FULL_RESOLUTION_CROSS" .*/
static const std::string& sOPTICAL_POINTING; /*!< A const string equal to "OPTICAL_POINTING" .*/
static const std::string& sHOLOGRAPHY; /*!< A const string equal to "HOLOGRAPHY" .*/
static const std::string& sNONE; /*!< A const string equal to "NONE" .*/
/**
* Return the major version number as an int.
* @return an int.
*/
static int version();
/**
* Return the revision as a string.
* @return a string
*/
static std::string revision();
/**
* Return the number of enumerators declared in CalDataOriginMod::CalDataOrigin.
* @return an unsigned int.
*/
static unsigned int size();
/**
* Returns an enumerator as a string.
* @param e an enumerator of CalDataOriginMod::CalDataOrigin.
* @return a string.
*/
static std::string name(const CalDataOriginMod::CalDataOrigin& e);
/**
* Equivalent to the name method.
*/
static std::string toString(const CalDataOriginMod::CalDataOrigin& f) { return name(f); }
/**
* Returns vector of all the enumerators as strings.
* The strings are stored in the vector in the same order than the enumerators are declared in the enumeration.
* @return a vector of string.
*/
static const std::vector<std::string> names();
// Create a CalDataOrigin enumeration object by specifying its name.
static CalDataOriginMod::CalDataOrigin newCalDataOrigin(const std::string& name);
/*! Return a CalDataOrigin's enumerator given a string.
* @param name the string representation of the enumerator.
* @return a CalDataOriginMod::CalDataOrigin's enumerator.
* @throws a string containing an error message if no enumerator could be found for this name.
*/
static CalDataOriginMod::CalDataOrigin literal(const std::string& name);
/*! Return a CalDataOrigin's enumerator given an unsigned int.
* @param i the index of the enumerator in CalDataOriginMod::CalDataOrigin.
* @return a CalDataOriginMod::CalDataOrigin's enumerator.
* @throws a string containing an error message if no enumerator could be found for this integer.
*/
static CalDataOriginMod::CalDataOrigin from_int(unsigned int i);
private:
/* Not Implemented. This is a pure static class. */
CCalDataOrigin();
CCalDataOrigin(const CCalDataOrigin&);
CCalDataOrigin& operator=(const CCalDataOrigin&);
static std::string badString(const std::string& name);
static std::string badInt(unsigned int i);
};
#endif /*!CCalDataOrigin_H*/
| [
"levan.l2ria@gmail.com"
] | levan.l2ria@gmail.com |
bf6c7a2ccbc28bdaab9d2b534cddf655aa963e6c | b28305dab0be0e03765c62b97bcd7f49a4f8073d | /components/omnibox/browser/omnibox_field_trial.h | 99f79ed0007757f74911d29cd63ecde780870bfa | [
"BSD-3-Clause"
] | permissive | svarvel/browser-android-tabs | 9e5e27e0a6e302a12fe784ca06123e5ce090ced5 | bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f | refs/heads/base-72.0.3626.105 | 2020-04-24T12:16:31.442851 | 2019-08-02T19:15:36 | 2019-08-02T19:15:36 | 171,950,555 | 1 | 2 | NOASSERTION | 2019-08-02T19:15:37 | 2019-02-21T21:47:44 | null | UTF-8 | C++ | false | false | 25,210 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_OMNIBOX_BROWSER_OMNIBOX_FIELD_TRIAL_H_
#define COMPONENTS_OMNIBOX_BROWSER_OMNIBOX_FIELD_TRIAL_H_
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "base/macros.h"
#include "components/omnibox/browser/autocomplete_input.h"
#include "components/omnibox/browser/autocomplete_match_type.h"
#include "third_party/metrics_proto/omnibox_event.pb.h"
namespace base {
struct Feature;
class TimeDelta;
}
namespace omnibox {
extern const base::Feature kHideFileUrlScheme;
extern const base::Feature kHideSteadyStateUrlScheme;
extern const base::Feature kHideSteadyStateUrlTrivialSubdomains;
extern const base::Feature kHideSteadyStateUrlPathQueryAndRef;
extern const base::Feature kOneClickUnelide;
extern const base::Feature kSimplifyHttpsIndicator;
extern const base::Feature kOmniboxRichEntitySuggestions;
extern const base::Feature kOmniboxNewAnswerLayout;
extern const base::Feature kOmniboxReverseAnswers;
extern const base::Feature kOmniboxTailSuggestions;
extern const base::Feature kOmniboxTabSwitchSuggestions;
extern const base::Feature kExperimentalKeywordMode;
extern const base::Feature kOmniboxPedalSuggestions;
extern const base::Feature kEnableClipboardProvider;
extern const base::Feature kSearchProviderWarmUpOnFocus;
extern const base::Feature kZeroSuggestRedirectToChrome;
extern const base::Feature kZeroSuggestSwapTitleAndUrl;
extern const base::Feature kDisplayTitleForCurrentUrl;
extern const base::Feature kQueryInOmnibox;
extern const base::Feature kUIExperimentMaxAutocompleteMatches;
extern const base::Feature kUIExperimentSwapTitleAndUrl;
extern const base::Feature kUIExperimentVerticalMargin;
extern const base::Feature kSpeculativeServiceWorkerStartOnQueryInput;
extern const base::Feature kDocumentProvider;
extern const base::Feature kOmniboxPopupShortcutIconsInZeroState;
} // namespace omnibox
// The set of parameters customizing the HUP scoring.
struct HUPScoringParams {
// A set of parameters describing how to cap a given count score. First,
// we apply a half-life based decay of the given count and then find the
// maximum relevance score based on the decay factor or counts specified
// in the corresponding bucket list. See comment on |buckets_| for details.
class ScoreBuckets {
public:
// Stores the max relevance at each count/decay factor threshold.
typedef std::pair<double, int> CountMaxRelevance;
ScoreBuckets();
ScoreBuckets(const ScoreBuckets& other);
~ScoreBuckets();
// Computes a half-life time decay given the |elapsed_time|.
double HalfLifeTimeDecay(const base::TimeDelta& elapsed_time) const;
int relevance_cap() const { return relevance_cap_; }
void set_relevance_cap(int relevance_cap) {
relevance_cap_ = relevance_cap;
}
int half_life_days() const { return half_life_days_; }
void set_half_life_days(int half_life_days) {
half_life_days_ = half_life_days;
}
bool use_decay_factor() const { return use_decay_factor_; }
void set_use_decay_factor(bool use_decay_factor) {
use_decay_factor_ = use_decay_factor;
}
std::vector<CountMaxRelevance>& buckets() { return buckets_; }
const std::vector<CountMaxRelevance>& buckets() const { return buckets_; }
// Estimates dynamic memory usage.
// See base/trace_event/memory_usage_estimator.h for more info.
size_t EstimateMemoryUsage() const;
private:
// History matches with relevance score greater or equal to |relevance_cap_|
// are not affected by this experiment.
// Set to -1, if there is no relevance cap in place and all matches are
// subject to demotion.
int relevance_cap_;
// Half life time for a decayed count as measured since the last visit.
// Set to -1 if not used.
int half_life_days_;
// The relevance score caps at successively decreasing threshold values.
// The thresholds are either decayed counts or decay factors, depending on
// the value of |use_decay_factor_|.
//
// Consider this example specifying the decayed counts:
// [(1, 1000), (0.5, 500), (0, 100)]
// If decayed count is 2 (which is >= 1), the corresponding match's maximum
// relevance will be capped at 1000. In case of 0.5, the score is capped
// at 500. Anything below 0.5 is capped at 100.
//
// This list is sorted by the pair's first element in descending order.
std::vector<CountMaxRelevance> buckets_;
// True when the bucket thresholds are decay factors rather than counts.
bool use_decay_factor_;
};
HUPScoringParams() {}
// Estimates dynamic memory usage.
// See base/trace_event/memory_usage_estimator.h for more info.
size_t EstimateMemoryUsage() const;
ScoreBuckets typed_count_buckets;
// Used only when the typed count is 0.
ScoreBuckets visited_count_buckets;
};
// This class manages the Omnibox field trials.
class OmniboxFieldTrial {
public:
// A mapping that contains multipliers indicating that matches of the
// specified type should have their relevance score multiplied by the
// given number. Omitted types are assumed to have multipliers of 1.0.
typedef std::map<AutocompleteMatchType::Type, float> DemotionMultipliers;
// A vector that maps from the number of matching pages to the document
// specificity score used in HistoryQuick provider / ScoredHistoryMatch
// scoring. The vector is sorted by the size_t (the number of matching pages).
// If an entry is omitted, the appropriate value is assumed to be the one in
// the later bucket. For example, with a vector containing {{1, 2.0},
// {3, 1.5}}, the score for 2 is inferred to be 1.5. Values beyond the
// end of the vector are assumed to have scores of 1.0.
typedef std::vector<std::pair<size_t, double>> NumMatchesScores;
// Do not change these values as they need to be in sync with values
// specified in experiment configs on the variations server.
enum EmphasizeTitlesCondition {
EMPHASIZE_WHEN_NONEMPTY = 0,
EMPHASIZE_WHEN_TITLE_MATCHES = 1,
EMPHASIZE_WHEN_ONLY_TITLE_MATCHES = 2,
EMPHASIZE_NEVER = 3
};
// These are the discrete possibilities for Pedal behavior.
enum class PedalSuggestionMode {
NONE,
IN_SUGGESTION,
DEDICATED,
};
// ---------------------------------------------------------
// For any experiment that's part of the bundled omnibox field trial.
// Returns a bitmap containing AutocompleteProvider::Type values
// that should be disabled in AutocompleteController.
static int GetDisabledProviderTypes();
// Returns whether the user is in any dynamic field trial where the
// group has a the prefix |group_prefix|.
static bool HasDynamicFieldTrialGroupPrefix(const char *group_prefix);
// ---------------------------------------------------------
// For the suggest field trial.
// Populates |field_trial_hash| with hashes of the active suggest field trial
// names, if any.
static void GetActiveSuggestFieldTrialHashes(
std::vector<uint32_t>* field_trial_hash);
// ---------------------------------------------------------
// For the AutocompleteController "stop timer" field trial.
// Returns the duration to be used for the AutocompleteController's stop
// timer. Returns the default value of 1.5 seconds if the stop timer
// override experiment isn't active or if parsing the experiment-provided
// duration fails.
static base::TimeDelta StopTimerFieldTrialDuration();
// ---------------------------------------------------------
// For the ZeroSuggestProvider field trial.
// Returns whether the user is in a ZeroSuggest field trial, which shows
// most visited URLs. This is true for both "MostVisited" and
// "MostVisitedWithoutSERP" trials.
static bool InZeroSuggestMostVisitedFieldTrial();
// Returns whether the user is in ZeroSuggest field trial showing most
// visited URLs except it doesn't show suggestions on Google search result
// pages.
static bool InZeroSuggestMostVisitedWithoutSerpFieldTrial();
// Returns whether the user is in a ZeroSuggest field trial, but should
// show recently searched-for queries instead.
static bool InZeroSuggestPersonalizedFieldTrial();
// ---------------------------------------------------------
// For the Zero Suggest Redirect to Chrome field trial.
// Returns the server-side experiment ID to use for contextual suggestions.
// Returns -1 if there is no associated experiment ID.
static int GetZeroSuggestRedirectToChromeExperimentId();
// Returns the server address associated with the current field trial.
static std::string GetZeroSuggestRedirectToChromeServerAddress();
// ---------------------------------------------------------
// For the ShortcutsScoringMaxRelevance experiment that's part of the
// bundled omnibox field trial.
// If the user is in an experiment group that, given the provided
// |current_page_classification| context, changes the maximum relevance
// ShortcutsProvider::CalculateScore() is supposed to assign, extract
// that maximum relevance score and put in in |max_relevance|. Returns
// true on a successful extraction. CalculateScore()'s return value is
// a product of this maximum relevance score and some attenuating factors
// that are all between 0 and 1. (Note that Shortcuts results may have
// their scores reduced later if the assigned score is higher than allowed
// for non-inlineable results. Shortcuts results are not allowed to be
// inlined.)
static bool ShortcutsScoringMaxRelevance(
metrics::OmniboxEventProto::PageClassification
current_page_classification,
int* max_relevance);
// ---------------------------------------------------------
// For the SearchHistory experiment that's part of the bundled omnibox
// field trial.
// Returns true if the user is in the experiment group that, given the
// provided |current_page_classification| context, scores search history
// query suggestions less aggressively so that they don't inline.
static bool SearchHistoryPreventInlining(
metrics::OmniboxEventProto::PageClassification
current_page_classification);
// Returns true if the user is in the experiment group that, given the
// provided |current_page_classification| context, disables all query
// suggestions from search history.
static bool SearchHistoryDisable(
metrics::OmniboxEventProto::PageClassification
current_page_classification);
// ---------------------------------------------------------
// For the DemoteByType experiment that's part of the bundled omnibox field
// trial.
// If the user is in an experiment group that, in the provided
// |current_page_classification| context, demotes the relevance scores
// of certain types of matches, populates the |demotions_by_type| map
// appropriately. Otherwise, sets |demotions_by_type| to its default
// value based on the context.
static void GetDemotionsByType(
metrics::OmniboxEventProto::PageClassification
current_page_classification,
DemotionMultipliers* demotions_by_type);
// ---------------------------------------------------------
// For the HistoryURL provider new scoring experiment that is part of the
// bundled omnibox field trial.
// Initializes the HUP |scoring_params| based on the active HUP scoring
// experiment.
static void GetDefaultHUPScoringParams(HUPScoringParams* scoring_params);
static void GetExperimentalHUPScoringParams(HUPScoringParams* scoring_params);
// ---------------------------------------------------------
// For the HQPBookmarkValue experiment that's part of the
// bundled omnibox field trial.
// Returns the value an untyped visit to a bookmark should receive.
// Compare this value with the default of 1 for non-bookmarked untyped
// visits to pages and the default of 20 for typed visits. Returns
// 10 if the bookmark value experiment isn't active.
static float HQPBookmarkValue();
// ---------------------------------------------------------
// For the HQPAllowMatchInTLD experiment that's part of the
// bundled omnibox field trial.
// Returns true if HQP should allow an input term to match in the
// top level domain (e.g., .com) of a URL. Returns false if the
// allow match in TLD experiment isn't active.
static bool HQPAllowMatchInTLDValue();
// ---------------------------------------------------------
// For the HQPAllowMatchInScheme experiment that's part of the
// bundled omnibox field trial.
// Returns true if HQP should allow an input term to match in the
// scheme (e.g., http://) of a URL. Returns false if the allow
// match in scheme experiment isn't active.
static bool HQPAllowMatchInSchemeValue();
// ---------------------------------------------------------
// For SearchProvider related experiments.
// Returns true if the search provider should not be caching results.
static bool DisableResultsCaching();
// Returns how the search provider should poll Suggest. Currently, we support
// measuring polling delay from the last keystroke or last suggest request.
static void GetSuggestPollingStrategy(bool* from_last_keystroke,
int* polling_delay_ms);
// ---------------------------------------------------------
// For HQP scoring related experiments to control the topicality and scoring
// ranges of relevancy scores.
// Returns the scoring buckets for HQP experiments. Returns an empty string
// if scoring buckets are not specified in the field trial. Scoring buckets
// are stored in string form giving mapping from (topicality_score,
// frequency_score) to final relevance score. Please see GetRelevancyScore()
// under chrome/browser/history::ScoredHistoryMatch for details.
static std::string HQPExperimentalScoringBuckets();
// Returns the topicality threshold for HQP experiments. Returns a default
// value of 0.5 if no threshold is specified in the field trial.
static float HQPExperimentalTopicalityThreshold();
// ---------------------------------------------------------
// For experiment to limit HQP url indexing that's part of the bundled
// omnibox field trial.
// Returns the maximum number of history urls to index for HQP at the startup.
// Note: this limit is only applied at startup and more urls can be indexed
// during the session. Returns -1 if limit is not set by trials.
static int MaxNumHQPUrlsIndexedAtStartup();
// ---------------------------------------------------------
// For the HQPFixFrequencyScoring experiment that's part of the
// bundled omnibox field trial.
// Returns the number of visits HQP should use when computing frequency
// scores. Returns 10 if the epxeriment isn't active.
static size_t HQPMaxVisitsToScore();
// Returns the score that should be given to typed transitions. (The score
// of non-typed transitions is 1.) Returns 1.5 if the experiment isn't
// active.
static float HQPTypedValue();
// Returns NumMatchesScores; see comment by the declaration of it.
// If the experiment isn't active, returns an NumMatchesScores of
// {{1, 3}, {2, 2.5}, {3, 2}, {4, 1.5}}.
static NumMatchesScores HQPNumMatchesScores();
// ---------------------------------------------------------
// For the HQPNumTitleWords experiment that's part of the
// bundled omnibox field trial.
// Returns the number of title words that are allowed to contribute
// to the topicality score. Words later in the title are ignored.
// Returns 20 as a default if the experiment isn't active.
static size_t HQPNumTitleWordsToAllow();
// ---------------------------------------------------------
// For the replace HUP experiment that's part of the bundled omnibox field
// trial.
// Returns whether HistoryQuick provider (HQP) should attempt to score
// suggestions also with a HistoryURL-provider-like (HUP-like) mode, and
// assign suggestions the max of this score and the normal score.
// Returns false if the experiment isn't active.
static bool HQPAlsoDoHUPLikeScoring();
// Returns whether HistoryURL provider (HUP) should search its database for
// URLs and suggest them. If false, HistoryURL provider merely creates the
// URL-what-you-typed match when appropriate. Return true if the experiment
// isn't active.
static bool HUPSearchDatabase();
// ---------------------------------------------------------
// For the aggressive keyword matching experiment that's part of the bundled
// omnibox field trial.
// One function is missing from here to avoid a cyclic dependency
// between search_engine and omnibox. In the search_engine component
// there is a OmniboxFieldTrialKeywordRequiresRegistry function
// that logically should be here.
//
// It returns whether KeywordProvider should consider the registry portion
// (e.g., co.uk) of keywords that look like hostnames as an important part of
// the keyword name for matching purposes. Returns true if the experiment
// isn't active.
// For keywords that look like hostnames, returns whether KeywordProvider
// should require users to type a prefix of the hostname to match against
// them, rather than just the domain name portion. In other words, returns
// whether the prefix before the domain name should be considered important
// for matching purposes. Returns true if the experiment isn't active.
static bool KeywordRequiresPrefixMatch();
// Returns the relevance score that KeywordProvider should assign to keywords
// with sufficiently-complete matches, i.e., the user has typed all of the
// important part of the keyword. Returns -1 if the experiment isn't active.
static int KeywordScoreForSufficientlyCompleteMatch();
// ---------------------------------------------------------
// For the EmphasizeTitles experiment that's part of the bundled omnibox
// field trial.
// Returns the conditions under which the UI code should display the title
// of a URL more prominently than the URL for input |input|. Normally the URL
// is displayed more prominently. Returns NEVER_EMPHASIZE if the experiment
// isn't active.
static EmphasizeTitlesCondition GetEmphasizeTitlesConditionForInput(
const AutocompleteInput& input);
// ---------------------------------------------------------
// For UI experiments.
// Returns true if the rich entities flag is enabled.
static bool IsRichEntitySuggestionsEnabled();
// Returns true if either the new answer layout flag or the
// #upcoming-ui-features flag is enabled.
static bool IsNewAnswerLayoutEnabled();
// Returns true if either the reverse answers flag or the
// #upcoming-ui-features flag is enabled.
static bool IsReverseAnswersEnabled();
// Returns true if either the tab switch suggestions flag or the
// #upcoming-ui-features flag is enabled.
static bool IsTabSwitchSuggestionsEnabled();
// Returns the #omnibox-pedal-suggestions feature's mode parameter as enum.
static PedalSuggestionMode GetPedalSuggestionMode();
// Returns true if either the steady-state elision flag for scheme or the
// #upcoming-ui-features flag is enabled.
static bool IsHideSteadyStateUrlSchemeEnabled();
// Returns true if either the steady-state elision flag for trivial
// subdomains or the #upcoming-ui-features flag is enabled.
static bool IsHideSteadyStateUrlTrivialSubdomainsEnabled();
// Returns true if the experimental keyword mode is enabled.
static bool IsExperimentalKeywordModeEnabled();
// ---------------------------------------------------------
// Clipboard URL suggestions:
// The parameter "ClipboardURLMaximumAge" doesn't live in this file; instead
// it lives in
// components/open_from_clipboard/clipboard_recent_content.cc.
// Please see ClipboardRecentContent::MaximumAgeOfClipboard() for the usage
// of it. The parameter cannot live here because that component cannot
// include this component, else there would be a circular dependency.
// ---------------------------------------------------------
// Exposed publicly for the sake of unittests.
static const char kBundledExperimentFieldTrialName[];
// Rule names used by the bundled experiment.
static const char kDisableProvidersRule[];
static const char kShortcutsScoringMaxRelevanceRule[];
static const char kSearchHistoryRule[];
static const char kDemoteByTypeRule[];
static const char kHQPBookmarkValueRule[];
static const char kHQPTypedValueRule[];
static const char kHQPAllowMatchInTLDRule[];
static const char kHQPAllowMatchInSchemeRule[];
static const char kZeroSuggestVariantRule[];
static const char kDisableResultsCachingRule[];
static const char kMeasureSuggestPollingDelayFromLastKeystrokeRule[];
static const char kSuggestPollingDelayMsRule[];
static const char kHQPMaxVisitsToScoreRule[];
static const char kHQPNumMatchesScoresRule[];
static const char kHQPNumTitleWordsRule[];
static const char kHQPAlsoDoHUPLikeScoringRule[];
static const char kHUPSearchDatabaseRule[];
static const char kPreventUWYTDefaultForNonURLInputsRule[];
static const char kKeywordRequiresRegistryRule[];
static const char kKeywordRequiresPrefixMatchRule[];
static const char kKeywordScoreForSufficientlyCompleteMatchRule[];
static const char kHQPAllowDupMatchesForScoringRule[];
static const char kEmphasizeTitlesRule[];
// Parameter names used by the HUP new scoring experiments.
static const char kHUPNewScoringTypedCountRelevanceCapParam[];
static const char kHUPNewScoringTypedCountHalfLifeTimeParam[];
static const char kHUPNewScoringTypedCountScoreBucketsParam[];
static const char kHUPNewScoringTypedCountUseDecayFactorParam[];
static const char kHUPNewScoringVisitedCountRelevanceCapParam[];
static const char kHUPNewScoringVisitedCountHalfLifeTimeParam[];
static const char kHUPNewScoringVisitedCountScoreBucketsParam[];
static const char kHUPNewScoringVisitedCountUseDecayFactorParam[];
// Parameter names used by the HQP experimental scoring experiments.
static const char kHQPExperimentalScoringBucketsParam[];
static const char kHQPExperimentalScoringTopicalityThresholdParam[];
// Parameter names used by the experiment that limits the number of history
// urls indexed for suggestions.
static const char kMaxNumHQPUrlsIndexedAtStartupOnLowEndDevicesParam[];
static const char kMaxNumHQPUrlsIndexedAtStartupOnNonLowEndDevicesParam[];
// Parameter names used by UI experiments.
static const char kUIMaxAutocompleteMatchesParam[];
static const char kUIVerticalMarginParam[];
static const char kPedalSuggestionModeParam[];
// Parameter name and values used by the Simplify HTTPS experiment.
static const char kSimplifyHttpsIndicatorParameterName[];
static const char kSimplifyHttpsIndicatorParameterEvToSecure[];
static const char kSimplifyHttpsIndicatorParameterSecureToLock[];
static const char kSimplifyHttpsIndicatorParameterBothToLock[];
static const char kSimplifyHttpsIndicatorParameterKeepSecureChip[];
// Parameter names used by Zero Suggest Redirect to Chrome.
static const char kZeroSuggestRedirectToChromeExperimentIdParam[];
static const char kZeroSuggestRedirectToChromeServerAddressParam[];
// The amount of time to wait before sending a new suggest request after the
// previous one unless overridden by a field trial parameter.
// Non-const because some unittests modify this value.
static int kDefaultMinimumTimeBetweenSuggestQueriesMs;
private:
friend class OmniboxFieldTrialTest;
// The bundled omnibox experiment comes with a set of parameters
// (key-value pairs). Each key indicates a certain rule that applies in
// a certain context. The value indicates what the consequences of
// applying the rule are. For example, the value of a SearchHistory rule
// in the context of a search results page might indicate that we should
// prevent search history matches from inlining.
//
// This function returns the value associated with the |rule| that applies
// in the current context (which currently consists of |page_classification|
// and whether Instant Extended is enabled). If no such rule exists in the
// current context, fall back to the rule in various wildcard contexts and
// return its value if found. If the rule remains unfound in the global
// context, returns the empty string. For more details, including how we
// prioritize different wildcard contexts, see the implementation. How to
// interpret the value is left to the caller; this is rule-dependent.
static std::string GetValueForRuleInContext(
const std::string& rule,
metrics::OmniboxEventProto::PageClassification page_classification);
DISALLOW_IMPLICIT_CONSTRUCTORS(OmniboxFieldTrial);
};
#endif // COMPONENTS_OMNIBOX_BROWSER_OMNIBOX_FIELD_TRIAL_H_
| [
"artem@brave.com"
] | artem@brave.com |
9c733822aefb362ad666dac8b78b0a3a86d2b6a0 | 6d54a7b26d0eb82152a549a6a9dfde656687752c | /src/app/clusters/ota-requestor/DefaultOTARequestorUserConsent.h | c56fde44a51dd17a4c0166b18541aeec93b03fe9 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | project-chip/connectedhomeip | 81a123d675cf527773f70047d1ed1c43be5ffe6d | ea3970a7f11cd227ac55917edaa835a2a9bc4fc8 | refs/heads/master | 2023-09-01T11:43:37.546040 | 2023-09-01T08:01:32 | 2023-09-01T08:01:32 | 244,694,174 | 6,409 | 1,789 | Apache-2.0 | 2023-09-14T20:56:31 | 2020-03-03T17:05:10 | C++ | UTF-8 | C++ | false | false | 1,959 | h | /*
*
* Copyright (c) 2022 Project CHIP Authors
* 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.
*/
#pragma once
#include <app/clusters/ota-requestor/OTARequestorUserConsentDelegate.h>
#include <lib/core/CHIPError.h>
namespace chip {
namespace ota {
/**
* @brief Default implementation of OTARequestorUserConsentDelegate interface.
*
* This class provides API to set the user consent state, and this state is then used by
* OTA Requestor Driver to decide whether to continue with the OTA process.
*/
class DefaultOTARequestorUserConsent : public OTARequestorUserConsentDelegate
{
public:
DefaultOTARequestorUserConsent() = default;
~DefaultOTARequestorUserConsent() = default;
// This method returns kGranted unless explicitly set by the user by calling SetUserConsentState()
UserConsentState GetUserConsentState(const UserConsentSubject & subject) override
{
UserConsentState curUserConsentState = mUserConsentState;
subject.Log();
mUserConsentState = chip::ota::UserConsentState::kGranted;
return curUserConsentState;
}
UserConsentState CheckDeferredUserConsentState() override { return mUserConsentState; }
void SetUserConsentState(UserConsentState state) { mUserConsentState = state; }
private:
UserConsentState mUserConsentState = UserConsentState::kGranted;
};
} // namespace ota
} // namespace chip
| [
"noreply@github.com"
] | noreply@github.com |
e911db9a8739e40073790660cf43d67fc4b84cc0 | df448416c46efbde45933c8f53ae566934e0c6cf | /HarmonyCoin/src/pbkdf2.cpp | 576b3441a925353ea3592054ffa144ac7bb9ac88 | [
"MIT"
] | permissive | exmachinacoin/HarmonyCoin | f76531b8af3763aeb7465031aa3d46cf42c4dc01 | 8ddbce0d06d2cf7a069aab6d0220af32eba973ed | refs/heads/master | 2021-06-18T06:09:14.409288 | 2017-06-20T10:07:04 | 2017-06-20T10:07:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,945 | cpp | // Copyright (c) 2013-2015 NovaCoin Developers
// Copyright (c) 2015 The HarmonyCoin developers
#include <string.h>
#include "pbkdf2.h"
static inline uint32_t
be32dec(const void *pp)
{
const uint8_t *p = (uint8_t const *)pp;
return ((uint32_t)(p[3]) + ((uint32_t)(p[2]) << 8) +
((uint32_t)(p[1]) << 16) + ((uint32_t)(p[0]) << 24));
}
static inline void
be32enc(void *pp, uint32_t x)
{
uint8_t * p = (uint8_t *)pp;
p[3] = x & 0xff;
p[2] = (x >> 8) & 0xff;
p[1] = (x >> 16) & 0xff;
p[0] = (x >> 24) & 0xff;
}
/* Initialize an HMAC-SHA256 operation with the given key. */
void
HMAC_SHA256_Init(HMAC_SHA256_CTX * ctx, const void * _K, size_t Klen)
{
unsigned char pad[64];
unsigned char khash[32];
const unsigned char * K = (const unsigned char *)_K;
size_t i;
/* If Klen > 64, the key is really SHA256(K). */
if (Klen > 64) {
SHA256_Init(&ctx->ictx);
SHA256_Update(&ctx->ictx, K, Klen);
SHA256_Final(khash, &ctx->ictx);
K = khash;
Klen = 32;
}
/* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */
SHA256_Init(&ctx->ictx);
memset(pad, 0x36, 64);
for (i = 0; i < Klen; i++)
pad[i] ^= K[i];
SHA256_Update(&ctx->ictx, pad, 64);
/* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */
SHA256_Init(&ctx->octx);
memset(pad, 0x5c, 64);
for (i = 0; i < Klen; i++)
pad[i] ^= K[i];
SHA256_Update(&ctx->octx, pad, 64);
/* Clean the stack. */
memset(khash, 0, 32);
}
/* Add bytes to the HMAC-SHA256 operation. */
void
HMAC_SHA256_Update(HMAC_SHA256_CTX * ctx, const void *in, size_t len)
{
/* Feed data to the inner SHA256 operation. */
SHA256_Update(&ctx->ictx, in, len);
}
/* Finish an HMAC-SHA256 operation. */
void
HMAC_SHA256_Final(unsigned char digest[32], HMAC_SHA256_CTX * ctx)
{
unsigned char ihash[32];
/* Finish the inner SHA256 operation. */
SHA256_Final(ihash, &ctx->ictx);
/* Feed the inner hash to the outer SHA256 operation. */
SHA256_Update(&ctx->octx, ihash, 32);
/* Finish the outer SHA256 operation. */
SHA256_Final(digest, &ctx->octx);
/* Clean the stack. */
memset(ihash, 0, 32);
}
/**
* PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen):
* Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and
* write the output to buf. The value dkLen must be at most 32 * (2^32 - 1).
*/
void
PBKDF2_SHA256(const uint8_t * passwd, size_t passwdlen, const uint8_t * salt,
size_t saltlen, uint64_t c, uint8_t * buf, size_t dkLen)
{
HMAC_SHA256_CTX PShctx, hctx;
size_t i;
uint8_t ivec[4];
uint8_t U[32];
uint8_t T[32];
uint64_t j;
int k;
size_t clen;
/* Compute HMAC state after processing P and S. */
HMAC_SHA256_Init(&PShctx, passwd, passwdlen);
HMAC_SHA256_Update(&PShctx, salt, saltlen);
/* Iterate through the blocks. */
for (i = 0; i * 32 < dkLen; i++) {
/* Generate INT(i + 1). */
be32enc(ivec, (uint32_t)(i + 1));
/* Compute U_1 = PRF(P, S || INT(i)). */
memcpy(&hctx, &PShctx, sizeof(HMAC_SHA256_CTX));
HMAC_SHA256_Update(&hctx, ivec, 4);
HMAC_SHA256_Final(U, &hctx);
/* T_i = U_1 ... */
memcpy(T, U, 32);
for (j = 2; j <= c; j++) {
/* Compute U_j. */
HMAC_SHA256_Init(&hctx, passwd, passwdlen);
HMAC_SHA256_Update(&hctx, U, 32);
HMAC_SHA256_Final(U, &hctx);
/* ... xor U_j ... */
for (k = 0; k < 32; k++)
T[k] ^= U[k];
}
/* Copy as many bytes as necessary into buf. */
clen = dkLen - i * 32;
if (clen > 32)
clen = 32;
memcpy(&buf[i * 32], T, clen);
}
/* Clean PShctx, since we never called _Final on it. */
memset(&PShctx, 0, sizeof(HMAC_SHA256_CTX));
}
| [
"ksh21tprld@naver.com"
] | ksh21tprld@naver.com |
eaf35432e2c780aee102b5fd5ce4a82e6c67865c | 8afb5afd38548c631f6f9536846039ef6cb297b9 | /MY_REPOS/misc-experiments/_FIREBFIRE/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc | 5b332b72024c98a7135b0c23494759ae00502e08 | [
"MIT",
"Apache-2.0"
] | permissive | bgoonz/UsefulResourceRepo2.0 | d87588ffd668bb498f7787b896cc7b20d83ce0ad | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | refs/heads/master | 2023-03-17T01:22:05.254751 | 2022-08-11T03:18:22 | 2022-08-11T03:18:22 | 382,628,698 | 10 | 12 | MIT | 2022-10-10T14:13:54 | 2021-07-03T13:58:52 | null | UTF-8 | C++ | false | false | 2,985 | cc | /*
*
* Copyright 2017 gRPC 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
*
orm.h>
#include "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/is_epollexclusive_available.h"
#ifdef GRPC_LINUX_EPOLL_CREATE1
#include <grpc/support/log.h>
#include <errno.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <unistd.h>
#include "src/core/lib/iomgr/sys_epoll_wrapper.h"
/* This polling engine is only relevant on linux kernels supporting epoll() */
bool grpc_is_epollexclusive_available(void) {
static bool logged_why_not = false;
int fd = epoll_create1(EPOLL_CLOEXEC);
if (fd < 0) {
if (!logged_why_not) {
gpr_log(GPR_DEBUG,
"epoll_create1 failed with error: %d. Not using epollex polling "
"engine.",
fd);
logged_why_not = true;
}
return false;
}
int evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (evfd < 0) {
if (!logged_why_not) {
gpr_log(GPR_DEBUG,
"eventfd failed with error: %d. Not using epollex polling "
"engine.",
fd);
logged_why_not = true;
}
close(fd);
return false;
}
struct epoll_event ev;
/* choose events that should cause an error on
EPOLLEXCLUSIVE enabled kernels - specifically the combination of
EPOLLONESHOT and EPOLLEXCLUSIVE */
ev.events =
static_cast<uint32_t>(EPOLLET | EPOLLIN | EPOLLEXCLUSIVE | EPOLLONESHOT);
ev.data.ptr = nullptr;
if (epoll_ctl(fd, EPOLL_CTL_ADD, evfd, &ev) != 0) {
if (errno != EINVAL) {
if (!logged_why_not) {
gpr_log(
GPR_ERROR,
"epoll_ctl with EPOLLEXCLUSIVE | EPOLLONESHOT failed with error: "
"%d. Not using epollex polling engine.",
errno);
logged_why_not = true;
}
close(fd);
close(evfd);
return false;
}
} else {
if (!logged_why_not) {
gpr_log(GPR_DEBUG,
"epoll_ctl with EPOLLEXCLUSIVE | EPOLLONESHOT succeeded. This is "
"evidence of no EPOLLEXCLUSIVE support. Not using "
"epollex polling engine.");
logged_why_not = true;
}
close(fd);
close(evfd);
return false;
}
// Check that EPOLLEXCLUSIVE is supported at all.
ev.events = static_cast<uint32_t>(EPOLLET | EPOLLIN | EPOLLEXCLUSIVE);
if (epoll_ctl(fd, EPOLL_CTL_ADD, evfd, &ev) != 0) {
if (!logged_why_not) {
gpr_log(GPR_DEBUG,
"epoll_ctl with EPOLLEXCLUSIVE failed with error: "
"%d. Not using epollex polling engine.",
errno);
logged_why_not = true;
}
close(fd);
close(evfd);
return false;
}
close(evfd);
close(fd);
return true;
}
#else
bool grpc_is_epollexclusive_available(void) { return false; }
#endif
| [
"bryan.guner@gmail.com"
] | bryan.guner@gmail.com |
cf2d002e92dd97a3cc4d9885c6f6bec5ab2aa660 | 38bc9a6e2888dbd41cc97624d75e375c44263ca7 | /Source/UnrealPrime/Public/UPPlayerController.h | 679e0380bebe06e4ad64855d3f4f91870a84f31f | [] | no_license | UTAwesome/UPrime | 2828315140552a0a9981888625417f1bcfa96097 | 72c95f062681479b304b9034d8380081e1489ee6 | refs/heads/master | 2021-01-10T15:23:40.758132 | 2016-02-20T07:23:55 | 2016-02-20T07:23:55 | 51,488,649 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | h | // (c) 2016 Evan 'Wail' Whiting
#pragma once
#include "PrimeMutator.h"
#include "UTPlayerController.h"
#include "UPPlayerController.generated.h"
UCLASS(config=Game)
class AUPPlayerController : public AUTPlayerController
{
GENERATED_UCLASS_BODY()
/** override to disable spectators being unable to chat */
virtual void ServerSay_Implementation(const FString& Message, bool bTeamMessage) override;
/** override suicide prevention behavior */
void ServerSuicide_Implementation() override;
}; | [
"wailofsuicide@gmail.com"
] | wailofsuicide@gmail.com |
ff39c1952e5325402478c3afba5d66ee7d3a5c64 | ce42c5ba6400e9ae743a45e20c821de06a56826f | /thrust/system/cuda/detail/bulk/detail/cuda_launcher/runtime_introspection.inl | faab2c0db5af27283906f870664af28eaac82cf0 | [
"Apache-2.0",
"BSL-1.0"
] | permissive | gwli/thrust | e6dde077a4b5840c78b910d5200af7529fc225d7 | 0b2888e8f82faf3f8a430c8759c5d838591209dd | refs/heads/master | 2021-01-16T23:02:32.380479 | 2014-07-17T00:58:24 | 2014-07-17T00:58:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,309 | inl | /*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrust/system/cuda/detail/bulk/detail/config.hpp>
#include <thrust/system/cuda/detail/bulk/detail/cuda_launcher/runtime_introspection.hpp>
#include <thrust/system/cuda/detail/bulk/detail/throw_on_error.hpp>
#include <thrust/system/cuda/detail/guarded_cuda_runtime_api.h>
#include <thrust/detail/util/blocking.h>
#include <thrust/detail/minmax.h>
#include <thrust/system_error.h>
#include <thrust/system/cuda/error.h>
BULK_NAMESPACE_PREFIX
namespace bulk
{
namespace detail
{
__host__ __device__
inline device_properties_t device_properties(int device_id)
{
device_properties_t prop = {};
cudaError_t error = cudaErrorNoDevice;
#if __BULK_HAS_CUDART__
error = cudaDeviceGetAttribute(&prop.major, cudaDevAttrComputeCapabilityMajor, device_id);
error = cudaDeviceGetAttribute(&prop.maxGridSize[0], cudaDevAttrMaxGridDimX, device_id);
error = cudaDeviceGetAttribute(&prop.maxGridSize[1], cudaDevAttrMaxGridDimY, device_id);
error = cudaDeviceGetAttribute(&prop.maxGridSize[2], cudaDevAttrMaxGridDimZ, device_id);
error = cudaDeviceGetAttribute(&prop.maxThreadsPerBlock, cudaDevAttrMaxThreadsPerBlock, device_id);
error = cudaDeviceGetAttribute(&prop.maxThreadsPerMultiProcessor, cudaDevAttrMaxThreadsPerMultiProcessor, device_id);
error = cudaDeviceGetAttribute(&prop.minor, cudaDevAttrComputeCapabilityMinor, device_id);
error = cudaDeviceGetAttribute(&prop.multiProcessorCount, cudaDevAttrMultiProcessorCount, device_id);
error = cudaDeviceGetAttribute(&prop.regsPerBlock, cudaDevAttrMaxRegistersPerBlock, device_id);
int temp;
error = cudaDeviceGetAttribute(&temp, cudaDevAttrMaxSharedMemoryPerBlock, device_id);
prop.sharedMemPerBlock = temp;
error = cudaDeviceGetAttribute(&prop.warpSize, cudaDevAttrWarpSize, device_id);
#endif
throw_on_error(error, "cudaDeviceGetProperty in get_device_properties");
return prop;
}
__host__ __device__
inline int current_device()
{
int result = -1;
#if __BULK_HAS_CUDART__
bulk::detail::throw_on_error(cudaGetDevice(&result), "current_device(): after cudaGetDevice");
#endif
if(result < 0)
{
bulk::detail::throw_on_error(cudaErrorNoDevice, "current_device(): after cudaGetDevice");
}
return result;
}
__host__ __device__
inline device_properties_t device_properties()
{
return device_properties(current_device());
}
template <typename KernelFunction>
__host__ __device__
inline function_attributes_t function_attributes(KernelFunction kernel)
{
#if __BULK_HAS_CUDART__
typedef void (*fun_ptr_type)();
fun_ptr_type fun_ptr = reinterpret_cast<fun_ptr_type>(kernel);
cudaFuncAttributes attributes;
bulk::detail::throw_on_error(cudaFuncGetAttributes(&attributes, fun_ptr), "function_attributes(): after cudaFuncGetAttributes");
// be careful about how this is initialized!
function_attributes_t result = {
attributes.constSizeBytes,
attributes.localSizeBytes,
attributes.maxThreadsPerBlock,
attributes.numRegs,
attributes.ptxVersion,
attributes.sharedSizeBytes
};
return result;
#else
return function_attributes_t();
#endif // __CUDACC__
}
__host__ __device__
inline size_t compute_capability(const device_properties_t &properties)
{
return 10 * properties.major + properties.minor;
}
__host__ __device__
inline size_t compute_capability()
{
return compute_capability(device_properties());
}
} // end namespace detail
} // end namespace bulk
BULK_NAMESPACE_SUFFIX
| [
"jaredhoberock@gmail.com"
] | jaredhoberock@gmail.com |
aff155dd694048e5a23a1ef60d576ceab2f9efcc | 4ce81f0f5763b353beb6e8b3191085dc637e211d | /lib-pca9685dmx/src/pca9685dmxledparams.cpp | a7adf8775247c898fb977e0398ce19293633e549 | [] | no_license | g-zi/rpidmx512 | befaf92d65c8f9eaf76e47e3e01cfd6a84ce59d1 | dc1b549c9bc056c8ebfcb9580c7849d4e5a22b1c | refs/heads/master | 2021-04-27T18:51:36.536196 | 2018-02-18T16:01:08 | 2018-02-18T16:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,536 | cpp | /**
* @file pca9685dmxledparams.cpp
*
*/
/* Copyright (C) 2018 by Arjan van Vught mailto:info@raspberrypi-dmx.nl
*
* 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 <stdint.h>
#ifndef NDEBUG
#include <stdio.h>
#endif
#include <assert.h>
#ifndef ALIGNED
#define ALIGNED __attribute__((aligned(4)))
#endif
#include "pca9685dmxledparams.h"
#include "pca9685dmxled.h"
#include "readconfigfile.h"
#include "sscan.h"
#define SET_PWM_FREQUENCY_MASK 1<<0
#define SET_OUTPUT_INVERT_MASK 1<<1
#define SET_OUTPUT_DRIVER_MASK 1<<2
#define I2C_SLAVE_ADDRESS_MASK 1<<3
static const char PARAMS_FILE_NAME[] ALIGNED = "pwmled.txt";
static const char PARAMS_I2C_SLAVE_ADDRESS[] ALIGNED = "i2c_slave_address";
static const char PARAMS_PWM_FREQUENCY[] ALIGNED = "pwm_frequency";
static const char PARAMS_OUTPUT_INVERT[] ALIGNED = "output_invert";
static const char PARAMS_OUTPUT_DRIVER[] ALIGNED = "output_driver";
PCA9685DmxLedParams::PCA9685DmxLedParams(void) :
PCA9685DmxParams(PARAMS_FILE_NAME),
m_bSetList(0),
m_nI2cAddress(PCA9685_I2C_ADDRESS_DEFAULT),
m_nPwmFrequency(PWMLED_DEFAULT_FREQUENCY),
m_bOutputInvert(false), // Output logic state not inverted. Value to use when external driver used.
m_bOutputDriver(true) // The 16 LEDn outputs are configured with a totem pole structure.
{
ReadConfigFile configfile(PCA9685DmxLedParams::staticCallbackFunction, this);
configfile.Read(PARAMS_FILE_NAME);
}
PCA9685DmxLedParams::~PCA9685DmxLedParams(void) {
}
void PCA9685DmxLedParams::Set(PCA9685DmxLed* pDmxLed) {
assert(pDmxLed != 0);
bool isSet;
if ((!GetSetList()) && (m_bSetList == 0)) {
return;
}
if(IsMaskSet(I2C_SLAVE_ADDRESS_MASK)) {
pDmxLed->SetI2cAddress(m_nI2cAddress);
}
if(IsMaskSet(SET_PWM_FREQUENCY_MASK)) {
pDmxLed->SetPwmfrequency(m_nPwmFrequency);
}
if(IsMaskSet(SET_OUTPUT_INVERT_MASK)) {
pDmxLed->SetInvert(m_bOutputInvert);
}
if(IsMaskSet(SET_OUTPUT_DRIVER_MASK)) {
pDmxLed->SetOutDriver(m_bOutputDriver);
}
const uint16_t DmxStartAddress = GetDmxStartAddress(isSet);
if (isSet) {
pDmxLed->SetDmxStartAddress(DmxStartAddress);
}
const uint8_t BoardInstances = GetBoardInstances(isSet);
if (isSet) {
pDmxLed->SetBoardInstances(BoardInstances);
}
const char *p = GetDmxSlotInfoRaw(isSet);
if (isSet) {
pDmxLed->SetSlotInfoRaw(p);
}
// Footprint overwrites board instances!
const uint16_t DmxFootprint = GetDmxFootprint(isSet);
if (isSet) {
pDmxLed->SetDmxFootprint(DmxFootprint);
}
}
void PCA9685DmxLedParams::Dump(void) {
#ifndef NDEBUG
if (m_bSetList == 0) {
return;
}
printf("PWM led params \'%s\':\n", PARAMS_FILE_NAME);
if(IsMaskSet(I2C_SLAVE_ADDRESS_MASK)) {
printf("%s=0x%2x\n", PARAMS_I2C_SLAVE_ADDRESS, m_nI2cAddress);
}
if(IsMaskSet(SET_PWM_FREQUENCY_MASK)) {
printf("%s=%d Hz\n", PARAMS_PWM_FREQUENCY, m_nPwmFrequency);
}
if(IsMaskSet(SET_OUTPUT_INVERT_MASK)) {
printf("%s=%d [Output logic state %sinverted]\n", PARAMS_OUTPUT_INVERT, (int) m_bOutputInvert, m_bOutputInvert ? "" : "not ");
}
if(IsMaskSet(SET_OUTPUT_DRIVER_MASK)) {
printf("%s=%d [The 16 LEDn outputs are configured with %s structure]\n", PARAMS_OUTPUT_DRIVER, (int) m_bOutputDriver, m_bOutputDriver ? "a totem pole" : "an open-drain");
}
PCA9685DmxParams::Dump();
#endif
}
bool PCA9685DmxLedParams::IsMaskSet(uint16_t nMask) const {
return (m_bSetList & nMask) == nMask;
}
void PCA9685DmxLedParams::staticCallbackFunction(void* p, const char* s) {
assert(p != 0);
assert(s != 0);
((PCA9685DmxLedParams *) p)->callbackFunction(s);
}
void PCA9685DmxLedParams::callbackFunction(const char* pLine) {
assert(pLine != 0);
uint8_t value8;
uint16_t value16;
if (Sscan::I2cAddress(pLine, PARAMS_I2C_SLAVE_ADDRESS, &value8) == SSCAN_OK) {
if ((value8 >= PCA9685_I2C_ADDRESS_DEFAULT) && (value8 != PCA9685_I2C_ADDRESS_FIXED)) {
m_nI2cAddress = value8;
m_bSetList |= I2C_SLAVE_ADDRESS_MASK;
}
return;
}
if (Sscan::Uint16(pLine, PARAMS_PWM_FREQUENCY, &value16) == SSCAN_OK) {
if ((value16 >= PCA9685_FREQUENCY_MIN) && (value16 <= PCA9685_FREQUENCY_MAX)) {
m_nPwmFrequency = value16;
m_bSetList |= SET_PWM_FREQUENCY_MASK;
}
return;
}
if (Sscan::Uint8(pLine, PARAMS_OUTPUT_INVERT, &value8) == SSCAN_OK) {
if (value8 != 0) {
m_bOutputInvert = true;
m_bSetList |= SET_OUTPUT_INVERT_MASK;
}
return;
}
if (Sscan::Uint8(pLine, PARAMS_OUTPUT_DRIVER, &value8) == SSCAN_OK) {
if (value8 == 0) {
m_bOutputDriver = false;
m_bSetList |= SET_OUTPUT_DRIVER_MASK;
}
return;
}
}
| [
"Arjan.van.Vught@gmail.com"
] | Arjan.van.Vught@gmail.com |
0e16e67f8850af1c540324a5a946525b7e1dc045 | 274324d00d740adb40b3dedf9de4d0f361b27ad3 | /shaders/lighting-src/rim.cpp | e969443fe404e58fc465252e871288b5ab3dd287 | [] | no_license | MAPSWorks/osgSample | 9bc180d25bee124c04c22c7c0b7081faa2125716 | 3fba6436bd405623c677025d2734f4905b3ace64 | refs/heads/master | 2020-05-22T00:42:50.042959 | 2017-07-29T18:33:44 | 2017-07-29T18:33:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,970 | cpp | //
// Example of GLSL rim shader.
//
// Author: Alex V. Boreskoff <alexboreskoff@mtu-net.ru>, <steps3d@narod.ru>
//
#include "libExt.h"
#ifdef MACOSX
#include <GLUT/glut.h>
#else
#include <glut.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "libTexture.h"
#include "Vector3D.h"
#include "Vector2D.h"
#include "Vector4D.h"
#include "Data.h"
#include "GlslProgram.h"
Vector3D eye ( 7, 5, 7 ); // camera position
Vector3D light ( 5, 0, 4 ); // light position
float angle = 0;
Vector3D rot ( 0, 0, 0 );
int mouseOldX = 0;
int mouseOldY = 0;
unsigned decalMap;
GlslProgram program;
/////////////////////////////////////////////////////////////////////////////////
void init ()
{
glClearColor ( 0.5, 0.5, 0.5, 1.0 );
glEnable ( GL_DEPTH_TEST );
glDepthFunc ( GL_LEQUAL );
glHint ( GL_POLYGON_SMOOTH_HINT, GL_NICEST );
glHint ( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
}
void display ()
{
glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// draw the light
program.unbind ();
glMatrixMode ( GL_MODELVIEW );
glPushMatrix ();
glTranslatef ( light.x, light.y, light.z );
glColor4f ( 1, 1, 1, 1 );
glutSolidSphere ( 0.1f, 15, 15 );
glPopMatrix ();
glMatrixMode ( GL_MODELVIEW );
glPushMatrix ();
glRotatef ( rot.x, 1, 0, 0 );
glRotatef ( rot.y, 0, 1, 0 );
glRotatef ( rot.z, 0, 0, 1 );
glBindTexture ( GL_TEXTURE_2D, decalMap );
program.bind ();
glutSolidTeapot ( 2.5 );
program.unbind ();
glPopMatrix ();
glutSwapBuffers ();
}
void reshape ( int w, int h )
{
glViewport ( 0, 0, (GLsizei)w, (GLsizei)h );
glMatrixMode ( GL_PROJECTION );
// factor all camera ops into projection matrix
glLoadIdentity ();
gluPerspective ( 60.0, (GLfloat)w/(GLfloat)h, 1.0, 60.0 );
gluLookAt ( eye.x, eye.y, eye.z, // eye
0, 0, 0, // center
0.0, 0.0, 1.0 ); // up
glMatrixMode ( GL_MODELVIEW );
glLoadIdentity ();
}
void motion ( int x, int y )
{
rot.y -= ((mouseOldY - y) * 180.0f) / 200.0f;
rot.z -= ((mouseOldX - x) * 180.0f) / 200.0f;
rot.x = 0;
if ( rot.z > 360 )
rot.z -= 360;
if ( rot.z < -360 )
rot.z += 360;
if ( rot.y > 360 )
rot.y -= 360;
if ( rot.y < -360 )
rot.y += 360;
mouseOldX = x;
mouseOldY = y;
glutPostRedisplay ();
}
void mouse ( int button, int state, int x, int y )
{
if ( state == GLUT_DOWN )
{
mouseOldX = x;
mouseOldY = y;
}
}
void key ( unsigned char key, int x, int y )
{
if ( key == 27 || key == 'q' || key == 'Q' ) // quit requested
exit ( 0 );
}
void animate ()
{
angle = 0.004f * glutGet ( GLUT_ELAPSED_TIME );
light.x = 2*cos ( angle );
light.y = 3*sin ( 1.4 * angle );
light.z = 3 + 0.5 * sin ( angle / 3 );
program.bind ();
program.setUniformVector ( "eyePos", Vector4D ( eye, 1 ) );
program.setUniformVector ( "lightPos", Vector4D ( light, 1 ) );
program.unbind ();
glutPostRedisplay ();
}
int main ( int argc, char * argv [] )
{
// initialize glut
glutInit ( &argc, argv );
glutInitDisplayMode ( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
glutInitWindowSize ( 500, 500 );
// create window
glutCreateWindow ( "Rim lighting" );
// register handlers
glutDisplayFunc ( display );
glutReshapeFunc ( reshape );
glutKeyboardFunc ( key );
glutMouseFunc ( mouse );
glutMotionFunc ( motion );
glutIdleFunc ( animate );
init ();
initExtensions ();
assertExtensionsSupported ( "GL_ARB_shading_language_100 GL_ARB_shader_objects" );
if ( !program.loadShaders ( "rim.vsh", "rim.fsh" ) )
{
printf ( "Error loading shaders:\n%s\n", program.getLog ().c_str () );
return 3;
}
decalMap = createTexture2D ( true, "../../Textures/oak.bmp" );
program.bind ();
program.setTexture ( "decalMap", 0 );
program.unbind ();
glutMainLoop ();
return 0;
}
| [
"achaplygin99@gmail.com"
] | achaplygin99@gmail.com |
e5a1738d150e3e7edc17cddd8d6e79b8ba5e3bb3 | c07dcb553e34ad2a8fe34177f52a7631c0439a5a | /Source/ToyRacing/Public/Trap.h | eba0e72378007fa21071d305ba2177b75916a1e7 | [] | no_license | eduamadeo/toyRacing | 5a6dafdca35683f0ad69d3066fb3883e3b1d0f09 | d3406b9210fcd8dc3a4f2b37045975d7fbba2121 | refs/heads/main | 2023-08-11T12:23:03.657370 | 2021-10-12T20:35:42 | 2021-10-12T20:35:42 | 322,689,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,503 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Trap.generated.h"
UCLASS()
class TOYRACING_API ATrap : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ATrap();
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
class UCapsuleComponent* CapsuleComponent;
// Static Mesh used to provide a visual representation of the object.
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
class UStaticMeshComponent* StaticMesh;
// Particle used when the projectile impacts against another object and explodes.
UPROPERTY(EditAnywhere, Category = "Effects")
class UParticleSystemComponent* TrapEffect;
/** Audio component for the hurricane sound */
UPROPERTY(Category = Display, VisibleDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
UAudioComponent* HurricaneSoundComponent;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION(Category = "Projectile")
void OnProjectileOverlap(class UPrimitiveComponent* OverlappingComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
UFUNCTION(Server, Reliable)
void SetTrapServer(class AActor* Actor);
};
| [
"eduamadeo@gmail.com"
] | eduamadeo@gmail.com |
2cacc10c6cb4fcfbf41b7f9bc3eb0dcd969bc19d | 9f6d0c9e9f0877e0cc954f61e2245c88839918f9 | /v8/gen/64/torque-generated/src/objects/js-segment-iterator-tq-csa.h | d95374ab058bfc30ec3634b60ef5ea725148c85d | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | fibjs/fibjs_vender | c2f4fd35b7ed9e9ea06680d75453b3ee81a25d0d | 6aa2431f65e17f9a51b60f12c14a36a8464fad5d | refs/heads/dev | 2023-08-03T18:39:02.369823 | 2023-07-27T14:12:00 | 2023-07-27T14:12:00 | 37,327,960 | 7 | 24 | null | 2022-05-18T15:08:24 | 2015-06-12T14:56:51 | C++ | UTF-8 | C++ | false | false | 2,302 | h | #ifndef V8_GEN_TORQUE_GENERATED_SRC_OBJECTS_JS_SEGMENT_ITERATOR_TQ_CSA_H_
#define V8_GEN_TORQUE_GENERATED_SRC_OBJECTS_JS_SEGMENT_ITERATOR_TQ_CSA_H_
#include "src/builtins/torque-csa-header-includes.h"
namespace v8 {
namespace internal {
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-segment-iterator.tq?l=11&c=1
TNode<JSSegmentIterator> Cast_JSSegmentIterator_0(compiler::CodeAssemblerState* state_, TNode<HeapObject> p_obj, compiler::CodeAssemblerLabel* label_CastError);
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-segment-iterator.tq?l=12&c=3
TNode<Foreign> LoadJSSegmentIteratorIcuBreakIterator_0(compiler::CodeAssemblerState* state_, TNode<JSSegmentIterator> p_o);
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-segment-iterator.tq?l=12&c=3
void StoreJSSegmentIteratorIcuBreakIterator_0(compiler::CodeAssemblerState* state_, TNode<JSSegmentIterator> p_o, TNode<Foreign> p_v);
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-segment-iterator.tq?l=13&c=3
TNode<Foreign> LoadJSSegmentIteratorUnicodeString_0(compiler::CodeAssemblerState* state_, TNode<JSSegmentIterator> p_o);
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-segment-iterator.tq?l=13&c=3
void StoreJSSegmentIteratorUnicodeString_0(compiler::CodeAssemblerState* state_, TNode<JSSegmentIterator> p_o, TNode<Foreign> p_v);
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-segment-iterator.tq?l=14&c=3
TNode<Smi> LoadJSSegmentIteratorFlags_0(compiler::CodeAssemblerState* state_, TNode<JSSegmentIterator> p_o);
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-segment-iterator.tq?l=14&c=3
void StoreJSSegmentIteratorFlags_0(compiler::CodeAssemblerState* state_, TNode<JSSegmentIterator> p_o, TNode<Smi> p_v);
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-segment-iterator.tq?l=11&c=1
TNode<JSSegmentIterator> DownCastForTorqueClass_JSSegmentIterator_0(compiler::CodeAssemblerState* state_, TNode<HeapObject> p_o, compiler::CodeAssemblerLabel* label_CastError);
} // namespace internal
} // namespace v8
#endif // V8_GEN_TORQUE_GENERATED_SRC_OBJECTS_JS_SEGMENT_ITERATOR_TQ_CSA_H_
| [
"lion@9465.net"
] | lion@9465.net |
92d6a6600502cdcd6bf6c7d5128916f77dd4a124 | 789dc9c0fd40be04a2c09003910859869fd3f810 | /Userland/Tests/LibC/accuracy-strtod.cpp | 881d7927949385f83fee0c85476e963445e8bbd5 | [
"BSD-2-Clause"
] | permissive | sanjaysanjel019/serenity | 198256864949b322f0c10ecfd33ab33450f5787b | 64ba289cfbdc5f205d5a54b8c9d28da7040ab054 | refs/heads/master | 2022-11-28T10:31:08.777209 | 2020-08-02T18:46:41 | 2020-08-02T19:11:28 | 284,650,567 | 1 | 0 | BSD-2-Clause | 2020-08-03T08:53:17 | 2020-08-03T08:53:16 | null | UTF-8 | C++ | false | false | 30,036 | cpp | /*
* Copyright (c) 2020, Ben Wiederhake <BenWiederhake.GitHub@gmx.de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
typedef char assert_size_t_is_int[sizeof(size_t) == 4 ? 1 : -1];
static const char* TEXT_ERROR = "\x1b[01;35m";
static const char* TEXT_WRONG = "\x1b[01;31m";
static const char* TEXT_OFBY1 = "\x1b[01;97m";
static const char* TEXT_RESET = "\x1b[0m";
static const long long LENIENCY = 8;
struct Testcase {
const char* test_name;
int should_consume;
const char* hex;
const char* test_string;
};
static Testcase TESTCASES[] = {
// What I came up with on my own:
{ "BW00", 0, "0000000000000000", ".." },
{ "BW01", 2, "3ff0000000000000", "1..0" },
{ "BW02", 1, "3ff0000000000000", "1" },
{ "BW03", 2, "0000000000000000", ".0" },
{ "BW04", 2, "0000000000000000", "0." },
{ "BW05", 2, "0000000000000000", "0.." },
// Second 'e' overwrites first exponent
{ "BW06", 3, "40af400000000000", "4e3e4" },
// Minus sign in exponent is ignored (`atof` only)
{ "BW07", 4, "3f747ae147ae147b", "5e-3" },
// "e" is ignored if followed by only zeros
{ "BW08", 3, "401c000000000000", "7e0" },
// Exponent overflow:
{ "BW09", -1, "0000000000000000", "1e-4294967296" },
// Excessive time use(!):
{ "BW10", -1, "0000000000000000", "1e-999999999" },
// Excessively large exponent (>64 bits):
{ "BW10", -1, "0000000000000000", "1e-9999999999999999999999" },
// Bugs I nearly introduced
{ "BWN01", 2, "3ff0000000000000", "1.-2" },
{ "BWN02", 2, "3ff0000000000000", "1. 2" },
{ "BWN03", 0, "0000000000000000", "++2" },
{ "BWN04", 1, "0000000000000000", "0b101" },
{ "BWN05", 3, "0000000000000000", " 0b101" },
{ "BWN06", 1, "0000000000000000", "0o123" },
{ "BWN07", 1, "0000000000000000", "0y2" },
{ "BWN08", 1, "3ff0000000000000", "1e" },
{ "BWN09", 1, "3ff0000000000000", "1e-" },
{ "BWN10", 6, "4034000000000000", "2e0001" },
{ "BWN11", 6, "41ddcd6500000000", "2e0009" },
{ "BWN12", 1, "0000000000000000", "0d1" },
{ "BWN13", -1, "7ff0000000000000", "184467440737095516151234567890e2147483639" },
{ "BWN14", -1, "0000000000000000", ".1234567890e-2147483639" },
{ "BWN15", -1, "8000000000000000", "-1e-9999" },
{ "BWN16", -1, "c3389e56ee5e7a58", "-6929495644600919.5" },
{ "BWN17", -1, "c3389e56ee5e7a57", "-6929495644600919" },
{ "BWN18", -1, "630a2b939cbca17f", "12345678901234567890e150" },
{ "BWN19", -1, "24c186a8a3f159df", "12345678901234567890e-150" },
// From the Serenity GitHub tracker:
// https://github.com/SerenityOS/serenity/issues/1979
{ "SR1", -1, "4014000000000001", "5.000000000000001" },
{ "SR2", -1, "4014000000000000", "5.0000000000000001" },
{ "SR3", -1, "3ff0000000000000", "1.0000000000000000000000000000001" },
{ "SR4", -1, "3ff0000000000000", "1.00000000000000000000000000000001" },
{ "SR5", -1, "3ff1f9add37c1216", "1.12345678912345678912345678912345" },
{ "SR6", -1, "3ff1f9add37c1216", "1.123456789123456789123456789123456789123456789" },
// Inspired from Abraham Hrvoje's "negativeFormattingTests":
// https://github.com/ahrvoje/numerics/blob/master/strtod/strtod_tests.toml
// Note that my interpretation is slightly stricter than what Abraham Hrvoje wrote.
{ "AHN01", 3, "7ff0000000000000", "inf1" },
{ "AHN02", 3, "7ff0000000000000", "inf+" },
{ "AHN03", 0, "0000000000000000", ".E" },
{ "AHN04", 3, "3ff0000000000000", "1.0e" },
{ "AHN05", 4, "400399999999999a", "2.45+e+3" },
{ "AHN06", 2, "4037000000000000", "23e.23" },
{ "AHN07", 0, "0000000000000000", "e9" },
{ "AHN08", 0, "0000000000000000", "+e" },
{ "AHN09", 0, "0000000000000000", "e+" },
{ "AHN10", 0, "0000000000000000", "." },
{ "AHN11", 0, "0000000000000000", "e" },
{ "AHN12", 2, "3fe6666666666666", ".7+" },
{ "AHN13", 3, "3fcae147ae147ae1", ".21e" },
{ "AHN14", 0, "0000000000000000", "+" },
{ "AHN15", 0, "0000000000000000", "" },
{ "AHN16", 3, "7ff0000000000000", "infe" },
{ "AHN17", 3, "7ff8000000000000", "nan(err" },
{ "AHN18", 3, "7ff8000000000000", "nan)" },
{ "AHN19", 3, "7ff8000000000000", "NAN(test_)_)" },
{ "AHN20", 3, "7ff8000000000000", "nan0" },
{ "AHN21", 0, "0000000000000000", "-.e+" },
{ "AHN22", 0, "0000000000000000", "-+12.34" },
// For a better description, see:
// https://github.com/ahrvoje/numerics/blob/master/strtod/strtod_tests.toml
// (Comments removed for ease of format conversion.)
// My machine generates the NaN "fff8000000000000" for 0/0, so I replaced the "correct" result by that.
{ "F0", -1, "348834c13cbf331d", "12.34E-56" },
{ "F1", -1, "c07c800000000000", "-456." },
{ "F2", -1, "405ec00000000000", "+123" },
{ "F3", -1, "7ff8000000000000", "nan" },
{ "F4", -1, "7ff8000000000000", "NaN" },
{ "F5", -1, "7ff8000000000000", "NAN" },
{ "F6", -1, "7ff0000000000000", "inf" },
{ "F7", -1, "7ff0000000000000", "Inf" },
{ "F8", -1, "7ff0000000000000", "INF" },
{ "F9", -1, "fff0000000000000", "-inf" },
{ "F10", -1, "7ff0000000000000", "+inF" },
{ "F11", -1, "7ff0000000000000", "+INF" },
{ "F12", -1, "3ff0000000000000", "1.0" },
{ "F13", -1, "4059000000000000", "1e2" },
{ "F14", -1, "44ada56a4b0835c0", "7.e22" },
{ "F15", -1, "44ada56a4b0835c0", "7.0e22" },
{ "F16", -1, "44ada56a4b0835c0", "7.0e+22" },
{ "F17", -1, "3b8a71fc0e147309", "7.0e-22" },
{ "F18", -1, "c02699999999999a", "-1.13e1" },
{ "F19", -1, "402699999999999a", "+1.13e+1" },
{ "F20", -1, "36e069d1347fd4b5", "23e-45" },
{ "F21", -1, "402a000000000000", ".13e2" },
{ "F22", -1, "beb5cf751db94e6b", "-.13e-5" },
{ "F23", -1, "405ec00000000000", "123" },
{ "F24", -1, "7ff8000000000000", "+nan" },
{ "F25", -1, "7ff0000000000000", "infinity" },
{ "F26", -1, "7ff0000000000000", "Infinity" },
{ "F27", 3, "7ff8000000000000", "nan(type-0)" },
{ "F28", 4, "7ff8000000000000", "+nan(catch_22)" },
{ "F29", -1, "7ff0000000000000", "INFINITY" },
{ "F30", -1, "3ff0000000000000", "0.00000001e+8" },
{ "F31", -1, "fff0000000000000", "-infinity" },
{ "F32", -1, "3705f1a59c73408e", "123.e-45" },
{ "F33", -1, "4085300000000000", "678." },
{ "F34", 4, "fff8000000000000", "-nan()" },
{ "C0", -1, "0000000000000000", "0.000e+00" },
{ "C1", -1, "0000000000000000", "1e-400" },
{ "C2", -1, "0000000000000000", "2.4703282292062326e-324" },
{ "C3", -1, "0000000000000000", "2.4703282292062327e-324" },
{ "C4", -1, "0000000000000001", "2.4703282292062328e-324" },
{ "C5", -1, "0000000000000001", "4.9406564584124654e-324" },
{ "C6", -1, "00000000000007e8", "1e-320" },
{ "C7", -1, "000fffffffffffff", "2.2250738585072009e-308" },
{ "C8", -1, "0010000000000000", "2.2250738585072014e-308" },
{ "C9", -1, "3abef2d0f5da7dd9", "1e-25" },
{ "C10", -1, "3b282db34012b251", "1.0e-23" },
{ "C11", -1, "3ff3c0ca428c59fb", "1.2345678901234567890" },
{ "C12", -1, "402699999999999a", "1.13e1" },
{ "C13", -1, "43e158e460913d00", "1e+19" },
{ "C14", -1, "449017f7df96be18", "1.9e+22" },
{ "C15", -1, "4496deb1154f79ec", "2.7e22" },
{ "C16", -1, "449a420db02bd7d6", "3.1e22" },
{ "C17", -1, "44ada56a4b0835c0", "7e22" },
{ "C18", -1, "7fefffffffffffff", "1.7976931348623158e+308" },
{ "C19", -1, "7ff0000000000000", "1.7976931348623159e+308" },
{ "C20", -1, "7ff0000000000000", "1e+400" },
{ "C21", -1, "000fffffffffffff", "2.225073858507201136057409796709131975934819546351645648023426109724822222021076945516529523908135087914149158913039621106870086438694594645527657207407820621743379988141063267329253552286881372149012981122451451889849057222307285255133155755015914397476397983411801999323962548289017107081850690630666655994938275772572015763062690663332647565300009245888316433037779791869612049497390377829704905051080609940730262937128958950003583799967207254304360284078895771796150945516748243471030702609144621572289880258182545180325707018860872113128079512233426288368622321503775666622503982534335974568884423900265498198385487948292206894721689831099698365846814022854243330660339850886445804001034933970427567186443383770486037861622771738545623065874679014086723327636718749999999999999999999999999999999999999e-308" },
{ "C22", -1, "0010000000000000", "2.22507385850720113605740979670913197593481954635164564802342610972482222202107694551652952390813508791414915891303962110687008643869459464552765720740782062174337998814106326732925355228688137214901298112245145188984905722230728525513315575501591439747639798341180199932396254828901710708185069063066665599493827577257201576306269066333264756530000924588831643303777979186961204949739037782970490505108060994073026293712895895000358379996720725430436028407889577179615094551674824347103070260914462157228988025818254518032570701886087211312807951223342628836862232150377566662250398253433597456888442390026549819838548794829220689472168983109969836584681402285424333066033985088644580400103493397042756718644338377048603786162277173854562306587467901408672332763671875e-308" },
{ "C23", -1, "0010000000000000", "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000222507385850720138309023271733240406421921598046233183055332741688720443481391819585428315901251102056406733973103581100515243416155346010885601238537771882113077799353200233047961014744258363607192156504694250373420837525080665061665815894872049117996859163964850063590877011830487479978088775374994945158045160505091539985658247081864511353793580499211598108576605199243335211435239014879569960959128889160299264151106346631339366347758651302937176204732563178148566435087212282863764204484681140761391147706280168985324411002416144742161856716615054015428508471675290190316132277889672970737312333408698898317506783884692609277397797285865965494109136909540613646756870239867831529068098461721092462539672851562500000000000000001" },
{ "C24", -1, "7ff0000000000000", "179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497792" },
{ "C25", -1, "7fefffffffffffff", "179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791.9999999999999999999999999999999999999999999999999999999999999999999999" },
{ "C26", -1, "0010000000000000", "2.2250738585072012e-308" },
{ "C27", -1, "0006123400000001", "8.44291197326099e-309" },
{ "C28", -1, "42c0000000000000", "35184372088831.999999999999999999999999999999999999" },
{ "C29", -1, "0000000000000000", "2.47032822920623272e-324" },
{ "C30", -1, "3ff199999999999a", "1.100000000000000088817841970012523233890533447265626" },
{ "C31", -1, "3f847ae147ae147b", ".010000000000000000057612911342378542997169" },
{ "C32", -1, "3ffd34fd8378ea83", "1.8254370818746402660437411213933955878019332885742187" },
{ "C33", -1, "43389e56ee5e7a58", "6929495644600919.5" },
{ "C34", -1, "432a9d28ff412a75", "3.7455744005952583e15" },
{ "C35", -1, "000fffffffffffff", "2.2250738585072011e-308" },
{ "C36", -1, "4c20000000000001", "5.0216813883093451685872615018317116712748411717802652598273e58" },
{ "C37", -1, "0000000008000000", "6.631236871469758276785396630275967243399099947355303144249971758736286630139265439618068200788048744105960420552601852889715006376325666595539603330361800519107591783233358492337208057849499360899425128640718856616503093444922854759159988160304439909868291973931426625698663157749836252274523485312442358651207051292453083278116143932569727918709786004497872322193856150225415211997283078496319412124640111777216148110752815101775295719811974338451936095907419622417538473679495148632480391435931767981122396703443803335529756003353209830071832230689201383015598792184172909927924176339315507402234836120730914783168400715462440053817592702766213559042115986763819482654128770595766806872783349146967171293949598850675682115696218943412532098591327667236328125E-316" },
{ "C38", -1, "0000000000010000", "3.237883913302901289588352412501532174863037669423108059901297049552301970670676565786835742587799557860615776559838283435514391084153169252689190564396459577394618038928365305143463955100356696665629202017331344031730044369360205258345803431471660032699580731300954848363975548690010751530018881758184174569652173110473696022749934638425380623369774736560008997404060967498028389191878963968575439222206416981462690113342524002724385941651051293552601421155333430225237291523843322331326138431477823591142408800030775170625915670728657003151953664260769822494937951845801530895238439819708403389937873241463484205608000027270531106827387907791444918534771598750162812548862768493201518991668028251730299953143924168545708663913273994694463908672332763671875E-319" },
{ "C39", -1, "0000800000000100", "6.953355807847677105972805215521891690222119817145950754416205607980030131549636688806115726399441880065386399864028691275539539414652831584795668560082999889551357784961446896042113198284213107935110217162654939802416034676213829409720583759540476786936413816541621287843248433202369209916612249676005573022703244799714622116542188837770376022371172079559125853382801396219552418839469770514904192657627060319372847562301074140442660237844114174497210955449896389180395827191602886654488182452409583981389442783377001505462015745017848754574668342161759496661766020028752888783387074850773192997102997936619876226688096314989645766000479009083731736585750335262099860150896718774401964796827166283225641992040747894382698751809812609536720628966577351093292236328125E-310" },
{ "C40", -1, "0000000000010800", "3.339068557571188581835713701280943911923401916998521771655656997328440314559615318168849149074662609099998113009465566426808170378434065722991659642619467706034884424989741080790766778456332168200464651593995817371782125010668346652995912233993254584461125868481633343674905074271064409763090708017856584019776878812425312008812326260363035474811532236853359905334625575404216060622858633280744301892470300555678734689978476870369853549413277156622170245846166991655321535529623870646888786637528995592800436177901746286272273374471701452991433047257863864601424252024791567368195056077320885329384322332391564645264143400798619665040608077549162173963649264049738362290606875883456826586710961041737908872035803481241600376705491726170293986797332763671875E-319" },
{ "C41", -1, "4e3fa69165a8eea2", "8.533e+68" },
{ "C42", -1, "19dbe0d1c7ea60c9", "4.1006e-184" },
{ "C43", -1, "7fe1cc0a350ca87b", "9.998e+307" },
{ "C44", -1, "0602117ae45cde43", "9.9538452227e-280" },
{ "C45", -1, "0a1fdd9e333badad", "6.47660115e-260" },
{ "C46", -1, "49e033d7eca0adef", "7.4e+47" },
{ "C47", -1, "4a1033d7eca0adef", "5.92e+48" },
{ "C48", -1, "4dd172b70eababa9", "7.35e+66" },
{ "C49", -1, "4b8b2628393e02cd", "8.32116e+55" },
{ "C50", -1, "bfed35696e58a32f", "-0.91276999999999997026378650843980722129344940185546876" },
{ "C51", -1, "c070a3d70a3d70a4", "-266.240000000000009094947017729282379150390624" },
{ "C52", -1, "3c97cb9433617c9c", "8.255628858767918002472043289952338102302250764062685473021474535926245152950286865234374e-17" },
{ "C53", -1, "43405e6cec57761a", "9214843084008499" },
{ "C54", -1, "3fe0000000000002", "0.500000000000000166533453693773481063544750213623046875" },
{ "C55", -1, "42c0000000000002", "3.518437208883201171875e13" },
{ "C56", -1, "404f44abd5aa7ca4", "62.5364939768271845828" },
{ "C57", -1, "3e0bd5cbaef0fd0c", "8.10109172351e-10" },
{ "C58", -1, "3ff8000000000000", "1.50000000000000011102230246251565404236316680908203125" },
{ "C59", -1, "433fffffffffffff", "9007199254740991.4999999999999999999999999999999995" },
{ "C60", -1, "44997a3c7271b021", "30078505129381147446200" },
{ "C61", -1, "4458180d5bad2e3e", "1777820000000000000001" },
{ "C62", -1, "3fe0000000000002", "0.50000000000000016656055874808561867439493653364479541778564453125" },
{ "C63", -1, "3fd92bb352c4623a", "0.3932922657273" },
{ "C64", -1, "0000000000000000", "2.4703282292062327208828439643411068618252990130716238221279284125033775363510437593264991818081799618989828234772285886546332835517796989819938739800539093906315035659515570226392290858392449105184435931802849936536152500319370457678249219365623669863658480757001585769269903706311928279558551332927834338409351978015531246597263579574622766465272827220056374006485499977096599470454020828166226237857393450736339007967761930577506740176324673600968951340535537458516661134223766678604162159680461914467291840300530057530849048765391711386591646239524912623653881879636239373280423891018672348497668235089863388587925628302755995657524455507255189313690836254779186948667994968324049705821028513185451396213837722826145437693412532098591327667236328124999e-324" },
{ "C65", -1, "0000000000000000", "2.4703282292062327208828439643411068618252990130716238221279284125033775363510437593264991818081799618989828234772285886546332835517796989819938739800539093906315035659515570226392290858392449105184435931802849936536152500319370457678249219365623669863658480757001585769269903706311928279558551332927834338409351978015531246597263579574622766465272827220056374006485499977096599470454020828166226237857393450736339007967761930577506740176324673600968951340535537458516661134223766678604162159680461914467291840300530057530849048765391711386591646239524912623653881879636239373280423891018672348497668235089863388587925628302755995657524455507255189313690836254779186948667994968324049705821028513185451396213837722826145437693412532098591327667236328125e-324" },
{ "C66", -1, "0000000000000001", "2.4703282292062327208828439643411068618252990130716238221279284125033775363510437593264991818081799618989828234772285886546332835517796989819938739800539093906315035659515570226392290858392449105184435931802849936536152500319370457678249219365623669863658480757001585769269903706311928279558551332927834338409351978015531246597263579574622766465272827220056374006485499977096599470454020828166226237857393450736339007967761930577506740176324673600968951340535537458516661134223766678604162159680461914467291840300530057530849048765391711386591646239524912623653881879636239373280423891018672348497668235089863388587925628302755995657524455507255189313690836254779186948667994968324049705821028513185451396213837722826145437693412532098591327667236328125001e-324" },
{ "C67", -1, "0000000000000001", "7.4109846876186981626485318930233205854758970392148714663837852375101326090531312779794975454245398856969484704316857659638998506553390969459816219401617281718945106978546710679176872575177347315553307795408549809608457500958111373034747658096871009590975442271004757307809711118935784838675653998783503015228055934046593739791790738723868299395818481660169122019456499931289798411362062484498678713572180352209017023903285791732520220528974020802906854021606612375549983402671300035812486479041385743401875520901590172592547146296175134159774938718574737870961645638908718119841271673056017045493004705269590165763776884908267986972573366521765567941072508764337560846003984904972149117463085539556354188641513168478436313080237596295773983001708984374999e-324" },
{ "C68", -1, "0000000000000002", "7.4109846876186981626485318930233205854758970392148714663837852375101326090531312779794975454245398856969484704316857659638998506553390969459816219401617281718945106978546710679176872575177347315553307795408549809608457500958111373034747658096871009590975442271004757307809711118935784838675653998783503015228055934046593739791790738723868299395818481660169122019456499931289798411362062484498678713572180352209017023903285791732520220528974020802906854021606612375549983402671300035812486479041385743401875520901590172592547146296175134159774938718574737870961645638908718119841271673056017045493004705269590165763776884908267986972573366521765567941072508764337560846003984904972149117463085539556354188641513168478436313080237596295773983001708984375e-324" },
{ "C69", -1, "0000000000000002", "7.4109846876186981626485318930233205854758970392148714663837852375101326090531312779794975454245398856969484704316857659638998506553390969459816219401617281718945106978546710679176872575177347315553307795408549809608457500958111373034747658096871009590975442271004757307809711118935784838675653998783503015228055934046593739791790738723868299395818481660169122019456499931289798411362062484498678713572180352209017023903285791732520220528974020802906854021606612375549983402671300035812486479041385743401875520901590172592547146296175134159774938718574737870961645638908718119841271673056017045493004705269590165763776884908267986972573366521765567941072508764337560846003984904972149117463085539556354188641513168478436313080237596295773983001708984375001e-324" },
{ "C70", -1, "7fe0000000000000", "8.9884656743115805365666807213050294962762414131308158973971342756154045415486693752413698006024096935349884403114202125541629105369684531108613657287705365884742938136589844238179474556051429647415148697857438797685859063890851407391008830874765563025951597582513936655578157348020066364210154316532161708031999e+307" },
{ "C71", -1, "7fe0000000000000", "8.9884656743115805365666807213050294962762414131308158973971342756154045415486693752413698006024096935349884403114202125541629105369684531108613657287705365884742938136589844238179474556051429647415148697857438797685859063890851407391008830874765563025951597582513936655578157348020066364210154316532161708032e+307" },
{ "C72", -1, "7fe0000000000001", "8.9884656743115805365666807213050294962762414131308158973971342756154045415486693752413698006024096935349884403114202125541629105369684531108613657287705365884742938136589844238179474556051429648741514697857438797685859063890851407391008830874765563025951597582513936655578157348020066364210154316532161708032001e+307" },
{ "C73", -1, "3ff0000010000000", "1.00000005960464477550" },
{ "C74", -1, "36c6000000000000", "7.7071415537864938e-45" },
{ "C75", -1, "0000000000000000", "2183167012312112312312.23538020374420446192e-370" },
{ "C76", -1, "0006c9a143590c14", "94393431193180696942841837085033647913224148539854e-358" },
{ "C77", -1, "3ff0000000000000", "99999999999999994487665465554760717039532578546e-47" },
{ "C78", -1, "44b52d02c7e14af6", "10000000000000000000000000000000000000000e-17" },
{ "C79", -1, "0007802665fd9600", "104308485241983990666713401708072175773165034278685682646111762292409330928739751702404658197872319129036519947435319418387839758990478549477777586673075945844895981012024387992135617064532141489278815239849108105951619997829153633535314849999674266169258928940692239684771590065027025835804863585454872499320500023126142553932654370362024104462255244034053203998964360882487378334860197725139151265590832887433736189468858614521708567646743455601905935595381852723723645799866672558576993978025033590728687206296379801363024094048327273913079612469982585674824156000783167963081616214710691759864332339239688734656548790656486646106983450809073750535624894296242072010195710276073042036425579852459556183541199012652571123898996574563824424330960027873516082763671875e-1075" },
{ "C80", -1, "4025cccccccccccd", "10.900000000000000012345678912345678912345" },
// Hexadecimal floats.
// Note that "0x579a" is "0xabcd << 1" with the top bit cut off, just as expected.
{ "Fp1", -1, "7c2579a000000000", "0xab.cdpef" },
// Sneaky floating point :P
{ "Fp2", -1, "43e9400000000000", "0xCAPE" },
};
constexpr size_t NUM_TESTCASES = sizeof(TESTCASES) / sizeof(TESTCASES[0]);
typedef double (*strtod_fn_t)(const char* str, char** endptr);
long long cast_ll(double d)
{
union readable_t {
double as_double;
long long as_ll;
};
typedef char assert_double_8bytes[sizeof(double) == 8 ? 1 : -1];
(void)sizeof(assert_double_8bytes);
typedef char assert_ll_8bytes[sizeof(long long) == 8 ? 1 : -1];
(void)sizeof(assert_ll_8bytes);
typedef char assert_readable_8bytes[sizeof(readable_t) == 8 ? 1 : -1];
(void)sizeof(assert_readable_8bytes);
readable_t readable;
readable.as_double = d;
return readable.as_ll;
}
bool is_strtod_close(strtod_fn_t strtod_fn, const char* test_string, const char* expect_hex, int expect_consume, long long expect_ll)
{
union readable_t {
double as_double;
unsigned char as_bytes[8];
};
typedef char assert_double_8bytes[sizeof(double) == 8 ? 1 : -1];
(void)sizeof(assert_double_8bytes);
typedef char assert_readable_8bytes[sizeof(readable_t) == 8 ? 1 : -1];
(void)sizeof(assert_readable_8bytes);
readable_t readable;
char* endptr = (char*)0x123;
readable.as_double = strtod_fn(test_string, &endptr);
char actual_hex[16 + 1] = { 0 };
for (size_t i = 0; i < 8; ++i) {
// Little endian, need to reverse order.
snprintf(&actual_hex[2 * i], 3, "%02x", readable.as_bytes[8 - 1 - i]);
}
bool actual_consume_possible = false;
int actual_consume;
if (endptr < test_string) {
actual_consume = 999;
} else {
const char* max_endptr = test_string + strlen(test_string);
actual_consume_possible = endptr <= max_endptr;
actual_consume = endptr - test_string;
}
long long actual_ll = cast_ll(readable.as_double);
long long off_by = expect_ll - actual_ll;
bool ofby1_hex = off_by != 0 && -LENIENCY <= off_by && off_by <= LENIENCY;
bool wrong_hex = !ofby1_hex && strcmp(expect_hex, actual_hex) != 0;
bool error_cns = !actual_consume_possible;
bool wrong_cns = !error_cns && (actual_consume != expect_consume);
printf(" %s%s%s(%s%2u%s)",
ofby1_hex ? TEXT_OFBY1 : wrong_hex ? TEXT_WRONG : "",
actual_hex,
(ofby1_hex || wrong_hex) ? TEXT_RESET : "",
error_cns ? TEXT_ERROR : wrong_cns ? TEXT_WRONG : "",
actual_consume,
(error_cns || wrong_cns) ? TEXT_RESET : "");
return !(wrong_hex || error_cns || wrong_cns);
}
long long hex_to_ll(const char* hex)
{
long long result = 0;
for (int i = 0; i < 16; ++i) {
char ch = *(hex + i);
int digit;
if ('0' <= ch && ch <= '9') {
digit = ch - '0';
} else if ('a' <= ch && ch <= 'f') {
digit = ch - 'a' + 10;
} else {
printf("\n!!! Encountered char %02x at %d.\n", ch, i);
assert(false);
}
result <<= 4;
result += digit;
}
return result;
}
int main()
{
if (sizeof(size_t) != 4) {
printf("lolwut?!\n");
return 1;
}
printf("Running %lu testcases...\n", NUM_TESTCASES);
printf("%3s(%-5s): %16s(%2s) %16s(%2s) %16s(%2s) %16s(%2s) – %s\n", "num", "name", "correct", "cs", "builtin", "cs", "old_strtod", "cs", "new_strtod", "cs", "teststring");
int successes = 0;
int fails = 0;
for (size_t i = 0; i < NUM_TESTCASES; i++) {
Testcase& tc = TESTCASES[i];
if (tc.should_consume == -1) {
tc.should_consume = strlen(tc.test_string);
}
printf("%3lu(%-5s):", i, tc.test_name);
printf(" %s(%2d)", tc.hex, tc.should_consume);
long long expect_ll = hex_to_ll(tc.hex);
bool success = false;
success = is_strtod_close(strtod, tc.test_string, tc.hex, tc.should_consume, expect_ll);
printf(" from %s\n", tc.test_string);
if (success) {
successes += 1;
} else {
fails += 1;
}
}
printf("Out of %lu tests, saw %d successes and %d fails.\n", NUM_TESTCASES, successes, fails);
if (fails != 0) {
printf("FAIL\n");
return 1;
}
printf("PASS (with leniency up to %lld ULP from the exact solution.\n", LENIENCY);
return 0;
}
| [
"kling@serenityos.org"
] | kling@serenityos.org |
7f02c21e6c97bf1d1bbaead10d2738e86ff4ac35 | a89de567681b5d6eda7ebbc40915f5df8b699938 | /Source/Test/Private/Abilities.spec.cpp | c48704620873d5f98f454acefec66de3550019d5 | [
"BSD-3-Clause"
] | permissive | vorixo/abilities | f3c23fde5b7e4e5cf5f2ce86212479728ee97e99 | a6c1635cf20d1e819cce7bcaeaef87548c66b39f | refs/heads/master | 2022-12-31T15:27:22.686652 | 2020-10-17T07:26:37 | 2020-10-17T07:26:37 | 304,935,001 | 2 | 0 | BSD-3-Clause | 2020-10-17T17:54:38 | 2020-10-17T17:41:59 | null | UTF-8 | C++ | false | false | 5,736 | cpp | // Copyright 2020 Splash Damage, Ltd. - All Rights Reserved.
#include <CoreMinimal.h>
#include "Helpers/TestHelpers.h"
#include "Helpers/TestAbility.h"
#if WITH_DEV_AUTOMATION_TESTS
/************************************************************************/
/* ABILITY SPEC */
/************************************************************************/
class FAbilityTestSpec_Abilities : public FAbilityTestSpec
{
GENERATE_SPEC(FAbilityTestSpec_Abilities, "Abilities.Ability",
EAutomationTestFlags::ProductFilter |
EAutomationTestFlags::EditorContext |
EAutomationTestFlags::ServerContext
);
UAbilitiesComponent* Component = nullptr;
};
void FAbilityTestSpec_Abilities::Define()
{
Describe("Execution", [this]()
{
BeforeEach([this]()
{
CreateWorld();
Component = AddTestComponent();
Component->EquipAbility<UTestAbility>();
Component->EquipAbility<UTestAbility2>();
});
It("Can be equipped", [this]()
{
TestTrue(TEXT("Is Equipped"), Component->IsEquipped<UTestAbility>());
});
It("Can be unequipped", [this]()
{
Component->UnequipAbility<UTestAbility>();
TestFalse(TEXT("Is Equipped after Unequip"), Component->IsEquipped<UTestAbility>());
});
It("Can equip again", [this]()
{
Component->UnequipAbility<UTestAbility>();
Component->EquipAbility<UTestAbility>();
TestTrue(TEXT("Is Equipped after Reequip"), Component->IsEquipped<UTestAbility>());
});
It("Calls Beginplay", [this]()
{
UTestAbility* Ability = Component->GetEquippedAbility<UTestAbility>();
TestTrue(TEXT("Called BeginPlay"), Ability->bCalledBeginPlay);
});
It("Calls Beginplay on two abilities", [this]()
{
UTestAbility* Ability = Component->GetEquippedAbility<UTestAbility>();
UTestAbility2* Ability2 = Component->GetEquippedAbility<UTestAbility2>();
TestTrue(TEXT("Called first BeginPlay"), Ability->bCalledBeginPlay);
TestTrue(TEXT("Called second BeginPlay"), Ability2->bCalledBeginPlay);
});
It("Instance is created", [this]()
{
TestNotNull(TEXT("Ability Instance after Equip"), Component->GetEquippedAbility<UTestAbility>());
});
It("Instance is destroyed", [this]()
{
Component->UnequipAbility<UTestAbility>();
TestNull(TEXT("Ability Instance after Unequip"), Component->GetEquippedAbility<UTestAbility>());
});
It("Can cast", [this]()
{
UAbility* Ability = Component->GetEquippedAbility<UTestAbility2>();
TestFalse(TEXT("Is Casting before Cast"), Ability->IsCasting());
Component->CastAbility<UTestAbility2>();
TestTrue(TEXT("Is Running after Cast"), Ability->IsCasting());
});
It("Can cancel cast", [this]()
{
UAbility* Ability = Component->GetEquippedAbility<UTestAbility2>();
Component->CastAbility<UTestAbility2>();
TestTrue(TEXT("Is Casting"), Ability->IsCasting());
Ability->Cancel();
TestFalse(TEXT("IsRunning after cancel Cast"), Ability->IsRunning());
TestTrue(TEXT("Ability was Cancelled"), Ability->IsCancelled());
TestFalse(TEXT("Ability Succeeded"), Ability->HasSucceeded());
});
It("Can activate after cast", [this]()
{
UAbility* Ability = Component->GetEquippedAbility<UTestAbility2>();
Component->CastAbility<UTestAbility2>();
TestTrue(TEXT("Is Casting"), Ability->IsCasting());
TestFalse(TEXT("IsActivated"), Ability->IsActivated());
const bool bResult = Ability->Activate();
TestTrue(TEXT("ActivatedReturn"), bResult);
TestTrue(TEXT("IsActivated"), Ability->IsActivated());
});
It("Can activate directly (no cast required)", [this]()
{
UAbility* Ability = Component->GetEquippedAbility<UTestAbility>();
TestFalse(TEXT("Is Running before Activation"), Ability->IsRunning());
Component->CastAbility<UTestAbility>();
TestTrue(TEXT("Is Running after Activation"), Ability->IsRunning());
});
It("Can not activate directly (cast required)", [this]()
{
UAbility* Ability = Component->GetEquippedAbility<UTestAbility2>();
const bool bResult = Ability->Activate();
TestFalse(TEXT("ActivatedReturn"), bResult);
TestFalse(TEXT("IsActivated"), Ability->IsActivated());
});
It("Won't activate if CanActivate is false", [this]()
{
UTestAbility* Ability = Component->GetEquippedAbility<UTestAbility>();
Ability->bEnableActivation = false;
const bool bResult = Component->CastAbility<UTestAbility>();
TestFalse(TEXT("ActivatedReturn"), bResult);
TestFalse(TEXT("IsActivated"), Ability->IsActivated());
Ability->bEnableActivation = true;
});
It("Can deactivate", [this]()
{
Component->CastAbility<UTestAbility>();
UAbility* Ability = Component->GetEquippedAbility<UTestAbility>();
TestTrue(TEXT("Is Running before Deactivation"), Ability->IsRunning());
Component->Cancel<UTestAbility>();
TestFalse(TEXT("Is Running after Deactivation"), Ability->IsRunning());
});
It("Can deactivate from OnActivate", [this]()
{
Component->EquipAbility<UTestAbility3>();
TestTrue(TEXT("Activated"), Component->CastAbility<UTestAbility3>());
UAbility* Ability = Component->GetEquippedAbility<UTestAbility3>();
// TestAbility3 will deactivate on activation
TestFalse(TEXT("Is Activated"), Ability->IsActivated());
});
It("Can deny activation", [this]()
{
UAbility* Ability = Component->GetEquippedAbility<UTestAbility>();
Cast<UTestAbility>(Ability)->bEnableActivation = false;
const bool bStarted = Component->CastAbility<UTestAbility>();
TestFalse(TEXT("Activation result"), bStarted);
TestFalse(TEXT("Is Running"), Ability->IsRunning());
});
AfterEach([this]()
{
RemoveTestComponent(Component);
ShutdownWorld();
});
});
}
#endif //WITH_DEV_AUTOMATION_TESTS
| [
"muit@piperift.com"
] | muit@piperift.com |
92bf7d54e3a7524f1c0c5039a8a1642e41d0d1a2 | da0935a2e8d8c00c5f952a1e3b64a89f302d3430 | /src/data/Abalone.cpp | d476b29dbd941174c11efdf6a2fabe157a356105 | [] | no_license | ekpyron/sparse_kernel_sampling | 6d0167bb31b3898a865e2c02cde6c550cd432217 | 989cf5de452bd9c7896edb43054e4831b0263fe7 | refs/heads/master | 2020-06-20T20:56:23.486219 | 2016-11-28T14:01:36 | 2016-11-28T14:01:36 | 74,822,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,293 | cpp | #include "Abalone.hpp"
#include <fstream>
#include <stdexcept>
#include <iostream>
#include <vector>
#include <eigen3/Eigen/Eigen>
#include <cmath>
#include <utility/Arguments.hpp>
#ifdef USE_MPFR
#include <sstream>
#include <mpreal.h>
#endif
#include <utility/mymath.hpp>
namespace {
template<typename float_type>
struct parse_data;
template<>
struct parse_data<float> {
static void parse(const std::string &line, Eigen::Matrix<float, 8, 1> &data) {
char c;
std::sscanf(line.c_str(), "%c %f %f %f %f %f %f %f %f", &c, &data(0), &data(1), &data(2),
&data(3), &data(4), &data(5), &data(6), &data(7));
}
};
template<>
struct parse_data<double> {
static void parse(const std::string &line, Eigen::Matrix<double, 8, 1> &data) {
char c;
std::sscanf(line.c_str(), "%c %lf %lf %lf %lf %lf %lf %lf %lf", &c, &data(0), &data(1), &data(2),
&data(3), &data(4), &data(5), &data(6), &data(7));
}
};
template<>
struct parse_data<long double> {
static void parse(const std::string &line, Eigen::Matrix<long double, 8, 1> &data) {
char c;
std::sscanf(line.c_str(), "%c %Lf %Lf %Lf %Lf %Lf %Lf %Lf %Lf", &c, &data(0), &data(1), &data(2),
&data(3), &data(4), &data(5), &data(6), &data(7));
}
};
#ifdef USE_MPFR
template<>
struct parse_data<mpfr::mpreal> {
static void parse(const std::string &line, Eigen::Matrix<mpfr::mpreal, 8, 1> &mpreal_data) {
std::istringstream stream(line);
std::string number;
std::getline(stream, number, ' ');
int i = 0;
while (std::getline(stream, number, ' ') && i < 8) {
mpreal_data(i++) = mpfr::mpreal(number);
}
}
};
#endif
}
template<typename float_type>
Abalone<float_type>::Abalone (void) {
bool verbose = Arguments::get().verbose();
if (verbose) std::cout << " Read abalone data..." << std::endl;
std::ifstream f ("abalone.data", std::ios_base::in);
if (!f.is_open ()) throw std::runtime_error("Cannot open abalone dataset.");
std::string line;
std::vector<Eigen::Matrix<float_type, 8, 1>> data;
while (std::getline(f, line).good()) {
char c;
data.emplace_back();
parse_data<float_type>::parse(line, data.back());
}
if (verbose) std::cout << " DONE." << std::endl;
if (verbose) std::cout << " Compute Gram Matrix..." << std::endl;
G_.resize (data.size(), data.size());
float_type max_dist = 0.0f;
for (auto i = 0; i < data.size (); i++) {
for (auto j = i+1; j < data.size(); j++) {
float_type d = (data[i] - data[j]).squaredNorm();
if (d > max_dist) max_dist = d;
}
}
float_type two_sigma_squared = 0.25f * max_dist;
for (auto i = 0; i < data.size(); i++) {
for (auto j = 0; j < data.size(); j++) {
float_type dist = (data[i] - data[j]).squaredNorm();
G_(i,j) = my_exp(-dist / two_sigma_squared);
}
}
if (verbose) std::cout << " DONE." << std::endl;
}
template<typename float_type>
Abalone<float_type>::~Abalone (void) {
}
template class Abalone<float>;
template class Abalone<double>;
template class Abalone<long double>;
#ifdef USE_MPFR
template class Abalone<mpfr::mpreal>;
#endif
| [
"daniel@ekpyron.org"
] | daniel@ekpyron.org |
121e8f6c373dc716316cea0dcfaf894322143640 | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /codeforce/341-360/354/d2.cpp | 70950a90a8e5a0117db628907b557c65c078b52e | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 2,457 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
int H,W;
int sy,sx,gy,gx;
string S;
int mask[1010][1010];
int dist[1010][1010][4];
int rot(int mask,int num) {
while(num--) mask=((mask<<1)&0xe) | ((mask>>3)&1);
return mask;
}
int cango(int m1,int m2,int dir) {
int c=0;
if(((m1 & (1<<dir))==0)) return 0;
dir=(dir+2)%4;
if(((m2 & (1<<dir))==0)) return 0;
return 1;
}
void solve() {
int i,j,k,l,r,x,y; string s;
cin>>H>>W;
FOR(y,H) {
cin>>S;
FOR(x,W) {
if(S[x]=='+' || S[x]=='|' || S[x]=='^' || S[x]=='L'|| S[x]=='R'|| S[x]=='D') mask[y][x] |= 1; // up;
if(S[x]=='+' || S[x]=='|' || S[x]=='v' || S[x]=='L'|| S[x]=='R'|| S[x]=='U') mask[y][x] |= 4; // down;
if(S[x]=='+' || S[x]=='-' || S[x]=='<' || S[x]=='R'|| S[x]=='U'|| S[x]=='D') mask[y][x] |= 8; // left;
if(S[x]=='+' || S[x]=='-' || S[x]=='>' || S[x]=='L'|| S[x]=='U'|| S[x]=='D') mask[y][x] |= 2; // right;
}
}
cin>>sy>>sx;
sy--,sx--;
cin>>gy>>gx;
gy--,gx--;
memset(dist,0x3f,sizeof(dist));
dist[sy][sx][0]=0;
queue<int> Q;
Q.push(sy*1000+sx);
while(Q.size()) {
auto r=Q.front();
int cy=r/1000%1000;
int cx=r%1000;
int cr=r/1000000;
Q.pop();
int cost = dist[cy][cx][cr];
if(dist[cy][cx][(cr+1)%4]>cost+1) {
dist[cy][cx][(cr+1)%4]=cost+1;
Q.push(((cr+1)%4)*1000000+cy*1000+cx);
}
FOR(i,4) {
int dx[4]={0,1,0,-1};
int dy[4]={-1,0,1,0};
int ty=cy+dy[i];
int tx=cx+dx[i];
if(tx<0 || tx>=W || ty<0 || ty>=H) continue;
if(cango(rot(mask[cy][cx],cr),rot(mask[ty][tx],cr),i)) {
if(dist[ty][tx][cr]>cost+1) {
dist[ty][tx][cr] = cost+1;
Q.push(cr*1000000+ty*1000+tx);
}
}
}
}
int mi=5010100;
FOR(i,4) mi=min(mi,dist[gy][gx][i]);
if(mi>5010000) mi=-1;
cout<<mi<<endl;
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
FOR(i,argc-1) s+=argv[i+1],s+='\n';
FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
solve(); return 0;
}
| [
"kmjp@users.noreply.github.com"
] | kmjp@users.noreply.github.com |
49c628835bad0797bd65d4e390533c7ae7b229c6 | 180f6c98c27bcaf403bf671b1145f1cecfd85c6f | /src/su_filepath.h | aa4e29f691fd9395eda9d22aa9f25c6696cede62 | [
"MIT"
] | permissive | sandym/sutils | 2b255ebcfa1ffa8f1f491d855445e0941a39400e | adf94578d48d1066f8b8177fcb20086efc9be962 | refs/heads/master | 2021-05-04T07:44:56.240910 | 2020-01-05T22:35:59 | 2020-01-05T22:35:59 | 70,688,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,452 | h | //
// su_filepath.h
// sutils
//
// Created by Sandy Martel on 12/03/10.
// Copyright (c) 2015年 Sandy Martel. All rights reserved.
//
// Permission to use, copy, modify, distribute, and sell this software for any
// purpose is hereby granted without fee. The sotware is provided "AS-IS" and
// without warranty of any kind, express, implied or otherwise.
//
#ifndef H_SU_FILEPATH
#define H_SU_FILEPATH
#include "su_platform.h"
#include <string_view>
#include <vector>
#include <memory>
#include <ctime>
#include <fstream>
namespace su {
class filepath final
{
public:
filepath() = default;
filepath( const std::string_view &i_path,
const filepath *i_relativeTo = nullptr );
filepath( const filepath &rhs ) = default;
filepath &operator=( const filepath &rhs ) = default;
filepath( filepath &&rhs ) = default;
filepath &operator=( filepath &&rhs ) = default;
// file spec initialization from special file system location
enum class location
{
kHome,
kCurrentWorkingDir,
kApplicationFolder,
kApplicationSupport,
kDesktop,
kDocuments,
kTempFolder, //!< temp folder for the current running instance
kNewTempSpec //!< a new, non-existing file path
};
filepath( location i_folder );
using BookmarkData = std::vector<char>;
filepath( const BookmarkData &i_fileBookmark,
const filepath *i_relativeTo = nullptr );
bool getBookmarkData( BookmarkData &o_data,
const filepath *i_relativeTo = nullptr ) const;
bool empty() const { return _path.empty(); }
void clear() { _path.clear(); }
// info
bool operator==( const filepath &rhs ) const { return _path == rhs._path; }
bool operator!=( const filepath &rhs ) const { return _path != rhs._path; }
bool operator<( const filepath &rhs ) const { return _path < rhs._path; }
bool operator<=( const filepath &rhs ) const { return _path <= rhs._path; }
bool operator>( const filepath &rhs ) const { return _path > rhs._path; }
bool operator>=( const filepath &rhs ) const { return _path >= rhs._path; }
const std::string &path() const { return _path; }
std::string name() const;
std::string stem() const;
std::string extension() const;
void setExtension( const std::string_view &i_ext );
#if UPLATFORM_WIN
std::wstring ospath() const;
#else
std::string ospath() const;
#endif
bool empty() { return _path.empty(); }
bool exists() const;
bool isFolder() const;
bool isFile() const;
std::time_t creation_date() const;
size_t file_size() const;
// iterating folder
bool isFolderEmpty() const;
std::vector<filepath> folderContent() const;
// Navigation
bool up();
bool add( const std::string_view &i_name );
// opening files
std::ifstream &fsopen( std::ifstream &o_fs,
std::ios_base::openmode i_mode = std::ios_base::in |
std::ios_base::binary ) const;
std::ofstream &fsopen( std::ofstream &o_fs,
std::ios_base::openmode i_mode = std::ios_base::out |
std::ios_base::trunc |
std::ios_base::binary ) const;
std::fstream &fsopen( std::fstream &o_fs,
std::ios_base::openmode i_mode = std::ios_base::in |
std::ios_base::out |
std::ios_base::binary ) const;
// file operation
bool unlink() const;
bool mkdir() const;
bool mkpath() const;
bool move( const filepath &i_dest ) const;
bool copy( const filepath &i_dest ) const;
private:
std::string _path;
};
}
inline std::string to_string( const su::filepath &v ) { return v.path(); }
#endif
| [
"sandy@mac.com"
] | sandy@mac.com |
a7ec03cbdbef90fe812421b41987b4128d818760 | 898116eafcfaabd5e0b3d5e9ca635084ef32f51d | /src/ControlPointsHelper.cpp | 8352d00d2090e936b45cdb105277458a3250eec7 | [
"MIT"
] | permissive | rafael-radkowski/setforge | 1b47bbe58db5dc16ae8f1cf230f72cbc9b2902cc | cfa42fc4fc77a3f74c0118a00e047a4c67a7452c | refs/heads/master | 2021-07-14T04:48:21.416907 | 2020-06-09T19:54:10 | 2020-06-09T19:54:10 | 167,021,377 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,835 | cpp | #include "ControlPointsHelper.h"
bool ControlPointsHelper::Read(const std::string path_and_filename, CPType& type, std::vector<glm::vec2>& control_points)
{
if (!FileUtils::Exists(path_and_filename))
{
std::cout << "[ERROR] ControlPointsHelper - file " << path_and_filename << "does not exist.\n" << std::endl;;
return false;
}
int N = 0;
control_points.clear();
std::ifstream in_file(path_and_filename, std::ofstream::in);
if(!in_file.is_open()){
std::cout << "[ERROR] ControlPointsHelper - Cannot open file " << path_and_filename << " for reading." << std::endl;
return false;
}
std::string label;
in_file >> label;
if (label.compare("BBox") == 0) {
type = ControlPointsHelper::BBox;
N = 9; // expect 8 corner pionts and the center
}
int i = 0;
while (in_file)
{
if(i > N-1) break;
std::string line;
in_file >> line;
std::vector<std::string> values = split(line, ',');
if (values.size() >= 2) {
//std::cout << i << ": " << std::stof(values[0]) << " : " <<std::stof(values[1]) << std::endl;
control_points.push_back(glm::vec2(std::stof(values[0]),std::stof(values[1])));
}
else {
std::cout << "[ERROR] ControlPointsHelper - Error while reading line from " << path_and_filename << "." << std::endl;
}
i++;
}
in_file.close();
// -------------------------------------------------------------
// fill up the vector with points if the number does not match the expected number
if (control_points.size() < N) {
for (int i = 0; i < N - control_points.size(); i++) {
control_points.push_back(glm::vec2(-1.0, -1.0));
}
}
return true;
}
bool ControlPointsHelper::Write(const std::string path_and_filename, const CPType type, std::vector<glm::vec2>& control_points)
{
std::ofstream out_file(path_and_filename, std::ofstream::out);
if(!out_file.is_open()){
std::cout << "[ERROR] ControlPointsHelper - Cannot open file " << path_and_filename << " for writing (1)." << std::endl;
return false;
}
switch (type){
case CPType::BBox:
out_file << "BBox\n";
break;
default:
out_file << "Unknown\n";
break;
}
for each (glm::vec2 p in control_points) {
out_file << p.x << "," << p.y << "\n";
}
out_file.close();
return true;
}
bool ControlPointsHelper::Read3D(const std::string path_and_filename, CPType& type, std::vector<glm::vec3>& control_points)
{
if (!FileUtils::Exists(path_and_filename))
{
std::cout << "[ERROR] ControlPointsHelper - file " << path_and_filename << "does not exist.\n" << std::endl;;
return false;
}
int N = 0;
control_points.clear();
std::ifstream in_file(path_and_filename, std::ofstream::in);
if(!in_file.is_open()){
std::cout << "[ERROR] ControlPointsHelper - Cannot open file " << path_and_filename << " for reading." << std::endl;
return false;
}
std::string label;
in_file >> label;
if (label.compare("BBoxLocal") == 0) {
type = ControlPointsHelper::BBoxLocal;
N = 8; // expect 8 corner pionts and the center
}
int i = 0;
while (in_file)
{
if(i > N-1) break;
std::string line;
in_file >> line;
std::vector<std::string> values = split(line, ',');
if (values.size() >= 3) {
//std::cout << i << ": " << std::stof(values[0]) << " : " <<std::stof(values[1]) << std::endl;
control_points.push_back(glm::vec3( std::stof(values[0]), std::stof(values[1]), std::stof(values[2])));
}
else {
std::cout << "[ERROR] ControlPointsHelper - Error while reading line from " << path_and_filename << "." << std::endl;
}
i++;
}
in_file.close();
// -------------------------------------------------------------
// fill up the vector with points if the number does not match the expected number
if (control_points.size() < N) {
for (int i = 0; i < N - control_points.size(); i++) {
control_points.push_back(glm::vec3(-1.0, -1.0, -1.0));
}
}
return true;
}
bool ControlPointsHelper::Write3D(const std::string path_and_filename, const CPType type, std::vector<glm::vec3>& control_points)
{
std::ofstream out_file(path_and_filename, std::ofstream::out);
if(!out_file.is_open()){
std::cout << "[ERROR] ControlPointsHelper - Cannot open file " << path_and_filename << " for writing (2)." << std::endl;
return false;
}
switch (type){
case CPType::BBox:
out_file << "BBox\n";
break;
case CPType::BBoxLocal:
out_file << "BBoxLocal\n";
break;
default:
out_file << "Unknown\n";
break;
}
for each (glm::vec3 p in control_points) {
out_file << p.x << "," << p.y << "," << p.z << "\n";
}
out_file.close();
return true;
}
std::vector<string> ControlPointsHelper::split(std::string str, char delimiter)
{
std::vector<std::string> strvec;
std::stringstream ss(str); // Turn the string into a stream.
std::string tok;
while(getline(ss, tok, delimiter)) {
strvec.push_back(tok);
}
return strvec;
} | [
"rafael@iastate.edu"
] | rafael@iastate.edu |
b335225673699605f05b2d2a78e5f38118fe723f | 91337a37770debaabbdbe6accd332edca0931100 | /algorithms/warmup/Compare the Triplets.cpp | 8a41e27e45c752ff7b08040f4d4fdc55634a553c | [] | no_license | googleknight/HackerRank_Solutions | d350ed98c0c6e7562dcd68a7260574a726d8ed91 | f584db0ff7699faf56d8c3f99c995a68a2deb0e0 | refs/heads/master | 2021-01-20T02:07:28.690211 | 2017-04-30T11:11:34 | 2017-04-30T11:11:34 | 89,375,687 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cpp | //https://www.hackerrank.com/challenges/compare-the-triplets
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main(){
int a0;
int a1;
int a2;
cin >> a0 >> a1 >> a2;
int b0;
int b1;
int b2;
cin >> b0 >> b1 >> b2;
int counta=0,countb=0;
if(a0>b0)counta++;
else if(a0<b0) countb++;
if(a1>b1)counta++;
else if(a1<b1) countb++;
if(a2>b2)counta++;
else if(a2<b2) countb++;
cout<<counta<<" "<<countb<<endl;
return 0;
}
| [
"mathur1995@gmail.com"
] | mathur1995@gmail.com |
725a14dca2583b31af8abcf440b59f1705ee560d | e59f5bdb06c6871df0da1b475978031739e34709 | /PICOFormatWriter/PICOFormatWriter.hpp | 269ec68790be888775726f943f894a779ebd1900 | [] | no_license | xtachx/AutoBub3hs | ed37f720b0bbdd50503ba2fe36ac3788d9c772b8 | 06e7e8be17dbef4fd0c27b6fd17eb8c66c22a923 | refs/heads/master | 2020-05-23T02:05:44.373290 | 2017-07-19T15:49:05 | 2017-07-19T15:49:05 | 186,596,477 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,330 | hpp | #ifndef PICOWRITER_HPP_INCLUDED
#define PICOWRITER_HPP_INCLUDED
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <opencv2/opencv.hpp>
class OutputWriter{
private:
int camera;
int StatusCode;
std::string OutputDir;
std::string run_number;
std::string abubOutFilename;
std::ofstream OutFile;
std::stringstream _StreamOutput;
protected:
public:
struct BubbleData{
std::vector<cv::Rect> RectData;
int StatusCode;
int frame0;
int event;
float dzdt;
float drdt;
BubbleData();
};
/*direct access to the trained data*/
BubbleData BubbleData0;
BubbleData BubbleData1;
BubbleData BubbleData2;
BubbleData BubbleData3;
/*Trainer instance initilized with the camera number*/
OutputWriter(std::string, std::string );
~OutputWriter(void );
/*Compute the mean and std*/
void writeHeader(void );
void stageCameraOutput(std::vector<cv::Rect> , int, int, int);
void stageCameraOutputError(int, int);
void formEachBubbleOutput(int, int&, int );
void writeCameraOutput(void);
};
#endif // ANALYZERUNIT_HPP_INCLUDED
| [
"1912767+xtachx@users.noreply.github.com"
] | 1912767+xtachx@users.noreply.github.com |
de6b754e78869a968bccd738f47a79ed254c0e8d | 674de04236af01eec7f2fa5f5b5b34461d140278 | /Auburn school projects [archive]/X. Fa2012/2710 Sftwr Construction [C++, UML]/Homework/004_Sept18Midnight/folder/hellolanguage.cpp | 499167b0c6ad118f75d0d5f4f905bf159d0f262e | [] | no_license | aewallace/School-Archive | 4e8cee69f9c096d6770ffec3676094610850871d | 3c218342c319c833a72332f610fbeb0bf501cef4 | refs/heads/master | 2021-01-02T08:57:15.363033 | 2015-10-08T19:21:35 | 2015-10-08T19:21:35 | 27,462,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | cpp | #include <iostream>
using namespace std;
int main( )
{
int numberOfLanguages;
cout << "Hello reader.\n"
<< "Welcome to C++.\n";
cout << "How many programming languages have you used? ";
cin >> numberOfLanguages;
if (numberOfLanguages < 1)
cout << "Read the preface. You may prefer\n"
<< "a more elementary book by the same author.\n";
else
cout << "Enjoy the book.\n";
return 0;
}
| [
"aew0024@tigermail.auburn.edu"
] | aew0024@tigermail.auburn.edu |
9457a8e17da155a855dc8a16028d9d165f565a78 | 2a440aea43b5b880fd433f58098ac3bbc66fcfec | /cloudesl/src/model/DeleteEslDeviceResult.cc | b3643cc6a3c9600abde9a481f720bdeac68c834d | [
"Apache-2.0"
] | permissive | longkai1028/aliyun-openapi-cpp-sdk | 30d6553e508c6a38d190557487972553a6ae64d5 | 97286a49ca7ae8754984f6b8abce1a8e6f48117c | refs/heads/master | 2023-04-04T00:13:25.713899 | 2021-04-13T02:28:45 | 2021-04-13T02:28:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,689 | cc | /*
* 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.
*/
#include <alibabacloud/cloudesl/model/DeleteEslDeviceResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Cloudesl;
using namespace AlibabaCloud::Cloudesl::Model;
DeleteEslDeviceResult::DeleteEslDeviceResult() :
ServiceResult()
{}
DeleteEslDeviceResult::DeleteEslDeviceResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DeleteEslDeviceResult::~DeleteEslDeviceResult()
{}
void DeleteEslDeviceResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["ErrorCode"].isNull())
errorCode_ = value["ErrorCode"].asString();
}
std::string DeleteEslDeviceResult::getMessage()const
{
return message_;
}
std::string DeleteEslDeviceResult::getErrorCode()const
{
return errorCode_;
}
bool DeleteEslDeviceResult::getSuccess()const
{
return success_;
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
eda772aa9b341f8500a7d45f09fe86569ebf43e6 | 7923c6b143279bb813b738c5dab2088174f4f2e0 | /sw_7seg/sw_7seg.cpp | a9af2fbb802e84550bc452a1ea1f86d0304e2c91 | [] | no_license | KeitetsuWorks/Arduino_sw_7seg | c582f09db3c8b424a17f92d143054226cd96d81e | 440f1ceee32e2d00e2ccc9a6e2ff8f714e6a6d41 | refs/heads/master | 2021-05-15T02:30:10.738048 | 2017-04-30T13:20:41 | 2017-04-30T13:20:41 | 31,153,541 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,375 | cpp | /*
* File: sw_7seg.cpp
* Author: Keitetsu
*
* Created on 2015/02/22
*/
#include "stdafx.h"
#include "display.h"
/*
* ピンアサイン
*/
#define PIN_SW1 16
/*
* グローバル変数
*/
byte count;
void setup()
{
// 7セグメントLED PIN設定
pinMode(2, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
// SW PIN設定
pinMode(PIN_SW1, INPUT_PULLUP);
count = 0;
display7seg(count);
}
void loop()
{
byte sw1_state;
static byte sw1_state_prev = HIGH;
sw1_state = digitalRead(PIN_SW1);
if(sw1_state == LOW){ // SW1が押下されている場合
delay(10); // 10ミリ秒の待ち時間
sw1_state = digitalRead(PIN_SW1);
if(sw1_state == LOW){ // SW1の状態を再確認(チャタリング対策)
if(sw1_state_prev == HIGH){ // 前回,SW1が押下されていなかった場合
count++; // カウント値をインクリメント
}
sw1_state_prev = LOW; // 今回のSW1の状態を記録
}
else{
sw1_state_prev = HIGH; // 今回のSW1の状態を記録
}
}
else{ // SW1が押下されていない場合
sw1_state_prev = HIGH; // 今回のSW1の状態を記録
}
if(count > 9){ // 表示は10進数1桁
count = 0;
}
display7seg(count);
}
| [
"keitetsu.jp@outlook.com"
] | keitetsu.jp@outlook.com |
6fb0299b78392b80e799b6e2cec4391a1e852c0e | 0b78894cd88fa0062ebda48197261aed65d81730 | /practice07.cpp | e73096af8e99c2b8de44b0e7594f59589b052bc1 | [] | no_license | starplaton/Jaeho | 3849205610839f37213cc962179b9dd464c90a94 | c430d6b80468b39eaceedd2a537ca2318e8c9928 | refs/heads/master | 2020-05-09T09:49:11.171670 | 2019-06-16T23:55:04 | 2019-06-16T23:55:04 | 181,016,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | cpp | #include <iostream>
#include <string>
using namespace std;
template<typename T, typename U>
class MyMap {
public:
MyMap(int size = 1) {
this->size = size;
arrkey = new T[size];
arrvalue = new U[size];
}
~MyMap() {}
U *operator[](T const c) {
for (int i = 0; i < size; i++)
{
if (c == arrkey[i]) return &arrvalue[i];
}
return NULL;
}
bool insert(T key2, U value2 ) {
for (int i = 0; i < size; i++)
{
arrkey[seq] = key2;
arrvalue[seq++] = value2;
return true;
}
return false;
}
private:
T* arrkey;
U* arrvalue;
int seq = 0;
int size = 0;
};
int main() {
MyMap<string, int> M1(10); // 10 is the maximum size of the map
M1.insert("one", 1); M1.insert("two", 2); M1.insert("three", 3);
if (M1["two"]) cout << *M1["two"] << endl;
else cout << "No Match" << endl;
if (M1["ten"]) cout << *M1["ten"] << endl;
else cout << "No Match" << endl;
MyMap<int, string> M2(10);
M2.insert(10, "ten"); M2.insert(20, "twenty"); M2.insert(30, "thirty");
if (M2[30]) cout << *M2[30] << endl;
else cout << "No Match" << endl;
} | [
"noreply@github.com"
] | noreply@github.com |
71952e687549858b8bb1f9ce950a250cfa5e49b8 | b38c30ffd7372684827a932e45915fa02c90af9a | /examples/cpp/main.cpp | 6bf27571311f20f84b85ca18de12eb548fab363f | [
"LLVM-exception",
"Apache-2.0"
] | permissive | maximebedard/wizer | d0f8975625dedf3ac38631d59eb6b32b020a332c | 953e04671727d8a60d5f61d91f6d3ed91da0689d | refs/heads/main | 2023-07-14T13:30:56.393122 | 2021-07-21T18:17:35 | 2021-07-21T18:17:35 | 392,772,843 | 0 | 0 | Apache-2.0 | 2021-08-04T17:20:38 | 2021-08-04T17:20:37 | null | UTF-8 | C++ | false | false | 782 | cpp | #include <stdio.h>
#include <wizer.h>
class Test {
public:
Test() : value(1) {
printf(
"global constructor (should be the first printed line)\n");
}
~Test() {
printf("global destructor (should be the last printed line)\n");
}
int value;
};
bool initialized = false;
int orig_value = 0;
Test t;
static void init_func() {
// This should run after the ctor for `t`, and before `main`.
orig_value = t.value;
t.value = 2;
initialized = true;
}
WIZER_INIT(init_func);
int main(int argc, char** argv) {
if (!initialized) init_func();
printf("argc (should not be baked into snapshot): %d\n", argc);
printf("orig_value (should be 1): %d\n", orig_value);
printf("t.value (should be 2): %d\n", t.value);
}
| [
"chris@cfallin.org"
] | chris@cfallin.org |
07f398eac6926e1a16d0bf39788f5e52f3ed0822 | 20c1eb4f458dd6c7daa0e969d51802068bb1bd93 | /GameSE102/CWindow.cpp | 34441a672920c45df5f8424a40125f65151a80cd | [] | no_license | tranght636/Game_SE102_K21 | 41b19010b3b0a7b74a12139312a610a6469cbe6f | 138ad88d774e5aaa4e58079ed781a27a9ebe0b03 | refs/heads/master | 2022-11-27T18:56:34.219780 | 2020-08-08T02:23:53 | 2020-08-08T02:23:53 | 264,373,899 | 0 | 0 | null | 2020-08-08T02:23:54 | 2020-05-16T06:24:50 | C++ | UTF-8 | C++ | false | false | 7,195 | cpp | #include "CWindow.h"
#include "debug.h"
CWindow * CWindow::__instance = NULL;
/*
Initialize DirectX, create a Direct3D device for rendering within the window, initial Sprite library for
rendering 2D images
- hInst: Application instance handle
- hWnd: Application window handle
*/
void CWindow::Init(HWND hWnd)
{
LPDIRECT3D9 d3d = Direct3DCreate9(D3D_SDK_VERSION);
this->hWnd = hWnd;
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferCount = 1;
RECT r;
GetClientRect(hWnd, &r); // retrieve Window width & height
d3dpp.BackBufferHeight = r.bottom + 1;
d3dpp.BackBufferWidth = r.right + 1;
d3d->CreateDevice(
D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp,
&d3ddv);
if (d3ddv == NULL)
{
OutputDebugString(L"[ERROR] CreateDevice failed\n");
return;
}
d3ddv->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuffer);
// Initialize sprite helper from Direct3DX helper library
D3DXCreateSprite(d3ddv, &spriteHandler);
OutputDebugString(L"[INFO] InitGame done;\n");
}
/*
Utility function to wrap LPD3DXSPRITE::Draw
*/
void CWindow::Draw(float x, float y, LPDIRECT3DTEXTURE9 texture, int left, int top, int right, int bottom, int achorX, int achorY, int alpha)
{
D3DXVECTOR3 p(floor(x-Camera::getInstance()->getX()), y, 0);
RECT r;
r.left = left;
r.top = top;
r.right = right;
r.bottom = bottom;
spriteHandler->Draw(texture, &r, &D3DXVECTOR3(achorX, achorY, 0), &p, D3DCOLOR_ARGB(alpha, 255, 255, 255));
}
int CWindow::IsKeyDown(int KeyCode)
{
return (keyStates[KeyCode] & 0x80) > 0;
}
void CWindow::InitKeyboard(LPKEYEVENTHANDLER handler)
{
HRESULT
hr = DirectInput8Create
(
(HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE),
DIRECTINPUT_VERSION,
IID_IDirectInput8, (VOID**)&di, NULL
);
if (hr != DI_OK)
{
DebugOut(L"[ERROR] DirectInput8Create failed!\n");
return;
}
hr = di->CreateDevice(GUID_SysKeyboard, &didv, NULL);
// TO-DO: put in exception handling
if (hr != DI_OK)
{
DebugOut(L"[ERROR] CreateDevice failed!\n");
return;
}
// Set the data format to "keyboard format" - a predefined data format
//
// A data format specifies which controls on a device we
// are interested in, and how they should be reported.
//
// This tells DirectInput that we will be passing an array
// of 256 bytes to IDirectInputDevice::GetDeviceState.
hr = didv->SetDataFormat(&c_dfDIKeyboard);
hr = didv->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
// IMPORTANT STEP TO USE BUFFERED DEVICE DATA!
//
// DirectInput uses unbuffered I/O (buffer size = 0) by default.
// If you want to read buffered data, you need to set a nonzero
// buffer size.
//
// Set the buffer size to DINPUT_BUFFERSIZE (defined above) elements.
//
// The buffer size is a DWORD property associated with the device.
DIPROPDWORD dipdw;
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = KEYBOARD_BUFFER_SIZE; // Arbitary buffer size
hr = didv->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);
hr = didv->Acquire();
if (hr != DI_OK)
{
DebugOut(L"[ERROR] DINPUT8::Acquire failed!\n");
return;
}
this->keyHandler = handler;
DebugOut(L"[INFO] Keyboard has been initialized successfully\n");
}
void CWindow::ProcessKeyboard()
{
HRESULT hr;
// Collect all key states first
hr = didv->GetDeviceState(sizeof(keyStates), keyStates);
if (FAILED(hr))
{
// If the keyboard lost focus or was not acquired then try to get control back.
if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
{
HRESULT h = didv->Acquire();
if (h == DI_OK)
{
DebugOut(L"[INFO] Keyboard re-acquired!\n");
}
else return;
}
else
{
//DebugOut(L"[ERROR] DINPUT::GetDeviceState failed. Error: %d\n", hr);
return;
}
}
keyHandler->KeyState((BYTE *)&keyStates);
// Collect all buffered events
DWORD dwElements = KEYBOARD_BUFFER_SIZE;
hr = didv->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), keyEvents, &dwElements, 0);
if (FAILED(hr))
{
//DebugOut(L"[ERROR] DINPUT::GetDeviceData failed. Error: %d\n", hr);
return;
}
// Scan through all buffered events, check if the key is pressed or released
for (DWORD i = 0; i < dwElements; i++)
{
int KeyCode = keyEvents[i].dwOfs;
int KeyState = keyEvents[i].dwData;
if ((KeyState & 0x80) > 0)
keyHandler->OnKeyDown(KeyCode);
else
keyHandler->OnKeyUp(KeyCode);
}
}
CWindow::~CWindow()
{
if (spriteHandler != NULL) spriteHandler->Release();
if (backBuffer != NULL) backBuffer->Release();
if (d3ddv != NULL) d3ddv->Release();
if (d3d != NULL) d3d->Release();
}
CWindow *CWindow::GetInstance()
{
if (__instance == NULL) __instance = new CWindow();
return __instance;
}
LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) {
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
HWND CWindow::CreateGameWindow(HINSTANCE hInstance, int nCmdShow, int ScreenWidth, int ScreenHeight)
{
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.hInstance = hInstance;
wc.lpfnWndProc = (WNDPROC)WinProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = WINDOW_CLASS_NAME;
wc.hIconSm = NULL;
RegisterClassEx(&wc);
HWND hWnd =
CreateWindow(
WINDOW_CLASS_NAME,
MAIN_WINDOW_TITLE,
WS_OVERLAPPEDWINDOW, // WS_EX_TOPMOST | WS_VISIBLE | WS_POPUP,
CW_USEDEFAULT,
CW_USEDEFAULT,
ScreenWidth,
ScreenHeight,
NULL,
NULL,
hInstance,
NULL);
if (!hWnd)
{
OutputDebugString(L"[ERROR] CreateWindow failed");
DWORD ErrCode = GetLastError();
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return hWnd;
}
/*
Utility function to load texture
*/
LPDIRECT3DTEXTURE9 CWindow::LoadTexture(LPCWSTR texturePath, D3DCOLOR transparentColor)
{
D3DXIMAGE_INFO info;
LPDIRECT3DTEXTURE9 texture;
HRESULT result = D3DXGetImageInfoFromFile(texturePath, &info);
if (result != D3D_OK)
{
DebugOut(L"[ERROR] GetImageInfoFromFile failed: %s\n", texturePath);
return NULL;
}
LPDIRECT3DDEVICE9 d3ddv = CWindow::GetInstance()->GetDirect3DDevice();
result = D3DXCreateTextureFromFileEx(
d3ddv, // Pointer to Direct3D device object
texturePath, // Path to the image to load
info.Width, // Texture width
info.Height, // Texture height
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
transparentColor, // Transparent color
&info,
NULL,
&texture); // Created texture pointer
if (result != D3D_OK)
{
DebugOut(L"[ERROR] CreateTextureFromFile failed. File: %s\n", texturePath);
return NULL;
}
DebugOut(L"[INFO] Texture loaded Ok: %s \n", texturePath);
return texture;
}
| [
"tranght636@gmail.com"
] | tranght636@gmail.com |
5040857922795279a0516533ae92f767fa277c2b | 1d2e30ee7817aa5132dd04b28e55eb99657cf4c1 | /ShootingScene.h | 9e4be17f479a1696dd38c0431027d10dd7e73ebe | [] | no_license | Shung-2/Mindustry | b13b20ec7739712b4e69d24361def4175a807044 | cefb5f38096a73502102231cebe313740bb655ae | refs/heads/main | 2023-07-31T05:06:06.163259 | 2021-09-24T16:11:37 | 2021-09-24T16:11:37 | 410,024,774 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 580 | h | #pragma once
#include "Scene.h"
class ShootingScene :
public Scene
{
private:
ImageObject _shootingScene;
GameObject* _enemyControler;
AnimObject* _testCore; //TEST용입니다 삭제해도 됩니다
GameObject* _projectileManager;
GameObject* _enemyManager;
AnimationClip* _enemyDaggerWalk;
public:
ShootingScene();
~ShootingScene();
virtual HRESULT Init();
virtual void Release();
virtual void Update();
virtual void Render();
void SetScene();
void TestCore(); //TEST용 삭제해도 됩니당
void SetProjectile();
void SetEnemyManager();
};
| [
"66060749+Shung-2@users.noreply.github.com"
] | 66060749+Shung-2@users.noreply.github.com |
2c841e36f966eebadc7d01dcab373d779ba6349f | c6a26cd1adb9005a61b5bdf93c9e7562576e81dc | /TextadventureTest/Room2.h | 58ac3162e7db6327d7a0bf15e5aa479ea41785f1 | [] | no_license | FelixK15/k15_textadventure | 4c385ce4b929d6af590fc5ac837c67e3d97a77d1 | 11bd6d9cfc8f06a12cf4909da9f962a002af5a6c | refs/heads/master | 2021-01-16T23:13:56.243285 | 2014-09-10T08:32:18 | 2014-09-10T08:32:18 | 65,762,625 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 580 | h | /**
* author Felix Klinge <f.klinge15@gmail.com>
* version 1.0
*
* LICENSE
* The sourcecode of this project is fully open source.
* You can do whatever you want with it.
*
* DESCRIPTION
* This is a Textadventure game that got developed during a 24 hours competition.
* So don't expect to find clean code or comments.
*
*/
#ifndef __K15_TEXTADVENTURETEST_ROOM2__
#define __K15_TEXTADVENTURETEST_ROOM2__
#include "Room.h"
namespace K15_Textadventure
{
class Room2
: public Room
{
public:
Room2();
~Room2(){};
};
}
#endif //__K15_TEXTADVENTURETEST_ROOM2__ | [
"f.klinge@k15games.de"
] | f.klinge@k15games.de |
daa4e8280a0a50cf52b748d0c763d9a19076196e | 2f6b17aa5911b83e27f365a28ad09ee74e0d63f9 | /source/plugins/gameFallout3/fallout3bsainvalidation.cpp | 8c69eb14cd900df7fcaf9e02a935a8dbb181b470 | [] | no_license | GrantSP/OriginalMO | afcc7b9bc8225db36216fe963c162696193e4b74 | 7935114fa2bbc6e38ad7a7b485754d20ee9bec23 | refs/heads/master | 2021-09-02T06:20:13.207699 | 2017-12-31T00:44:07 | 2017-12-31T00:44:07 | 115,833,608 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 440 | cpp | #include "fallout3bsainvalidation.h"
#include <imoinfo.h>
Fallout3BSAInvalidation::Fallout3BSAInvalidation(const std::shared_ptr<DataArchives> &dataArchives, MOBase::IOrganizer *moInfo)
: GamebryoBSAInvalidation(dataArchives, "fallout.ini", moInfo)
{
}
QString Fallout3BSAInvalidation::invalidationBSAName() const
{
return "Fallout - Invalidation.bsa";
}
unsigned long Fallout3BSAInvalidation::bsaVersion() const
{
return 0x68;
}
| [
"fr00gyl@gmail.com"
] | fr00gyl@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.