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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
596f4aee6b0a0e4b665313db01db32c154ffc951 | d4d24f8a54bee6e76610f274d98ae165e461b133 | /packet_testing/Full_packet_test_MPU/full_packet_test/full_packet_test.ino | b8154762afa9ce80a21b5d115b941d2e1c404b0d | [] | no_license | crazymach/Arduino-Projects | f3733d4b014d5ff31ed65149d2dd6d8aa6d04aa2 | fc32b67371ed2cd060b93bb4f10e687e0c0167ef | refs/heads/master | 2020-09-24T05:41:37.257992 | 2017-01-08T01:37:51 | 2017-01-08T01:37:51 | 66,501,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,307 | ino | #include <ArduinoJson.h>
#include<Wire.h>
const int MPU_addr=0x68; // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
String incomingByte;
float loadvalue;
float average;
int load_sensor;
int xcoord = 1;
int ycoord = 2;
int zcoord = 3;
int led = 13;
//1.Read 2. Parse 3. Do Work 4. Generate 5. Print
//{"seq":2,"led":0}$
void setup() {
// put your setup code here, to run once:
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
while (Serial.available()) {
char INBYTE = Serial.read();
if (INBYTE == '$') {
char charBuf[50];
incomingByte.toCharArray(charBuf,50);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(incomingByte);
char Sequence = root["seq"];
char led_json = root["led"];
int incoming_sequence = Sequence;
if(incoming_sequence > 0){
if (led_json == 1)
{
blinking();
}
StaticJsonBuffer<200> jsonBuffer;
JsonObject& outgoing = jsonBuffer.createObject();
outgoing["Packet Number"] = Sequence ;
outgoing["Sensor"] = average_calculation();
JsonObject& gyro = outgoing.createNestedObject("Gyro");
gyro["GyX"] = GyX;
gyro["GyY"] = GyY;
gyro["GyZ"] = GyZ;
JsonObject& Accel = outgoing.createNestedObject("Accel");
Accel["AcX"] = AcX;
Accel["AcY"] = AcY;
Accel["AcZ"] = AcZ;
outgoing["Temp"] = Tmp;
outgoing.printTo(Serial);
Serial.println();
}
incomingByte = "";
}
else {
incomingByte += INBYTE; //add byte to json string (to parse later)
}
/*delay(3); //delay to allow buffer to fill
if (Serial.available() >0) {
char INBYTE = Serial.read(); //gets one byte from serial buffer
incomingByte += INBYTE; //makes the string readString
} */
}
}
//void json(String incomingByte){
// char charBuf[50];
// incomingByte.toCharArray(charBuf,50);
//
// StaticJsonBuffer<200> jsonBuffer;
// JsonObject& root = jsonBuffer.parseObject(incomingByte);
// char Sequence = root["seq"];
// char led_json = root["led"];
// int incoming_sequence = Sequence;
// if(incoming_sequence > 0){
// if(led_json == 1)
// {
// blinking();
// }
// StaticJsonBuffer<200> jsonBuffer;
// JsonObject& outgoing = jsonBuffer.createObject();
// outgoing["Packet Number"] = Sequence ;
// outgoing["Sensor"] = analogRead(A0) ;
//
// JsonObject& gyro = outgoing.createNestedObject("Gyro");
// gyro["X"] = xcoord;
// gyro["Y"] = ycoord;
// gyro["Z"] = zcoord;
//
// outgoing.printTo(Serial);
// Serial.println();
// }
// delay(800);
//}
void blinking(){
int count = 0;
while(count < 15){
digitalWrite(led, HIGH);
delay(30);
digitalWrite(led,LOW);
delay(30);
count += 1;
}
}
float average_calculation(){
for(int x = 0; x <200; x++){
loadvalue = analogRead(A0);
average = (loadvalue + average)/2;
}
float calculation = average;
return calculation;
}
void MPU(){
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr,14,true); // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Tmp = Tmp/340.00+36.53;
}
| [
"benhyee@gmail.com"
] | benhyee@gmail.com |
3e3618922a5a116b786e415ad7b4583f6fa9ab93 | c8eb28a643230de0564db51829ed8d2e7a9a574e | /Virutal.cpp | 173fb9c878e7cc6eb69134c4d4cb81ea983fa2c8 | [] | no_license | michaelsad10/cpp | 6af6dfc4964e4b67e636cddc70e90facae98d7f7 | e707168be77cdb18910dfd56c12a776784ca8dc0 | refs/heads/master | 2020-03-30T18:58:39.443876 | 2018-10-18T15:28:15 | 2018-10-18T15:28:15 | 151,522,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | cpp | #include <iostream>
using namespace std;
class Animal{
public:
void getFamily(){cout << "We are animals" << endl;}
virtual void getClass(){cout << "I'm an Animal" << endl;}
};
class Dog : public Animal{
public:
void getClass(){cout <<"I'm a dog" << endl; }
};
class GermanShepard : public Dog{
public:
void getClass(){cout << "I'm a german shepard" << endl; }
void getDerived(){cout << "I'm an animal and dog" << endl; }
};
void whatClassAreYou(Animal *animal){
animal -> getClass();
}
int main(){
Animal *animal = new Animal;
Dog *dog = new Dog;
GermanShepard max;
Dog spot;
Dog* ptrDog = &spot;
Animal* ptrGshepard = &max;
ptrDog -> getFamily();
ptrDog -> getClass();
ptrGshepard -> getFamily();
ptrGshepard -> getClass();
whatClassAreYou(animal);
whatClassAreYou(dog);
return 0;
} | [
"sadag004@umn.edu"
] | sadag004@umn.edu |
4b62fcfd5231c13cbc2632ecaea7b438a254372a | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/40/6f8e91f06ac7a1/main.cpp | b224ad7c6354f5ba92baa57fe4c70f32a4642b62 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | #include <iostream>
#include <string>
#include <typeinfo>
struct Base {}; // non-polymorphic
struct Derived : Base {};
struct Base2 { virtual void foo() {} }; // polymorphic
struct Derived2 : Base2 {};
int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
3ed2fc4b14092e8063abdd3239b3c6156701175d | a7b670687a192cffcc9355691549478ff22d1fa3 | /frc-cpp-sim/WPILib-2013/GearTooth.cpp | 58cfb869b32ada551981897019f044ea029702eb | [] | no_license | anidev/frc-simulator | f226d9af0bcb4fc25f33ad3a28dceb0fbadac109 | 3c60daa84acbabdcde5aa9de6935e1950b48e4c3 | refs/heads/master | 2020-12-24T17:35:21.255684 | 2014-02-04T04:45:21 | 2014-02-04T04:45:21 | 7,597,042 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,389 | cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "GearTooth.h"
//const double GearTooth::kGearToothThreshold;
/**
* Common code called by the constructors.
*/
void GearTooth::EnableDirectionSensing(bool directionSensitive)
{
if (directionSensitive)
{
SetPulseLengthMode(kGearToothThreshold);
}
}
/**
* Construct a GearTooth sensor given a channel.
*
* The default module is assumed.
*
* @param channel The GPIO channel on the digital module that the sensor is connected to.
* @param directionSensitive Enable the pulse length decoding in hardware to specify count direction.
*/
GearTooth::GearTooth(UINT32 channel, bool directionSensitive)
: Counter(channel)
{
EnableDirectionSensing(directionSensitive);
}
/**
* Construct a GearTooth sensor given a channel and module.
*
* @param moduleNumber The digital module (1 or 2).
* @param channel The GPIO channel on the digital module that the sensor is connected to.
* @param directionSensitive Enable the pulse length decoding in hardware to specify count direction.
*/
GearTooth::GearTooth(UINT8 moduleNumber, UINT32 channel, bool directionSensitive)
: Counter(moduleNumber, channel)
{
EnableDirectionSensing(directionSensitive);
}
/**
* Construct a GearTooth sensor given a digital input.
* This should be used when sharing digial inputs.
*
* @param source An object that fully descibes the input that the sensor is connected to.
* @param directionSensitive Enable the pulse length decoding in hardware to specify count direction.
*/
GearTooth::GearTooth(DigitalSource *source, bool directionSensitive)
: Counter(source)
{
EnableDirectionSensing(directionSensitive);
}
GearTooth::GearTooth(DigitalSource &source, bool directionSensitive): Counter(source)
{
EnableDirectionSensing(directionSensitive);
}
/**
* Free the resources associated with a gear tooth sensor.
*/
GearTooth::~GearTooth()
{
}
std::string GearTooth::GetSmartDashboardType() {
return "GearTooth";
}
| [
"anidev.aelico@gmail.com"
] | anidev.aelico@gmail.com |
38d02f2a61e74fd3ab76bd97890d24020681eb99 | dc5c9ff6dbf84558e15a778dd6a3d91058b82c54 | /toolkit/SequenceMethods.cc | a15d3837efda882d960a0d4e3a821e48609b0e04 | [
"MIT"
] | permissive | rdeforest/ColdStore | a8138c2543fd22dcb6ded30e49dd93144047b2c0 | 07d673de64d9536ca9225fd98d2ff038d07cf9b8 | refs/heads/master | 2021-01-16T17:47:11.562347 | 2015-06-27T16:15:20 | 2015-06-27T16:15:20 | 38,057,961 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,557 | cc | // SequenceMethods.cc: builds the $list data object
// Copyright (C) 2001 Ryan Daum
// see LICENSE (MD5 f5220f8f599e5e926f37cf32efe3ab68) for terms
#include <Data.hh>
#include <Tuple.hh>
#include <Object.hh>
#include <Store.hh>
#include <List.hh>
#include <Frame.hh>
#include <Frob.hh>
#include <Error.hh>
#include <String.hh>
#include <Closure.hh>
#include <MetaData.hh>
#include "common.hh"
static Slot join( Frame *context )
{
Slot self = context->_this;
Slot args = context->_arguments;
if ( ! (AKO((Data*)(self), List )) )
throw new Error("type", self, "join must be called on a list");
Slot sep = " ";
if (args->length() == 1) {
sep = args[0];
if ( ! (AKO((Data*)(sep), String )) )
throw new Error("type", sep, "1st argument to words must be a string");
}
return ((List*)(Data*)self)->join(sep);
}
static Slot englishJoin( Frame *context )
{
Slot self = context->_this;
Slot args = context->_arguments;
if ( ! (AKO((Data*)(self), List )) )
throw new Error("type", self, "englishJoin must be called on a list");
Slot res = new String();
Slot l = self->iterator();
while (l->More()) {
Slot el = l->Next();
if (!l->More())
res = res->concat("and ");
res = res->concat( el );
if (l->More())
res = res->concat(", ");
}
return res;
}
Slot defineExtraSequenceMethods(Frame *context)
{
if (!MetaData::instance)
MetaData::instance = new MetaData();
MetaData::instance.join = &join;
MetaData::instance.englishJoin = &englishJoin;
return true;
}
| [
"guitar.robot@gmail.com"
] | guitar.robot@gmail.com |
e2dc6bde960c6c3836bc11056fea3d10c504737a | d1a18053ff3db569686e7b7e74c45a669f23c81f | /src/generator/genFunctions.cpp | d02fcd90e90283e907bd08ff84ca0503d995998c | [
"MIT"
] | permissive | ThermalSpan/cpp-knapsack | 73efccdf6c16029cda7dd190810ad61102fc37cb | dcc577a3ef9f9da1f2a85400465f488d91fdd8cf | refs/heads/master | 2021-01-10T15:15:50.324353 | 2016-02-03T21:35:19 | 2016-02-03T21:35:19 | 50,005,472 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,021 | cpp | //
// genFunctions.cpp
// knapsack
//
// Created by Russell Wilhelm Bentley on 1/21/16.
// Copyright (c) 2016 Russell Wilhelm Bentley
// Distributed under the MIT License
//
#include "genFunctions.h"
using namespace std;
void genUnCor (int itemCount, int range, ofstream &outputFile) {
for (int i = 1; i <= itemCount; i++) {
int weight = (rand () % range) + 1;
int value = rand () % range + 1;
outputFile << i << " " << value << " " << weight << endl;
}
}
void genWeakCor (int itemCount, int range, ofstream &outputFile) {
int interval = range / 10;
int priceRange = 2 * interval;
for (int i = 1; i <= itemCount; i++) {
int weight = (rand () % range) + 1;
int value = ((rand () % priceRange) - interval) + weight;
outputFile << i << " " << value << " " << weight << endl;
}
}
void genStrCor (int itemCount, int range, ofstream &outputFile) {
int offset = range / 10;
for (int i = 1; i <= itemCount; i++) {
int weight = (rand () % range) + 1;
outputFile << i << " " << weight + offset << " " << weight << endl;
}
}
void genInvStrCor (int itemCount, int range, ofstream &outputFile) {
int offset = range / 10;
for (int i = 1; i <= itemCount; i++) {
int weight = (rand () % range) + 1;
outputFile << i << " " << weight - offset << " " << weight << endl;
}
}
void genAlmStrCor (int itemCount, int range, ofstream &outputFile) {
int interval = range / 10;
int increment = range / 500;
int priceRange = 2 * increment;
for (int i = 1; i <= itemCount; i++) {
int weight = rand () %range + 1;
int value = ((rand () % priceRange) - increment) + weight + interval;
outputFile << i << " " << value << " " << weight << endl;
}
}
void genSubSum (int itemCount, int range, ofstream &outputFile) {
for (int i = 1; i <= itemCount; i++) {
int weight = rand () %range + 1;
outputFile << i << " " << weight << " " << weight << endl;
}
}
| [
"russell.bentley@Uconn.edu"
] | russell.bentley@Uconn.edu |
4cfc85bb1569831d5c45b85df37804b97539404c | 1310ca784c1b0b9238f2407eb59d0704b8ae5a08 | /NextGen/arduino/Noncurrent/z_WeightSensorTests/HX711.ino | 685f14da5661ce75bc7da8606ccbb8c0fef4bc36 | [] | no_license | RyannDaGreat/LightWave | 6b89838bfd48dba010eb5229b84b206be4e8ccbb | d055b0c01b01b3795d9e6c28b6b70f969893ed97 | refs/heads/master | 2023-07-20T08:23:47.526629 | 2023-07-18T00:25:02 | 2023-07-18T00:25:02 | 123,113,725 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,318 | ino | /**
*
* HX711 library for Arduino
* https://github.com/bogde/HX711
*
* MIT License
* (c) 2018 Bogdan Necula
*
**/
#ifndef HX711_h
#define HX711_h
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
class HX711
{
private:
byte PD_SCK; // Power Down and Serial Clock Input Pin
byte DOUT; // Serial Data Output Pin
byte GAIN; // amplification factor
long OFFSET = 0; // used for tare weight
float SCALE = 1; // used to return weight in grams, kg, ounces, whatever
public:
HX711();
virtual ~HX711();
// Initialize library with data output pin, clock input pin and gain factor.
// Channel selection is made by passing the appropriate gain:
// - With a gain factor of 64 or 128, channel A is selected
// - With a gain factor of 32, channel B is selected
// The library default is "128" (Channel A).
void begin(byte dout, byte pd_sck, byte gain = 128);
// Check if HX711 is ready
// from the datasheet: When output data is not ready for retrieval, digital output pin DOUT is high. Serial clock
// input PD_SCK should be low. When DOUT goes to low, it indicates data is ready for retrieval.
bool is_ready();
// Wait for the HX711 to become ready
void wait_ready(unsigned long delay_ms = 0);
bool wait_ready_retry(int retries = 3, unsigned long delay_ms = 0);
bool wait_ready_timeout(unsigned long timeout = 1000, unsigned long delay_ms = 0);
// set the gain factor; takes effect only after a call to read()
// channel A can be set for a 128 or 64 gain; channel B has a fixed 32 gain
// depending on the parameter, the channel is also set to either A or B
void set_gain(byte gain = 128);
// waits for the chip to be ready and returns a reading
long read();
// returns an average reading; times = how many times to read
long read_average(byte times = 10);
// returns (read_average() - OFFSET), that is the current value without the tare weight; times = how many readings to do
double get_value(byte times = 1);
// returns get_value() divided by SCALE, that is the raw value divided by a value obtained via calibration
// times = how many readings to do
float get_units(byte times = 1);
// set the OFFSET value for tare weight; times = how many times to read the tare value
void tare(byte times = 10);
// set the SCALE value; this value is used to convert the raw data to "human readable" data (measure units)
void set_scale(float scale = 1.f);
// get the current SCALE
float get_scale();
// set OFFSET, the value that's subtracted from the actual reading (tare weight)
void set_offset(long offset = 0);
// get the current OFFSET
long get_offset();
// puts the chip into power down mode
void power_down();
// wakes up the chip after power down mode
void power_up();
};
#endif /* HX711_h */
/**
*
* HX711 library for Arduino
* https://github.com/bogde/HX711
*
* MIT License
* (c) 2018 Bogdan Necula
*
**/
//#include <Arduino.h>
//#include "HX711.h"
// TEENSYDUINO has a port of Dean Camera's ATOMIC_BLOCK macros for AVR to ARM Cortex M3.
#define HAS_ATOMIC_BLOCK (defined(ARDUINO_ARCH_AVR) || defined(TEENSYDUINO))
// Whether we are running on either the ESP8266 or the ESP32.
#define ARCH_ESPRESSIF (defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32))
// Whether we are actually running on FreeRTOS.
#define IS_FREE_RTOS defined(ARDUINO_ARCH_ESP32)
// Define macro designating whether we're running on a reasonable
// fast CPU and so should slow down sampling from GPIO.
#define FAST_CPU \
( \
ARCH_ESPRESSIF || \
defined(ARDUINO_ARCH_SAM) || defined(ARDUINO_ARCH_SAMD) || \
defined(ARDUINO_ARCH_STM32) || defined(TEENSYDUINO) \
)
#if HAS_ATOMIC_BLOCK
// Acquire AVR-specific ATOMIC_BLOCK(ATOMIC_RESTORESTATE) macro.
#include <util/atomic.h>
#endif
#if FAST_CPU
#else
// Make shiftIn() be aware of clockspeed for
// faster CPUs like ESP32, Teensy 3.x and friends.
// See also:
// - https://github.com/bogde/HX711/issues/75
// - https://github.com/arduino/Arduino/issues/6561
// - https://community.hiveeyes.org/t/using-bogdans-canonical-hx711-library-on-the-esp32/539
uint8_t shiftInSlow(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
uint8_t value = 0;
uint8_t i;
for(i = 0; i < 8; ++i) {
digitalWrite(clockPin, HIGH);
delayMicroseconds(1);
if(bitOrder == LSBFIRST)
value |= digitalRead(dataPin) << i;
else
value |= digitalRead(dataPin) << (7 - i);
digitalWrite(clockPin, LOW);
delayMicroseconds(1);
}
return value;
}
#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftInSlow(data,clock,order)
//#else
//#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftIn(data,clock,order)
#endif
HX711::HX711() {
}
HX711::~HX711() {
}
void HX711::begin(byte dout, byte pd_sck, byte gain) {
PD_SCK = pd_sck;
DOUT = dout;
pinMode(PD_SCK, OUTPUT);
pinMode(DOUT, INPUT);
set_gain(gain);
}
bool HX711::is_ready() {
return digitalRead(DOUT) == LOW;
}
void HX711::set_gain(byte gain) {
switch (gain) {
case 128: // channel A, gain factor 128
GAIN = 1;
break;
case 64: // channel A, gain factor 64
GAIN = 3;
break;
case 32: // channel B, gain factor 32
GAIN = 2;
break;
}
digitalWrite(PD_SCK, LOW);
read();
}
long HX711::read() {
// Wait for the chip to become ready.
wait_ready();
// Define structures for reading data into.
unsigned long value = 0;
uint8_t data[3] = { 0 };
uint8_t filler = 0x00;
// Protect the read sequence from system interrupts. If an interrupt occurs during
// the time the PD_SCK signal is high it will stretch the length of the clock pulse.
// If the total pulse time exceeds 60 uSec this will cause the HX711 to enter
// power down mode during the middle of the read sequence. While the device will
// wake up when PD_SCK goes low again, the reset starts a new conversion cycle which
// forces DOUT high until that cycle is completed.
//
// The result is that all subsequent bits read by shiftIn() will read back as 1,
// corrupting the value returned by read(). The ATOMIC_BLOCK macro disables
// interrupts during the sequence and then restores the interrupt mask to its previous
// state after the sequence completes, insuring that the entire read-and-gain-set
// sequence is not interrupted. The macro has a few minor advantages over bracketing
// the sequence between `noInterrupts()` and `interrupts()` calls.
#if HAS_ATOMIC_BLOCK
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
#elif IS_FREE_RTOS
// Begin of critical section.
// Critical sections are used as a valid protection method
// against simultaneous access in vanilla FreeRTOS.
// Disable the scheduler and call portDISABLE_INTERRUPTS. This prevents
// context switches and servicing of ISRs during a critical section.
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
portENTER_CRITICAL(&mux);
#else
// Disable interrupts.
noInterrupts();
#endif
// Pulse the clock pin 24 times to read the data.
data[2] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
data[1] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
data[0] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
// Set the channel and the gain factor for the next reading using the clock pin.
for (unsigned int i = 0; i < GAIN; i++) {
digitalWrite(PD_SCK, HIGH);
#if ARCH_ESPRESSIF
delayMicroseconds(1);
#endif
digitalWrite(PD_SCK, LOW);
#if ARCH_ESPRESSIF
delayMicroseconds(1);
#endif
}
#if IS_FREE_RTOS
// End of critical section.
portEXIT_CRITICAL(&mux);
#elif HAS_ATOMIC_BLOCK
}
#else
// Enable interrupts again.
interrupts();
#endif
// Replicate the most significant bit to pad out a 32-bit signed integer
if (data[2] & 0x80) {
filler = 0xFF;
} else {
filler = 0x00;
}
// Construct a 32-bit signed integer
value = ( static_cast<unsigned long>(filler) << 24
| static_cast<unsigned long>(data[2]) << 16
| static_cast<unsigned long>(data[1]) << 8
| static_cast<unsigned long>(data[0]) );
return static_cast<long>(value);
}
void HX711::wait_ready(unsigned long delay_ms) {
// Wait for the chip to become ready.
// This is a blocking implementation and will
// halt the sketch until a load cell is connected.
while (!is_ready()) {
// Probably will do no harm on AVR but will feed the Watchdog Timer (WDT) on ESP.
// https://github.com/bogde/HX711/issues/73
delay(delay_ms);
}
}
bool HX711::wait_ready_retry(int retries, unsigned long delay_ms) {
// Wait for the chip to become ready by
// retrying for a specified amount of attempts.
// https://github.com/bogde/HX711/issues/76
int count = 0;
while (count < retries) {
if (is_ready()) {
return true;
}
delay(delay_ms);
count++;
}
return false;
}
bool HX711::wait_ready_timeout(unsigned long timeout, unsigned long delay_ms) {
// Wait for the chip to become ready until timeout.
// https://github.com/bogde/HX711/pull/96
unsigned long millisStarted = millis();
while (millis() - millisStarted < timeout) {
if (is_ready()) {
return true;
}
delay(delay_ms);
}
return false;
}
long HX711::read_average(byte times) {
long sum = 0;
for (byte i = 0; i < times; i++) {
sum += read();
// Probably will do no harm on AVR but will feed the Watchdog Timer (WDT) on ESP.
// https://github.com/bogde/HX711/issues/73
delay(0);
}
return sum / times;
}
double HX711::get_value(byte times) {
return read_average(times) - OFFSET;
}
float HX711::get_units(byte times) {
return get_value(times) / SCALE;
}
void HX711::tare(byte times) {
double sum = read_average(times);
set_offset(sum);
}
void HX711::set_scale(float scale) {
SCALE = scale;
}
float HX711::get_scale() {
return SCALE;
}
void HX711::set_offset(long offset) {
OFFSET = offset;
}
long HX711::get_offset() {
return OFFSET;
}
void HX711::power_down() {
digitalWrite(PD_SCK, LOW);
digitalWrite(PD_SCK, HIGH);
}
void HX711::power_up() {
digitalWrite(PD_SCK, LOW);
}
| [
"sqrtryan@gmail.com"
] | sqrtryan@gmail.com |
281fc722314ed908a48c661c7b575d8ae5224596 | 1bf6613e21a5695582a8e6d9aaa643af4a1a5fa8 | /src/net/quic/test_tools/.svn/text-base/mock_random.h.svn-base | b583182a6b09e7a5846815919a1200604580e9ac | [
"BSD-3-Clause"
] | permissive | pqrkchqps/MusicBrowser | ef5c9603105b4f4508a430d285334667ec3c1445 | 03216439d1cc3dae160f440417fcb557bb72f8e4 | refs/heads/master | 2020-05-20T05:12:14.141094 | 2013-05-31T02:21:07 | 2013-05-31T02:21:07 | 10,395,498 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 832 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_QUIC_TEST_TOOLS_MOCK_RANDOM_H_
#define NET_QUIC_TEST_TOOLS_MOCK_RANDOM_H_
#include "base/compiler_specific.h"
#include "net/quic/crypto/quic_random.h"
namespace net {
class MockRandom : public QuicRandom {
public:
// QuicRandom:
// Fills the |data| buffer with 'r'.
virtual void RandBytes(void* data, size_t len) OVERRIDE;
// Returns 0xDEADBEEF.
virtual uint64 RandUint64() OVERRIDE;
// Returns false.
virtual bool RandBool() OVERRIDE;
// Does nothing.
virtual void Reseed(const void* additional_entropy,
size_t entropy_len) OVERRIDE;
};
} // namespace net
#endif // NET_QUIC_TEST_TOOLS_MOCK_RANDOM_H_
| [
"creps002@umn.edu"
] | creps002@umn.edu | |
625436d24bccb87d154c89174b264b9b8151529c | 04b5b56a9ed37dac7525131f2653beb38888c54e | /c/猴子偷桃.cpp | 27f1887c30a4ffb14d863cbe96f07042f3ed6a3c | [] | no_license | Wild-pointers/pratice | 597ef5e2ea5747a2d17e3c2ca882124540d097a9 | 3d69731e325c0d7e07d63a56b0048b6c0ca05333 | refs/heads/master | 2022-12-21T22:08:26.942611 | 2020-08-09T11:21:28 | 2020-08-09T11:21:28 | 222,474,079 | 0 | 0 | null | 2022-12-16T00:37:14 | 2019-11-18T14:53:45 | Java | UTF-8 | C++ | false | false | 103 | cpp | #include <stdio.h>
int main()
{
int i,n=0;
for(i=0;i<7;i++)
{
n=(n+1)*2;
printf("%d\n",n);
}
}
| [
"1416170632@qq.com"
] | 1416170632@qq.com |
9c45ae66fffebdefc4881d2d1366737c207e5c81 | d4e9f4dac826b08f3427f58541976abefd72c0d3 | /solution.cpp | 37ec03d9121e83432626c280a75bfa4885dd749f | [] | no_license | froycard/ProjectEuler-12 | 2f76fdda470b0408739fa3a5dd24656efb189d29 | 946050c3fabddff6414d8d867c71b3aa0be9b0e8 | refs/heads/master | 2022-07-08T05:11:21.384124 | 2020-05-17T18:55:22 | 2020-05-17T18:55:22 | 264,734,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | cpp | #include<iostream>
#include<cmath>
#include<vector>
#include<set>
using namespace std;
set<unsigned> divisor(unsigned n)
{
set <unsigned> divs = {1,n};
for(auto i=2; i<int(sqrt(n))+1;++i)
if(n%i == 0)
{
divs.insert(i);
divs.insert(n/i);
}
return divs;
}
int main()
{
unsigned number;
for(auto i = 1;;++i)
{
unsigned triangular = i*(i+1)/2;
set<unsigned> divs = divisor(triangular);
if(divs.size()>500)
{
number = triangular;
break;
}
}
cout << "Sol.: " << number << endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
fa37047a1981e7ce6198d225fb741665f1b08a97 | 6b698df1c15b492b21b923c3c2384d71a32e1de4 | /src/data_structures/tree/t_tree.h | c209f5c71d46b401d83a62223dbb75392efd03fc | [] | no_license | eric-therond/accassias | 7929c85bf5163afde23467bd9decf74826873c87 | dd602d598ded18a13dd8f674dcbe23b43a97b336 | refs/heads/master | 2021-01-15T18:58:17.187136 | 2017-06-20T19:21:49 | 2017-06-20T19:21:49 | 32,142,493 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | h | #ifndef T_TREE_H
#define T_TREE_H
#include "data_structures/graph/t_graph.h"
template <typename T>
class t_tree: public t_graph<T>
{
public:
t_tree(){
this->root = NULL;
this->istree = true;
};
};
#endif
| [
"eric.therond.fr@gmail.com"
] | eric.therond.fr@gmail.com |
fd2fa986fee90de3b08aed169b0955e8e8b18034 | 2cfa657fd119a23de2a5c2ae6d55e6d2516bae2d | /src/wallet/test/wallet_crypto_tests.cpp | e3eb8a6f3970b99e684bc49af64e52a9600b46d2 | [
"MIT"
] | permissive | vivuscoin/vivuscoin | 640b10ae3a72c03b501e03b07caae09ce6c87c81 | ba0db89712234bf68b2d6b63ef2c420d65c7c25d | refs/heads/master | 2023-05-07T06:26:26.241247 | 2021-05-25T03:54:32 | 2021-05-25T03:54:32 | 362,198,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,844 | cpp | // Copyright (c) 2014-2018 The Bitcoin Core developers
// Copyright (c) 2021 The Vivuscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/test_vivuscoin.h>
#include <util/strencodings.h>
#include <wallet/crypter.h>
#include <vector>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(wallet_crypto_tests, BasicTestingSetup)
class TestCrypter
{
public:
static void TestPassphraseSingle(const std::vector<unsigned char>& vchSalt, const SecureString& passphrase, uint32_t rounds,
const std::vector<unsigned char>& correctKey = std::vector<unsigned char>(),
const std::vector<unsigned char>& correctIV=std::vector<unsigned char>())
{
CCrypter crypt;
crypt.SetKeyFromPassphrase(passphrase, vchSalt, rounds, 0);
if(!correctKey.empty())
BOOST_CHECK_MESSAGE(memcmp(crypt.vchKey.data(), correctKey.data(), crypt.vchKey.size()) == 0, \
HexStr(crypt.vchKey.begin(), crypt.vchKey.end()) + std::string(" != ") + HexStr(correctKey.begin(), correctKey.end()));
if(!correctIV.empty())
BOOST_CHECK_MESSAGE(memcmp(crypt.vchIV.data(), correctIV.data(), crypt.vchIV.size()) == 0,
HexStr(crypt.vchIV.begin(), crypt.vchIV.end()) + std::string(" != ") + HexStr(correctIV.begin(), correctIV.end()));
}
static void TestPassphrase(const std::vector<unsigned char>& vchSalt, const SecureString& passphrase, uint32_t rounds,
const std::vector<unsigned char>& correctKey = std::vector<unsigned char>(),
const std::vector<unsigned char>& correctIV=std::vector<unsigned char>())
{
TestPassphraseSingle(vchSalt, passphrase, rounds, correctKey, correctIV);
for(SecureString::const_iterator i(passphrase.begin()); i != passphrase.end(); ++i)
TestPassphraseSingle(vchSalt, SecureString(i, passphrase.end()), rounds);
}
static void TestDecrypt(const CCrypter& crypt, const std::vector<unsigned char>& vchCiphertext, \
const std::vector<unsigned char>& vchPlaintext = std::vector<unsigned char>())
{
CKeyingMaterial vchDecrypted;
crypt.Decrypt(vchCiphertext, vchDecrypted);
if (vchPlaintext.size())
BOOST_CHECK(CKeyingMaterial(vchPlaintext.begin(), vchPlaintext.end()) == vchDecrypted);
}
static void TestEncryptSingle(const CCrypter& crypt, const CKeyingMaterial& vchPlaintext,
const std::vector<unsigned char>& vchCiphertextCorrect = std::vector<unsigned char>())
{
std::vector<unsigned char> vchCiphertext;
crypt.Encrypt(vchPlaintext, vchCiphertext);
if (!vchCiphertextCorrect.empty())
BOOST_CHECK(vchCiphertext == vchCiphertextCorrect);
const std::vector<unsigned char> vchPlaintext2(vchPlaintext.begin(), vchPlaintext.end());
TestDecrypt(crypt, vchCiphertext, vchPlaintext2);
}
static void TestEncrypt(const CCrypter& crypt, const std::vector<unsigned char>& vchPlaintextIn, \
const std::vector<unsigned char>& vchCiphertextCorrect = std::vector<unsigned char>())
{
TestEncryptSingle(crypt, CKeyingMaterial(vchPlaintextIn.begin(), vchPlaintextIn.end()), vchCiphertextCorrect);
for(std::vector<unsigned char>::const_iterator i(vchPlaintextIn.begin()); i != vchPlaintextIn.end(); ++i)
TestEncryptSingle(crypt, CKeyingMaterial(i, vchPlaintextIn.end()));
}
};
BOOST_AUTO_TEST_CASE(passphrase) {
// These are expensive.
TestCrypter::TestPassphrase(ParseHex("0000deadbeef0000"), "test", 25000, \
ParseHex("fc7aba077ad5f4c3a0988d8daa4810d0d4a0e3bcb53af662998898f33df0556a"), \
ParseHex("cf2f2691526dd1aa220896fb8bf7c369"));
std::string hash(GetRandHash().ToString());
std::vector<unsigned char> vchSalt(8);
GetRandBytes(vchSalt.data(), vchSalt.size());
uint32_t rounds = InsecureRand32();
if (rounds > 30000)
rounds = 30000;
TestCrypter::TestPassphrase(vchSalt, SecureString(hash.begin(), hash.end()), rounds);
}
BOOST_AUTO_TEST_CASE(encrypt) {
std::vector<unsigned char> vchSalt = ParseHex("0000deadbeef0000");
BOOST_CHECK(vchSalt.size() == WALLET_CRYPTO_SALT_SIZE);
CCrypter crypt;
crypt.SetKeyFromPassphrase("passphrase", vchSalt, 25000, 0);
TestCrypter::TestEncrypt(crypt, ParseHex("22bcade09ac03ff6386914359cfe885cfeb5f77ff0d670f102f619687453b29d"));
for (int i = 0; i != 100; i++)
{
uint256 hash(GetRandHash());
TestCrypter::TestEncrypt(crypt, std::vector<unsigned char>(hash.begin(), hash.end()));
}
}
BOOST_AUTO_TEST_CASE(decrypt) {
std::vector<unsigned char> vchSalt = ParseHex("0000deadbeef0000");
BOOST_CHECK(vchSalt.size() == WALLET_CRYPTO_SALT_SIZE);
CCrypter crypt;
crypt.SetKeyFromPassphrase("passphrase", vchSalt, 25000, 0);
// Some corner cases the came up while testing
TestCrypter::TestDecrypt(crypt,ParseHex("795643ce39d736088367822cdc50535ec6f103715e3e48f4f3b1a60a08ef59ca"));
TestCrypter::TestDecrypt(crypt,ParseHex("de096f4a8f9bd97db012aa9d90d74de8cdea779c3ee8bc7633d8b5d6da703486"));
TestCrypter::TestDecrypt(crypt,ParseHex("32d0a8974e3afd9c6c3ebf4d66aa4e6419f8c173de25947f98cf8b7ace49449c"));
TestCrypter::TestDecrypt(crypt,ParseHex("e7c055cca2faa78cb9ac22c9357a90b4778ded9b2cc220a14cea49f931e596ea"));
TestCrypter::TestDecrypt(crypt,ParseHex("b88efddd668a6801d19516d6830da4ae9811988ccbaf40df8fbb72f3f4d335fd"));
TestCrypter::TestDecrypt(crypt,ParseHex("8cae76aa6a43694e961ebcb28c8ca8f8540b84153d72865e8561ddd93fa7bfa9"));
for (int i = 0; i != 100; i++)
{
uint256 hash(GetRandHash());
TestCrypter::TestDecrypt(crypt, std::vector<unsigned char>(hash.begin(), hash.end()));
}
}
BOOST_AUTO_TEST_SUITE_END()
| [
"support@vivuscoin.com"
] | support@vivuscoin.com |
d06975fda18b32b9a1c092f46a80e4eda75a0c5c | a6900da7d9fea94acf4b4f87492f93c9f43d99c9 | /game/testapp/inputcontroller.cpp | 5121de80ab9584b2991bd55e2c36f77bb13b934e | [] | no_license | akin666/bolt | a2433ac7f883db44f6f16de46a32a0fe93065364 | 84785c73d94dfb0a9106e3ac38c35e1a4fcfd5da | refs/heads/master | 2022-11-04T21:53:40.143858 | 2012-05-27T14:08:08 | 2012-05-27T14:08:08 | 276,093,947 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,407 | cpp | /*
* inputcontroller.cpp
*
* Created on: 9.2.2012
* Author: akin
*/
#include "inputcontroller.hpp"
#include <log>
InputController::InputController()
: bolt::Controller("inputcontroller" , false )
{
}
InputController::~InputController()
{
}
void InputController::initialize()
{
LOG_OUT << "Input init" << std::endl;
}
void InputController::getDependencies(bolt::StringSet & dep)
{
}
void InputController::attach(bolt::Entity & entity)
{
}
void InputController::detach(bolt::Entity & entity)
{
}
void InputController::start(bolt::ControllerNode & node)
{
// deliver input actions.. ?
}
void InputController::handleKeyboard(unsigned int key, float state)
{
LOG_OUT << "Input handleKeyboard " << key << " state " << state << std::endl;
}
void InputController::handleKeyboardCharacter(unsigned int key, float state)
{
LOG_OUT << "Input handleKeyboardCharacter " << key << " state " << state << std::endl;
}
void InputController::handleMouseMove(float x, float y)
{
LOG_OUT << "Input handleMouseMove x:" << x << " y:" << y << std::endl;
}
void InputController::handleMouseButton(bolt::Button button, float state)
{
LOG_OUT << "Input handleMouseButton " << button << " state " << state << std::endl;
}
void InputController::handleMouseWheel(float val)
{
LOG_OUT << "Input handleMouseWheel " << val << std::endl;
}
| [
"akin@localhost"
] | akin@localhost |
5f7fc905d9dca572c2704177ea150a34eaecb30a | e7473a998bb761b8e653abb94ae593bb0c0086e5 | /android/android_42/display/libgralloc/alloc_controller.cpp | e4d1d689dc19ce63c0d1cb4d6c0f829eeb8b94a2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | yakuizhao/intel-vaapi-driver | 27353904d4483d80d961b90e0cd9864168dd245f | b2bb0383352694941826543a171b557efac2219b | refs/heads/master | 2021-01-22T02:44:19.263890 | 2020-12-01T02:25:48 | 2020-12-01T02:26:50 | 81,062,952 | 0 | 0 | NOASSERTION | 2019-02-22T03:28:11 | 2017-02-06T08:05:28 | C | UTF-8 | C++ | false | false | 9,466 | cpp | /*
* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Code Aurora Forum, 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* 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.
*/
#include <cutils/log.h>
#include <fcntl.h>
#include "gralloc_priv.h"
#include "alloc_controller.h"
#include "memalloc.h"
#include "ionalloc.h"
#include "gr.h"
#include "comptype.h"
using namespace gralloc;
using namespace qdutils;
//Common functions
static bool canFallback(int usage, bool triedSystem)
{
// Fallback to system heap when alloc fails unless
// 1. Composition type is MDP
// 2. Alloc from system heap was already tried
// 3. The heap type is requsted explicitly
// 4. The heap type is protected
// 5. The buffer is meant for external display only
if(QCCompositionType::getInstance().getCompositionType() &
COMPOSITION_TYPE_MDP)
return false;
if(triedSystem)
return false;
if(usage & (GRALLOC_HEAP_MASK | GRALLOC_USAGE_PROTECTED |
GRALLOC_USAGE_PRIVATE_CP_BUFFER))
return false;
if(usage & (GRALLOC_HEAP_MASK | GRALLOC_USAGE_PRIVATE_EXTERNAL_ONLY))
return false;
//Return true by default
return true;
}
static bool useUncached(int usage)
{
// System heaps cannot be uncached
if(usage & (GRALLOC_USAGE_PRIVATE_SYSTEM_HEAP |
GRALLOC_USAGE_PRIVATE_IOMMU_HEAP))
return false;
if (usage & GRALLOC_USAGE_PRIVATE_UNCACHED)
return true;
return false;
}
IAllocController* IAllocController::sController = NULL;
IAllocController* IAllocController::getInstance(void)
{
if(sController == NULL) {
sController = new IonController();
}
return sController;
}
//-------------- IonController-----------------------//
IonController::IonController()
{
mIonAlloc = new IonAlloc();
}
int IonController::allocate(alloc_data& data, int usage)
{
int ionFlags = 0;
int ret;
bool noncontig = false;
data.uncached = useUncached(usage);
data.allocType = 0;
if(usage & GRALLOC_USAGE_PRIVATE_UI_CONTIG_HEAP)
ionFlags |= ION_HEAP(ION_SF_HEAP_ID);
if(usage & GRALLOC_USAGE_PRIVATE_SYSTEM_HEAP) {
ionFlags |= ION_HEAP(ION_SYSTEM_HEAP_ID);
noncontig = true;
}
if(usage & GRALLOC_USAGE_PRIVATE_IOMMU_HEAP)
ionFlags |= ION_HEAP(ION_IOMMU_HEAP_ID);
if(usage & GRALLOC_USAGE_PRIVATE_MM_HEAP)
ionFlags |= ION_HEAP(ION_CP_MM_HEAP_ID);
if(usage & GRALLOC_USAGE_PRIVATE_CAMERA_HEAP)
ionFlags |= ION_HEAP(ION_CAMERA_HEAP_ID);
if(usage & GRALLOC_USAGE_PRIVATE_CP_BUFFER)
ionFlags |= ION_SECURE;
// if no flags are set, default to
// SF + IOMMU heaps, so that bypass can work
// we can fall back to system heap if
// we run out.
if(!ionFlags)
ionFlags = ION_HEAP(ION_SF_HEAP_ID) | ION_HEAP(ION_IOMMU_HEAP_ID);
data.flags = ionFlags;
ret = mIonAlloc->alloc_buffer(data);
// Fallback
if(ret < 0 && canFallback(usage,
(ionFlags & ION_SYSTEM_HEAP_ID)))
{
ALOGW("Falling back to system heap");
data.flags = ION_HEAP(ION_SYSTEM_HEAP_ID);
noncontig = true;
ret = mIonAlloc->alloc_buffer(data);
}
if(ret >= 0 ) {
data.allocType |= private_handle_t::PRIV_FLAGS_USES_ION;
if(noncontig)
data.allocType |= private_handle_t::PRIV_FLAGS_NONCONTIGUOUS_MEM;
if(ionFlags & ION_SECURE)
data.allocType |= private_handle_t::PRIV_FLAGS_SECURE_BUFFER;
}
return ret;
}
IMemAlloc* IonController::getAllocator(int flags)
{
IMemAlloc* memalloc = NULL;
if (flags & private_handle_t::PRIV_FLAGS_USES_ION) {
memalloc = mIonAlloc;
} else {
ALOGE("%s: Invalid flags passed: 0x%x", __FUNCTION__, flags);
}
return memalloc;
}
size_t getBufferSizeAndDimensions(int width, int height, int format,
int& alignedw, int &alignedh)
{
size_t size;
alignedw = ALIGN(width, 32);
alignedh = ALIGN(height, 32);
switch (format) {
case HAL_PIXEL_FORMAT_RGBA_8888:
case HAL_PIXEL_FORMAT_RGBX_8888:
case HAL_PIXEL_FORMAT_BGRA_8888:
size = alignedw * alignedh * 4;
break;
case HAL_PIXEL_FORMAT_RGB_888:
size = alignedw * alignedh * 3;
break;
case HAL_PIXEL_FORMAT_RGB_565:
case HAL_PIXEL_FORMAT_RGBA_5551:
case HAL_PIXEL_FORMAT_RGBA_4444:
size = alignedw * alignedh * 2;
break;
// adreno formats
case HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO: // NV21
size = ALIGN(alignedw*alignedh, 4096);
size += ALIGN(2 * ALIGN(width/2, 32) * ALIGN(height/2, 32), 4096);
break;
case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED: // NV12
// The chroma plane is subsampled,
// but the pitch in bytes is unchanged
// The GPU needs 4K alignment, but the video decoder needs 8K
alignedw = ALIGN(width, 128);
size = ALIGN( alignedw * alignedh, 8192);
size += ALIGN( alignedw * ALIGN(height/2, 32), 8192);
break;
case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
case HAL_PIXEL_FORMAT_YCbCr_420_SP:
case HAL_PIXEL_FORMAT_YCrCb_420_SP:
case HAL_PIXEL_FORMAT_YV12:
if ((format == HAL_PIXEL_FORMAT_YV12) && ((width&1) || (height&1))) {
ALOGE("w or h is odd for the YV12 format");
return -EINVAL;
}
alignedw = ALIGN(width, 16);
alignedh = height;
if (HAL_PIXEL_FORMAT_NV12_ENCODEABLE == format) {
// The encoder requires a 2K aligned chroma offset.
size = ALIGN(alignedw*alignedh, 2048) +
(ALIGN(alignedw/2, 16) * (alignedh/2))*2;
} else {
size = alignedw*alignedh +
(ALIGN(alignedw/2, 16) * (alignedh/2))*2;
}
size = ALIGN(size, 4096);
break;
case HAL_PIXEL_FORMAT_YCbCr_422_SP:
case HAL_PIXEL_FORMAT_YCrCb_422_SP:
if(width & 1) {
ALOGE("width is odd for the YUV422_SP format");
return -EINVAL;
}
alignedw = ALIGN(width, 16);
alignedh = height;
size = ALIGN(alignedw * alignedh * 2, 4096);
break;
default:
ALOGE("unrecognized pixel format: 0x%x", format);
return -EINVAL;
}
return size;
}
// Allocate buffer from width, height and format into a
// private_handle_t. It is the responsibility of the caller
// to free the buffer using the free_buffer function
int alloc_buffer(private_handle_t **pHnd, int w, int h, int format, int usage)
{
alloc_data data;
int alignedw, alignedh;
gralloc::IAllocController* sAlloc =
gralloc::IAllocController::getInstance();
data.base = 0;
data.fd = -1;
data.offset = 0;
data.size = getBufferSizeAndDimensions(w, h, format, alignedw, alignedh);
data.align = getpagesize();
data.uncached = useUncached(usage);
int allocFlags = usage;
int err = sAlloc->allocate(data, allocFlags);
if (0 != err) {
ALOGE("%s: allocate failed", __FUNCTION__);
return -ENOMEM;
}
private_handle_t* hnd = new private_handle_t(data.fd, data.size,
data.allocType, 0, format,
alignedw, alignedh);
hnd->base = (int) data.base;
hnd->offset = data.offset;
hnd->gpuaddr = 0;
*pHnd = hnd;
return 0;
}
void free_buffer(private_handle_t *hnd)
{
gralloc::IAllocController* sAlloc =
gralloc::IAllocController::getInstance();
if (hnd && hnd->fd > 0) {
IMemAlloc* memalloc = sAlloc->getAllocator(hnd->flags);
memalloc->free_buffer((void*)hnd->base, hnd->size, hnd->offset, hnd->fd);
}
if(hnd)
delete hnd;
}
| [
"yakuizhao@tencent.com"
] | yakuizhao@tencent.com |
4d1a56ca5e1f17e1b69e4c83e29c10852ceaf3c7 | 4df1038d6511e221ac090f7113ca9cf741837edb | /week_07/day_4_RPG_GAME_2_refactor/Skeleton.cpp | 39b9bddbd81af914007ffce44c4ba5edf37169e0 | [] | no_license | greenfox-zerda-sparta/juliabaki | 86af6ef89b290cc968247e5dbe1dc7f57c8d357c | 82998e8105914375ed2927426d6b04f8fa280b38 | refs/heads/master | 2021-01-17T18:21:25.037633 | 2017-02-07T11:27:59 | 2017-02-07T11:27:59 | 71,350,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 259 | cpp | #include "Skeleton.h"
Skeleton::Skeleton() {
set_coordinates();
}
Skeleton::~Skeleton() {
}
void Skeleton::draw(GameContext& context) {
context.draw_sprite("skeleton.bmp", coordinate_x * 72, coordinate_y * 72);
}
void Skeleton::move(GameContext&) {
}
| [
"bakijulia@gmail.com"
] | bakijulia@gmail.com |
1c8eb9d656bbd953c03eb02483eb074fb79035bd | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /chrome/browser/chooser_controller/chooser_controller.cc | 45390379754de4b1aebe2da556905c6ee7f93b03 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 2,784 | cc | // 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.
#include "chrome/browser/chooser_controller/chooser_controller.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "components/url_formatter/elide_url.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/constants.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/origin.h"
namespace {
base::string16 CreateTitle(content::RenderFrameHost* render_frame_host,
int title_string_id_origin,
int title_string_id_extension) {
url::Origin origin = render_frame_host->GetLastCommittedOrigin();
if (origin.scheme() == extensions::kExtensionScheme) {
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
content::BrowserContext* browser_context =
web_contents->GetBrowserContext();
extensions::ExtensionRegistry* extension_registry =
extensions::ExtensionRegistry::Get(browser_context);
if (extension_registry) {
const extensions::Extension* extension =
extension_registry->enabled_extensions().GetByID(origin.host());
if (extension) {
return l10n_util::GetStringFUTF16(title_string_id_extension,
base::UTF8ToUTF16(extension->name()));
}
}
}
return l10n_util::GetStringFUTF16(
title_string_id_origin,
url_formatter::FormatOriginForSecurityDisplay(
origin, url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC));
}
} // namespace
ChooserController::ChooserController(content::RenderFrameHost* owner,
int title_string_id_origin,
int title_string_id_extension) {
if (owner) {
title_ =
CreateTitle(owner, title_string_id_origin, title_string_id_extension);
}
}
ChooserController::~ChooserController() {}
base::string16 ChooserController::GetTitle() const {
return title_;
}
bool ChooserController::ShouldShowIconBeforeText() const {
return false;
}
bool ChooserController::ShouldShowFootnoteView() const {
return true;
}
bool ChooserController::AllowMultipleSelection() const {
return false;
}
int ChooserController::GetSignalStrengthLevel(size_t index) const {
return -1;
}
bool ChooserController::IsConnected(size_t index) const {
return false;
}
bool ChooserController::IsPaired(size_t index) const {
return false;
}
void ChooserController::OpenAdapterOffHelpUrl() const {
NOTREACHED();
}
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
71235dda3cd9f27dd2821c43635a8d5ba5b0f0cf | 7e7037ec077e786c48aab7578405119560233e2f | /C++ small tasks/find HCF (GCD) of two numbers.cpp | f6b322970e9ffb70c5596511ae80900a671a9f3a | [] | no_license | MubarizKhan/CS217-Object-Oriented-Programming | 84f4de2f443a88c4e04cd2aa0b45f6ad9811f854 | ed23929adbade51ca8e82cc221322db14f827fcf | refs/heads/master | 2020-06-16T16:20:29.857100 | 2019-11-16T17:14:15 | 2019-11-16T17:14:15 | 195,634,475 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67 | cpp | #include <iostream>
using namespace std;
int main(){
}
| [
"noreply@github.com"
] | noreply@github.com |
6473320889ab2419a0630b0fe378c687d56d865d | d5514a7253720c93062e75c5307ab78ec6a17c47 | /cartArduino/read_server_parameters/read_server_parameters.ino | da7edfd848cf721cb4bf67e5051b672fefe23dbe | [] | no_license | seanxyuan/Arduino | 9b14b84660b97b85c5da4d6c3ad15001169f73c7 | 454f64c553448d3664ee1b1ef181257460bab373 | refs/heads/master | 2021-01-06T05:01:51.657972 | 2020-02-20T22:24:25 | 2020-02-20T22:24:25 | 241,218,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,837 | ino | //include ros packages
#include <ros.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
#include "Adafruit_HTU21DF.h"
#include <ros_essentials_cpp/Arduino_I.h>
#include <ros_essentials_cpp/Arduino_O.h>
#include <SoftwareSerial.h>
#include "RoboClaw.h"
SoftwareSerial serial(10,11);
RoboClaw roboclaw(&serial,10000);
//define arduino pins
int relay1 = 38; int relay1Error = 39; int relay2 = 40; int relay2Error = 41;
int relay3 = 42; int relay3Error = 43; int relay4 = 44; int relay4Error = 45;
int relay5 = 46; int relay5Error = 47; int relay6 = 48; int relay6Error = 49;
int relay7 = 50; int relay7Error = 51; int relay8 = 52; int relay8Error = 52;
int sensor1 = 28; int sensor2 = 29; int sensor3 = 30; int sensor4 = 31;
int sensor5 = 32; int sensor6 = 33; int sensor7 = 34; int sensor8 = 35;
int servo1 = 24; int servo2 = 25; int servo3 = 26; int servo4 = 27;
//define roboclaw parameters
#define address1 0x80
#define address2 0x81
//#define address3 0x82
//#define address4 0x83
//const float address1AP = 10;
//const float address1AI = 1;
//const float address1AD = 0.1;
//const float address1AQPPS = 100000;
//const float address1BP = 10;
//const float address1BI = 1;
//const float address1BD = 0.1;
//const float address1BQPPS = 100000;
//const float address2 = 0x81;
//const float address2AP = 10;
//const float address2AI = 1;
//const float address2AD = 0.1;
//const float address2AQPPS = 100000;
//const float address2BP = 10;
//const float address2BI = 1;
//const float address2BD = 0.1;
//const float address2BQPPS = 100000;
//define sensor parameters
int temperature = 0;
int humidity = 0;
int concreteTemperature = 0;
int accelXNozzle = 0;
int accelYNozzle = 0;
int accelZNozzle = 0;
int accelXCart = 0;
int accelYCart = 0;
int accelZCart = 0;
//initialize ROS
ros::NodeHandle nh;
ros_essentials_cpp::Arduino_I arduino_i;
ros_essentials_cpp::Arduino_O arduino_o;
ros::Publisher arduino_output("Arduino_Output_topic", &arduino_o);
//Set up IMU
uint16_t BNO055_SAMPLERATE_DELAY_MS = 1000;
Adafruit_BNO055 bno = Adafruit_BNO055(55);
//Set up BNO055 acceleration
double x = -1000000, y = -1000000 , z = -1000000; //dumb values, easy to spot problem
double sum = -1000000; //sum value
double maxAccel = -100000;
void printEvent(sensors_event_t* event) {
double x = -1000000, y = -1000000 , z = -1000000; //dumb values, easy to spot problem
double sum = -1000000; //sum value
if (event->type == SENSOR_TYPE_ACCELEROMETER) {
x = event->acceleration.x;
y = event->acceleration.y;
z = event->acceleration.z;
sum = sqrt(x*x + y*y + z*z);
}
if (sum > maxAccel) maxAccel = sum;
}
//Set up temperature and humidity sensor
Adafruit_HTU21DF htu = Adafruit_HTU21DF();
//arduino subscribe message input
void messageArduino_I( const ros_essentials_cpp::Arduino_I &arduino_i_msg){
digitalWrite(relay1,arduino_i_msg.relay1); digitalWrite(relay2,arduino_i_msg.relay2);
digitalWrite(relay3,arduino_i_msg.relay3); digitalWrite(relay4,arduino_i_msg.relay4);
digitalWrite(relay5,arduino_i_msg.relay5); digitalWrite(relay6,arduino_i_msg.relay6);
digitalWrite(relay7,arduino_i_msg.relay7); digitalWrite(relay8,arduino_i_msg.relay8);
digitalWrite(servo1,arduino_i_msg.RCServo1); digitalWrite(servo2,arduino_i_msg.RCServo2);
digitalWrite(servo3,arduino_i_msg.RCServo3); digitalWrite(servo4,arduino_i_msg.RCServo4);
}
void update_sensor(){
arduino_o.relay1Error = random(2); arduino_o.relay2Error = random(2);
arduino_o.relay3Error = random(2); arduino_o.relay4Error = random(2);
arduino_o.relay5Error = random(2); arduino_o.relay6Error = random(2);
arduino_o.relay7Error = random(2); arduino_o.relay8Error = random(2);
arduino_o.sensor1 = random(2); arduino_o.sensor2 = random(2);
arduino_o.sensor3 = random(2); arduino_o.sensor4 = random(2);
arduino_o.sensor5 = random(2); arduino_o.sensor6 = random(2);
arduino_o.sensor7 = random(2); arduino_o.sensor8 = random(2);
arduino_o.temperature = random(100); arduino_o.humidity = random(100);
arduino_o.windSpeed = random(100); arduino_o.concreteTemperature = random(100);
arduino_o.accelXNozzle = random(1000); arduino_o.accelYNozzle = random(1000); arduino_o.accelZNozzle = random(1000);
arduino_o.accelXCart = random(1000); arduino_o.accelYCart = random(1000); arduino_o.accelZCart = random(1000);
}
//initialize subscriber
ros::Subscriber<ros_essentials_cpp::Arduino_I> sub("Arduino_Input_topic", &messageArduino_I );
//system setup
void setup()
{
pinMode(relay1, OUTPUT); pinMode(relay2, OUTPUT); pinMode(relay3, OUTPUT); pinMode(relay4, OUTPUT);
pinMode(relay5, OUTPUT); pinMode(relay6, OUTPUT); pinMode(relay7, OUTPUT); pinMode(relay8, OUTPUT);
pinMode(servo1, OUTPUT); pinMode(servo2, OUTPUT); pinMode(servo3, OUTPUT); pinMode(servo4, OUTPUT);
pinMode(relay1Error, INPUT); pinMode(relay2Error, INPUT); pinMode(relay3Error, INPUT); pinMode(relay4Error, INPUT);
pinMode(relay5Error, INPUT); pinMode(relay6Error, INPUT); pinMode(relay7Error, INPUT); pinMode(relay8Error, INPUT);
pinMode(sensor1, INPUT); pinMode(sensor2, INPUT); pinMode(sensor3, INPUT); pinMode(sensor4, INPUT);
pinMode(sensor5, INPUT); pinMode(sensor6, INPUT); pinMode(sensor7, INPUT); pinMode(sensor8, INPUT);
nh.initNode();
nh.subscribe(sub);
nh.advertise(arduino_output);
roboclaw.begin(38400);
}
void loop()
{
float temp = htu.readTemperature();
float rel_hum = htu.readHumidity();
//could add VECTOR_ACCELEROMETER, VECTOR_MAGNETOMETER,VECTOR_GRAVITY...
sensors_event_t linearAccelData;
bno.getEvent(&linearAccelData, Adafruit_BNO055::VECTOR_LINEARACCEL);
printEvent(&linearAccelData);
update_sensor();
arduino_output.publish( &arduino_o );
delay(50); //refresh every 50 ms
nh.spinOnce();
}
| [
"seanxyuan@gmail.com"
] | seanxyuan@gmail.com |
35c728166e95ec8309d69edfa82718496fff8c1b | c48e0bbf12e7528f4f188fd27f26d5e12acb6157 | /src/s390/code-stubs-s390.cc | 18af0387d5287140bc9fcb5294652986f216ce6c | [
"BSD-3-Clause",
"bzip2-1.0.6"
] | permissive | theharithsa/v8 | b4576a8b26a00fc146ef3dba086c28b982c00b83 | 6ebf9fbb93d31f9be41156a3325d58704ed4933d | refs/heads/master | 2021-05-31T17:39:45.678975 | 2016-04-08T15:29:42 | 2016-04-08T15:31:15 | 55,805,573 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 207,218 | cc | // Copyright 2014 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.
#if V8_TARGET_ARCH_S390
#include "src/code-stubs.h"
#include "src/api-arguments.h"
#include "src/base/bits.h"
#include "src/bootstrapper.h"
#include "src/codegen.h"
#include "src/ic/handler-compiler.h"
#include "src/ic/ic.h"
#include "src/ic/stub-cache.h"
#include "src/isolate.h"
#include "src/regexp/jsregexp.h"
#include "src/regexp/regexp-macro-assembler.h"
#include "src/runtime/runtime.h"
#include "src/s390/code-stubs-s390.h"
namespace v8 {
namespace internal {
static void InitializeArrayConstructorDescriptor(
Isolate* isolate, CodeStubDescriptor* descriptor,
int constant_stack_parameter_count) {
Address deopt_handler =
Runtime::FunctionForId(Runtime::kArrayConstructor)->entry;
if (constant_stack_parameter_count == 0) {
descriptor->Initialize(deopt_handler, constant_stack_parameter_count,
JS_FUNCTION_STUB_MODE);
} else {
descriptor->Initialize(r2, deopt_handler, constant_stack_parameter_count,
JS_FUNCTION_STUB_MODE);
}
}
static void InitializeInternalArrayConstructorDescriptor(
Isolate* isolate, CodeStubDescriptor* descriptor,
int constant_stack_parameter_count) {
Address deopt_handler =
Runtime::FunctionForId(Runtime::kInternalArrayConstructor)->entry;
if (constant_stack_parameter_count == 0) {
descriptor->Initialize(deopt_handler, constant_stack_parameter_count,
JS_FUNCTION_STUB_MODE);
} else {
descriptor->Initialize(r2, deopt_handler, constant_stack_parameter_count,
JS_FUNCTION_STUB_MODE);
}
}
void ArrayNoArgumentConstructorStub::InitializeDescriptor(
CodeStubDescriptor* descriptor) {
InitializeArrayConstructorDescriptor(isolate(), descriptor, 0);
}
void ArraySingleArgumentConstructorStub::InitializeDescriptor(
CodeStubDescriptor* descriptor) {
InitializeArrayConstructorDescriptor(isolate(), descriptor, 1);
}
void ArrayNArgumentsConstructorStub::InitializeDescriptor(
CodeStubDescriptor* descriptor) {
InitializeArrayConstructorDescriptor(isolate(), descriptor, -1);
}
void InternalArrayNoArgumentConstructorStub::InitializeDescriptor(
CodeStubDescriptor* descriptor) {
InitializeInternalArrayConstructorDescriptor(isolate(), descriptor, 0);
}
void FastArrayPushStub::InitializeDescriptor(CodeStubDescriptor* descriptor) {
Address deopt_handler = Runtime::FunctionForId(Runtime::kArrayPush)->entry;
descriptor->Initialize(r2, deopt_handler, -1, JS_FUNCTION_STUB_MODE);
}
void InternalArraySingleArgumentConstructorStub::InitializeDescriptor(
CodeStubDescriptor* descriptor) {
InitializeInternalArrayConstructorDescriptor(isolate(), descriptor, 1);
}
void InternalArrayNArgumentsConstructorStub::InitializeDescriptor(
CodeStubDescriptor* descriptor) {
InitializeInternalArrayConstructorDescriptor(isolate(), descriptor, -1);
}
#define __ ACCESS_MASM(masm)
static void EmitIdenticalObjectComparison(MacroAssembler* masm, Label* slow,
Condition cond);
static void EmitSmiNonsmiComparison(MacroAssembler* masm, Register lhs,
Register rhs, Label* lhs_not_nan,
Label* slow, bool strict);
static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm, Register lhs,
Register rhs);
void HydrogenCodeStub::GenerateLightweightMiss(MacroAssembler* masm,
ExternalReference miss) {
// Update the static counter each time a new code stub is generated.
isolate()->counters()->code_stubs()->Increment();
CallInterfaceDescriptor descriptor = GetCallInterfaceDescriptor();
int param_count = descriptor.GetRegisterParameterCount();
{
// Call the runtime system in a fresh internal frame.
FrameScope scope(masm, StackFrame::INTERNAL);
DCHECK(param_count == 0 ||
r2.is(descriptor.GetRegisterParameter(param_count - 1)));
// Push arguments
for (int i = 0; i < param_count; ++i) {
__ push(descriptor.GetRegisterParameter(i));
}
__ CallExternalReference(miss, param_count);
}
__ Ret();
}
void DoubleToIStub::Generate(MacroAssembler* masm) {
Label out_of_range, only_low, negate, done, fastpath_done;
Register input_reg = source();
Register result_reg = destination();
DCHECK(is_truncating());
int double_offset = offset();
// Immediate values for this stub fit in instructions, so it's safe to use ip.
Register scratch = GetRegisterThatIsNotOneOf(input_reg, result_reg);
Register scratch_low =
GetRegisterThatIsNotOneOf(input_reg, result_reg, scratch);
Register scratch_high =
GetRegisterThatIsNotOneOf(input_reg, result_reg, scratch, scratch_low);
DoubleRegister double_scratch = kScratchDoubleReg;
__ push(scratch);
// Account for saved regs if input is sp.
if (input_reg.is(sp)) double_offset += kPointerSize;
if (!skip_fastpath()) {
// Load double input.
__ LoadDouble(double_scratch, MemOperand(input_reg, double_offset));
// Do fast-path convert from double to int.
__ ConvertDoubleToInt64(double_scratch,
#if !V8_TARGET_ARCH_S390X
scratch,
#endif
result_reg, d0);
// Test for overflow
#if V8_TARGET_ARCH_S390X
__ TestIfInt32(result_reg, r0);
#else
__ TestIfInt32(scratch, result_reg, r0);
#endif
__ beq(&fastpath_done, Label::kNear);
}
__ Push(scratch_high, scratch_low);
// Account for saved regs if input is sp.
if (input_reg.is(sp)) double_offset += 2 * kPointerSize;
__ LoadlW(scratch_high,
MemOperand(input_reg, double_offset + Register::kExponentOffset));
__ LoadlW(scratch_low,
MemOperand(input_reg, double_offset + Register::kMantissaOffset));
__ ExtractBitMask(scratch, scratch_high, HeapNumber::kExponentMask);
// Load scratch with exponent - 1. This is faster than loading
// with exponent because Bias + 1 = 1024 which is a *S390* immediate value.
STATIC_ASSERT(HeapNumber::kExponentBias + 1 == 1024);
__ SubP(scratch, Operand(HeapNumber::kExponentBias + 1));
// If exponent is greater than or equal to 84, the 32 less significant
// bits are 0s (2^84 = 1, 52 significant bits, 32 uncoded bits),
// the result is 0.
// Compare exponent with 84 (compare exponent - 1 with 83).
__ CmpP(scratch, Operand(83));
__ bge(&out_of_range, Label::kNear);
// If we reach this code, 31 <= exponent <= 83.
// So, we don't have to handle cases where 0 <= exponent <= 20 for
// which we would need to shift right the high part of the mantissa.
// Scratch contains exponent - 1.
// Load scratch with 52 - exponent (load with 51 - (exponent - 1)).
__ Load(r0, Operand(51));
__ SubP(scratch, r0, scratch);
__ CmpP(scratch, Operand::Zero());
__ ble(&only_low, Label::kNear);
// 21 <= exponent <= 51, shift scratch_low and scratch_high
// to generate the result.
__ ShiftRight(scratch_low, scratch_low, scratch);
// Scratch contains: 52 - exponent.
// We needs: exponent - 20.
// So we use: 32 - scratch = 32 - 52 + exponent = exponent - 20.
__ Load(r0, Operand(32));
__ SubP(scratch, r0, scratch);
__ ExtractBitMask(result_reg, scratch_high, HeapNumber::kMantissaMask);
// Set the implicit 1 before the mantissa part in scratch_high.
STATIC_ASSERT(HeapNumber::kMantissaBitsInTopWord >= 16);
__ Load(r0, Operand(1 << ((HeapNumber::kMantissaBitsInTopWord)-16)));
__ ShiftLeftP(r0, r0, Operand(16));
__ OrP(result_reg, result_reg, r0);
__ ShiftLeft(r0, result_reg, scratch);
__ OrP(result_reg, scratch_low, r0);
__ b(&negate, Label::kNear);
__ bind(&out_of_range);
__ mov(result_reg, Operand::Zero());
__ b(&done, Label::kNear);
__ bind(&only_low);
// 52 <= exponent <= 83, shift only scratch_low.
// On entry, scratch contains: 52 - exponent.
__ LoadComplementRR(scratch, scratch);
__ ShiftLeft(result_reg, scratch_low, scratch);
__ bind(&negate);
// If input was positive, scratch_high ASR 31 equals 0 and
// scratch_high LSR 31 equals zero.
// New result = (result eor 0) + 0 = result.
// If the input was negative, we have to negate the result.
// Input_high ASR 31 equals 0xffffffff and scratch_high LSR 31 equals 1.
// New result = (result eor 0xffffffff) + 1 = 0 - result.
__ ShiftRightArith(r0, scratch_high, Operand(31));
#if V8_TARGET_ARCH_S390X
__ lgfr(r0, r0);
__ ShiftRightP(r0, r0, Operand(32));
#endif
__ XorP(result_reg, r0);
__ ShiftRight(r0, scratch_high, Operand(31));
__ AddP(result_reg, r0);
__ bind(&done);
__ Pop(scratch_high, scratch_low);
__ bind(&fastpath_done);
__ pop(scratch);
__ Ret();
}
// Handle the case where the lhs and rhs are the same object.
// Equality is almost reflexive (everything but NaN), so this is a test
// for "identity and not NaN".
static void EmitIdenticalObjectComparison(MacroAssembler* masm, Label* slow,
Condition cond) {
Label not_identical;
Label heap_number, return_equal;
__ CmpP(r2, r3);
__ bne(¬_identical);
// Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
// so we do the second best thing - test it ourselves.
// They are both equal and they are not both Smis so both of them are not
// Smis. If it's not a heap number, then return equal.
if (cond == lt || cond == gt) {
// Call runtime on identical JSObjects.
__ CompareObjectType(r2, r6, r6, FIRST_JS_RECEIVER_TYPE);
__ bge(slow);
// Call runtime on identical symbols since we need to throw a TypeError.
__ CmpP(r6, Operand(SYMBOL_TYPE));
__ beq(slow);
// Call runtime on identical SIMD values since we must throw a TypeError.
__ CmpP(r6, Operand(SIMD128_VALUE_TYPE));
__ beq(slow);
} else {
__ CompareObjectType(r2, r6, r6, HEAP_NUMBER_TYPE);
__ beq(&heap_number);
// Comparing JS objects with <=, >= is complicated.
if (cond != eq) {
__ CmpP(r6, Operand(FIRST_JS_RECEIVER_TYPE));
__ bge(slow);
// Call runtime on identical symbols since we need to throw a TypeError.
__ CmpP(r6, Operand(SYMBOL_TYPE));
__ beq(slow);
// Call runtime on identical SIMD values since we must throw a TypeError.
__ CmpP(r6, Operand(SIMD128_VALUE_TYPE));
__ beq(slow);
// Normally here we fall through to return_equal, but undefined is
// special: (undefined == undefined) == true, but
// (undefined <= undefined) == false! See ECMAScript 11.8.5.
if (cond == le || cond == ge) {
__ CmpP(r6, Operand(ODDBALL_TYPE));
__ bne(&return_equal);
__ CompareRoot(r2, Heap::kUndefinedValueRootIndex);
__ bne(&return_equal);
if (cond == le) {
// undefined <= undefined should fail.
__ LoadImmP(r2, Operand(GREATER));
} else {
// undefined >= undefined should fail.
__ LoadImmP(r2, Operand(LESS));
}
__ Ret();
}
}
}
__ bind(&return_equal);
if (cond == lt) {
__ LoadImmP(r2, Operand(GREATER)); // Things aren't less than themselves.
} else if (cond == gt) {
__ LoadImmP(r2, Operand(LESS)); // Things aren't greater than themselves.
} else {
__ LoadImmP(r2, Operand(EQUAL)); // Things are <=, >=, ==, === themselves
}
__ Ret();
// For less and greater we don't have to check for NaN since the result of
// x < x is false regardless. For the others here is some code to check
// for NaN.
if (cond != lt && cond != gt) {
__ bind(&heap_number);
// It is a heap number, so return non-equal if it's NaN and equal if it's
// not NaN.
// The representation of NaN values has all exponent bits (52..62) set,
// and not all mantissa bits (0..51) clear.
// Read top bits of double representation (second word of value).
__ LoadlW(r4, FieldMemOperand(r2, HeapNumber::kExponentOffset));
// Test that exponent bits are all set.
STATIC_ASSERT(HeapNumber::kExponentMask == 0x7ff00000u);
__ ExtractBitMask(r5, r4, HeapNumber::kExponentMask);
__ CmpLogicalP(r5, Operand(0x7ff));
__ bne(&return_equal);
// Shift out flag and all exponent bits, retaining only mantissa.
__ sll(r4, Operand(HeapNumber::kNonMantissaBitsInTopWord));
// Or with all low-bits of mantissa.
__ LoadlW(r5, FieldMemOperand(r2, HeapNumber::kMantissaOffset));
__ OrP(r2, r5, r4);
__ CmpP(r2, Operand::Zero());
// For equal we already have the right value in r2: Return zero (equal)
// if all bits in mantissa are zero (it's an Infinity) and non-zero if
// not (it's a NaN). For <= and >= we need to load r0 with the failing
// value if it's a NaN.
if (cond != eq) {
Label not_equal;
__ bne(¬_equal, Label::kNear);
// All-zero means Infinity means equal.
__ Ret();
__ bind(¬_equal);
if (cond == le) {
__ LoadImmP(r2, Operand(GREATER)); // NaN <= NaN should fail.
} else {
__ LoadImmP(r2, Operand(LESS)); // NaN >= NaN should fail.
}
}
__ Ret();
}
// No fall through here.
__ bind(¬_identical);
}
// See comment at call site.
static void EmitSmiNonsmiComparison(MacroAssembler* masm, Register lhs,
Register rhs, Label* lhs_not_nan,
Label* slow, bool strict) {
DCHECK((lhs.is(r2) && rhs.is(r3)) || (lhs.is(r3) && rhs.is(r2)));
Label rhs_is_smi;
__ JumpIfSmi(rhs, &rhs_is_smi);
// Lhs is a Smi. Check whether the rhs is a heap number.
__ CompareObjectType(rhs, r5, r6, HEAP_NUMBER_TYPE);
if (strict) {
// If rhs is not a number and lhs is a Smi then strict equality cannot
// succeed. Return non-equal
// If rhs is r2 then there is already a non zero value in it.
Label skip;
__ beq(&skip, Label::kNear);
if (!rhs.is(r2)) {
__ mov(r2, Operand(NOT_EQUAL));
}
__ Ret();
__ bind(&skip);
} else {
// Smi compared non-strictly with a non-Smi non-heap-number. Call
// the runtime.
__ bne(slow);
}
// Lhs is a smi, rhs is a number.
// Convert lhs to a double in d7.
__ SmiToDouble(d7, lhs);
// Load the double from rhs, tagged HeapNumber r2, to d6.
__ LoadDouble(d6, FieldMemOperand(rhs, HeapNumber::kValueOffset));
// We now have both loaded as doubles but we can skip the lhs nan check
// since it's a smi.
__ b(lhs_not_nan);
__ bind(&rhs_is_smi);
// Rhs is a smi. Check whether the non-smi lhs is a heap number.
__ CompareObjectType(lhs, r6, r6, HEAP_NUMBER_TYPE);
if (strict) {
// If lhs is not a number and rhs is a smi then strict equality cannot
// succeed. Return non-equal.
// If lhs is r2 then there is already a non zero value in it.
Label skip;
__ beq(&skip, Label::kNear);
if (!lhs.is(r2)) {
__ mov(r2, Operand(NOT_EQUAL));
}
__ Ret();
__ bind(&skip);
} else {
// Smi compared non-strictly with a non-smi non-heap-number. Call
// the runtime.
__ bne(slow);
}
// Rhs is a smi, lhs is a heap number.
// Load the double from lhs, tagged HeapNumber r3, to d7.
__ LoadDouble(d7, FieldMemOperand(lhs, HeapNumber::kValueOffset));
// Convert rhs to a double in d6.
__ SmiToDouble(d6, rhs);
// Fall through to both_loaded_as_doubles.
}
// See comment at call site.
static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm, Register lhs,
Register rhs) {
DCHECK((lhs.is(r2) && rhs.is(r3)) || (lhs.is(r3) && rhs.is(r2)));
// If either operand is a JS object or an oddball value, then they are
// not equal since their pointers are different.
// There is no test for undetectability in strict equality.
STATIC_ASSERT(LAST_TYPE == LAST_JS_RECEIVER_TYPE);
Label first_non_object;
// Get the type of the first operand into r4 and compare it with
// FIRST_JS_RECEIVER_TYPE.
__ CompareObjectType(rhs, r4, r4, FIRST_JS_RECEIVER_TYPE);
__ blt(&first_non_object, Label::kNear);
// Return non-zero (r2 is not zero)
Label return_not_equal;
__ bind(&return_not_equal);
__ Ret();
__ bind(&first_non_object);
// Check for oddballs: true, false, null, undefined.
__ CmpP(r4, Operand(ODDBALL_TYPE));
__ beq(&return_not_equal);
__ CompareObjectType(lhs, r5, r5, FIRST_JS_RECEIVER_TYPE);
__ bge(&return_not_equal);
// Check for oddballs: true, false, null, undefined.
__ CmpP(r5, Operand(ODDBALL_TYPE));
__ beq(&return_not_equal);
// Now that we have the types we might as well check for
// internalized-internalized.
STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
__ OrP(r4, r4, r5);
__ AndP(r0, r4, Operand(kIsNotStringMask | kIsNotInternalizedMask));
__ beq(&return_not_equal);
}
// See comment at call site.
static void EmitCheckForTwoHeapNumbers(MacroAssembler* masm, Register lhs,
Register rhs,
Label* both_loaded_as_doubles,
Label* not_heap_numbers, Label* slow) {
DCHECK((lhs.is(r2) && rhs.is(r3)) || (lhs.is(r3) && rhs.is(r2)));
__ CompareObjectType(rhs, r5, r4, HEAP_NUMBER_TYPE);
__ bne(not_heap_numbers);
__ LoadP(r4, FieldMemOperand(lhs, HeapObject::kMapOffset));
__ CmpP(r4, r5);
__ bne(slow); // First was a heap number, second wasn't. Go slow case.
// Both are heap numbers. Load them up then jump to the code we have
// for that.
__ LoadDouble(d6, FieldMemOperand(rhs, HeapNumber::kValueOffset));
__ LoadDouble(d7, FieldMemOperand(lhs, HeapNumber::kValueOffset));
__ b(both_loaded_as_doubles);
}
// Fast negative check for internalized-to-internalized equality or receiver
// equality. Also handles the undetectable receiver to null/undefined
// comparison.
static void EmitCheckForInternalizedStringsOrObjects(MacroAssembler* masm,
Register lhs, Register rhs,
Label* possible_strings,
Label* runtime_call) {
DCHECK((lhs.is(r2) && rhs.is(r3)) || (lhs.is(r3) && rhs.is(r2)));
// r4 is object type of rhs.
Label object_test, return_equal, return_unequal, undetectable;
STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
__ mov(r0, Operand(kIsNotStringMask));
__ AndP(r0, r4);
__ bne(&object_test, Label::kNear);
__ mov(r0, Operand(kIsNotInternalizedMask));
__ AndP(r0, r4);
__ bne(possible_strings);
__ CompareObjectType(lhs, r5, r5, FIRST_NONSTRING_TYPE);
__ bge(runtime_call);
__ mov(r0, Operand(kIsNotInternalizedMask));
__ AndP(r0, r5);
__ bne(possible_strings);
// Both are internalized. We already checked they weren't the same pointer so
// they are not equal. Return non-equal by returning the non-zero object
// pointer in r2.
__ Ret();
__ bind(&object_test);
__ LoadP(r4, FieldMemOperand(lhs, HeapObject::kMapOffset));
__ LoadP(r5, FieldMemOperand(rhs, HeapObject::kMapOffset));
__ LoadlB(r6, FieldMemOperand(r4, Map::kBitFieldOffset));
__ LoadlB(r7, FieldMemOperand(r5, Map::kBitFieldOffset));
__ AndP(r0, r6, Operand(1 << Map::kIsUndetectable));
__ bne(&undetectable);
__ AndP(r0, r7, Operand(1 << Map::kIsUndetectable));
__ bne(&return_unequal);
__ CompareInstanceType(r4, r4, FIRST_JS_RECEIVER_TYPE);
__ blt(runtime_call);
__ CompareInstanceType(r5, r5, FIRST_JS_RECEIVER_TYPE);
__ blt(runtime_call);
__ bind(&return_unequal);
// Return non-equal by returning the non-zero object pointer in r2.
__ Ret();
__ bind(&undetectable);
__ AndP(r0, r7, Operand(1 << Map::kIsUndetectable));
__ beq(&return_unequal);
// If both sides are JSReceivers, then the result is false according to
// the HTML specification, which says that only comparisons with null or
// undefined are affected by special casing for document.all.
__ CompareInstanceType(r4, r4, ODDBALL_TYPE);
__ beq(&return_equal);
__ CompareInstanceType(r5, r5, ODDBALL_TYPE);
__ bne(&return_unequal);
__ bind(&return_equal);
__ LoadImmP(r2, Operand(EQUAL));
__ Ret();
}
static void CompareICStub_CheckInputType(MacroAssembler* masm, Register input,
Register scratch,
CompareICState::State expected,
Label* fail) {
Label ok;
if (expected == CompareICState::SMI) {
__ JumpIfNotSmi(input, fail);
} else if (expected == CompareICState::NUMBER) {
__ JumpIfSmi(input, &ok);
__ CheckMap(input, scratch, Heap::kHeapNumberMapRootIndex, fail,
DONT_DO_SMI_CHECK);
}
// We could be strict about internalized/non-internalized here, but as long as
// hydrogen doesn't care, the stub doesn't have to care either.
__ bind(&ok);
}
// On entry r3 and r4 are the values to be compared.
// On exit r2 is 0, positive or negative to indicate the result of
// the comparison.
void CompareICStub::GenerateGeneric(MacroAssembler* masm) {
Register lhs = r3;
Register rhs = r2;
Condition cc = GetCondition();
Label miss;
CompareICStub_CheckInputType(masm, lhs, r4, left(), &miss);
CompareICStub_CheckInputType(masm, rhs, r5, right(), &miss);
Label slow; // Call builtin.
Label not_smis, both_loaded_as_doubles, lhs_not_nan;
Label not_two_smis, smi_done;
__ OrP(r4, r3, r2);
__ JumpIfNotSmi(r4, ¬_two_smis);
__ SmiUntag(r3);
__ SmiUntag(r2);
__ SubP(r2, r3, r2);
__ Ret();
__ bind(¬_two_smis);
// NOTICE! This code is only reached after a smi-fast-case check, so
// it is certain that at least one operand isn't a smi.
// Handle the case where the objects are identical. Either returns the answer
// or goes to slow. Only falls through if the objects were not identical.
EmitIdenticalObjectComparison(masm, &slow, cc);
// If either is a Smi (we know that not both are), then they can only
// be strictly equal if the other is a HeapNumber.
STATIC_ASSERT(kSmiTag == 0);
DCHECK_EQ(static_cast<Smi*>(0), Smi::FromInt(0));
__ AndP(r4, lhs, rhs);
__ JumpIfNotSmi(r4, ¬_smis);
// One operand is a smi. EmitSmiNonsmiComparison generates code that can:
// 1) Return the answer.
// 2) Go to slow.
// 3) Fall through to both_loaded_as_doubles.
// 4) Jump to lhs_not_nan.
// In cases 3 and 4 we have found out we were dealing with a number-number
// comparison. The double values of the numbers have been loaded
// into d7 and d6.
EmitSmiNonsmiComparison(masm, lhs, rhs, &lhs_not_nan, &slow, strict());
__ bind(&both_loaded_as_doubles);
// The arguments have been converted to doubles and stored in d6 and d7
__ bind(&lhs_not_nan);
Label no_nan;
__ cdbr(d7, d6);
Label nan, equal, less_than;
__ bunordered(&nan);
__ beq(&equal, Label::kNear);
__ blt(&less_than, Label::kNear);
__ LoadImmP(r2, Operand(GREATER));
__ Ret();
__ bind(&equal);
__ LoadImmP(r2, Operand(EQUAL));
__ Ret();
__ bind(&less_than);
__ LoadImmP(r2, Operand(LESS));
__ Ret();
__ bind(&nan);
// If one of the sides was a NaN then the v flag is set. Load r2 with
// whatever it takes to make the comparison fail, since comparisons with NaN
// always fail.
if (cc == lt || cc == le) {
__ LoadImmP(r2, Operand(GREATER));
} else {
__ LoadImmP(r2, Operand(LESS));
}
__ Ret();
__ bind(¬_smis);
// At this point we know we are dealing with two different objects,
// and neither of them is a Smi. The objects are in rhs_ and lhs_.
if (strict()) {
// This returns non-equal for some object types, or falls through if it
// was not lucky.
EmitStrictTwoHeapObjectCompare(masm, lhs, rhs);
}
Label check_for_internalized_strings;
Label flat_string_check;
// Check for heap-number-heap-number comparison. Can jump to slow case,
// or load both doubles into r2, r3, r4, r5 and jump to the code that handles
// that case. If the inputs are not doubles then jumps to
// check_for_internalized_strings.
// In this case r4 will contain the type of rhs_. Never falls through.
EmitCheckForTwoHeapNumbers(masm, lhs, rhs, &both_loaded_as_doubles,
&check_for_internalized_strings,
&flat_string_check);
__ bind(&check_for_internalized_strings);
// In the strict case the EmitStrictTwoHeapObjectCompare already took care of
// internalized strings.
if (cc == eq && !strict()) {
// Returns an answer for two internalized strings or two detectable objects.
// Otherwise jumps to string case or not both strings case.
// Assumes that r4 is the type of rhs_ on entry.
EmitCheckForInternalizedStringsOrObjects(masm, lhs, rhs, &flat_string_check,
&slow);
}
// Check for both being sequential one-byte strings,
// and inline if that is the case.
__ bind(&flat_string_check);
__ JumpIfNonSmisNotBothSequentialOneByteStrings(lhs, rhs, r4, r5, &slow);
__ IncrementCounter(isolate()->counters()->string_compare_native(), 1, r4,
r5);
if (cc == eq) {
StringHelper::GenerateFlatOneByteStringEquals(masm, lhs, rhs, r4, r5);
} else {
StringHelper::GenerateCompareFlatOneByteStrings(masm, lhs, rhs, r4, r5, r6);
}
// Never falls through to here.
__ bind(&slow);
if (cc == eq) {
{
FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
__ Push(lhs, rhs);
__ CallRuntime(strict() ? Runtime::kStrictEqual : Runtime::kEqual);
}
// Turn true into 0 and false into some non-zero value.
STATIC_ASSERT(EQUAL == 0);
__ LoadRoot(r3, Heap::kTrueValueRootIndex);
__ SubP(r2, r2, r3);
__ Ret();
} else {
__ Push(lhs, rhs);
int ncr; // NaN compare result
if (cc == lt || cc == le) {
ncr = GREATER;
} else {
DCHECK(cc == gt || cc == ge); // remaining cases
ncr = LESS;
}
__ LoadSmiLiteral(r2, Smi::FromInt(ncr));
__ push(r2);
// Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
// tagged as a small integer.
__ TailCallRuntime(Runtime::kCompare);
}
__ bind(&miss);
GenerateMiss(masm);
}
void StoreBufferOverflowStub::Generate(MacroAssembler* masm) {
// We don't allow a GC during a store buffer overflow so there is no need to
// store the registers in any particular way, but we do have to store and
// restore them.
__ MultiPush(kJSCallerSaved | r14.bit());
if (save_doubles()) {
__ MultiPushDoubles(kCallerSavedDoubles);
}
const int argument_count = 1;
const int fp_argument_count = 0;
const Register scratch = r3;
AllowExternalCallThatCantCauseGC scope(masm);
__ PrepareCallCFunction(argument_count, fp_argument_count, scratch);
__ mov(r2, Operand(ExternalReference::isolate_address(isolate())));
__ CallCFunction(ExternalReference::store_buffer_overflow_function(isolate()),
argument_count);
if (save_doubles()) {
__ MultiPopDoubles(kCallerSavedDoubles);
}
__ MultiPop(kJSCallerSaved | r14.bit());
__ Ret();
}
void StoreRegistersStateStub::Generate(MacroAssembler* masm) {
__ PushSafepointRegisters();
__ b(r14);
}
void RestoreRegistersStateStub::Generate(MacroAssembler* masm) {
__ PopSafepointRegisters();
__ b(r14);
}
void MathPowStub::Generate(MacroAssembler* masm) {
const Register base = r3;
const Register exponent = MathPowTaggedDescriptor::exponent();
DCHECK(exponent.is(r4));
const Register heapnumbermap = r7;
const Register heapnumber = r2;
const DoubleRegister double_base = d1;
const DoubleRegister double_exponent = d2;
const DoubleRegister double_result = d3;
const DoubleRegister double_scratch = d0;
const Register scratch = r1;
const Register scratch2 = r9;
Label call_runtime, done, int_exponent;
if (exponent_type() == ON_STACK) {
Label base_is_smi, unpack_exponent;
// The exponent and base are supplied as arguments on the stack.
// This can only happen if the stub is called from non-optimized code.
// Load input parameters from stack to double registers.
__ LoadP(base, MemOperand(sp, 1 * kPointerSize));
__ LoadP(exponent, MemOperand(sp, 0 * kPointerSize));
__ LoadRoot(heapnumbermap, Heap::kHeapNumberMapRootIndex);
__ UntagAndJumpIfSmi(scratch, base, &base_is_smi);
__ LoadP(scratch, FieldMemOperand(base, JSObject::kMapOffset));
__ CmpP(scratch, heapnumbermap);
__ bne(&call_runtime);
__ LoadDouble(double_base, FieldMemOperand(base, HeapNumber::kValueOffset));
__ b(&unpack_exponent, Label::kNear);
__ bind(&base_is_smi);
__ ConvertIntToDouble(scratch, double_base);
__ bind(&unpack_exponent);
__ UntagAndJumpIfSmi(scratch, exponent, &int_exponent);
__ LoadP(scratch, FieldMemOperand(exponent, JSObject::kMapOffset));
__ CmpP(scratch, heapnumbermap);
__ bne(&call_runtime);
__ LoadDouble(double_exponent,
FieldMemOperand(exponent, HeapNumber::kValueOffset));
} else if (exponent_type() == TAGGED) {
// Base is already in double_base.
__ UntagAndJumpIfSmi(scratch, exponent, &int_exponent);
__ LoadDouble(double_exponent,
FieldMemOperand(exponent, HeapNumber::kValueOffset));
}
if (exponent_type() != INTEGER) {
// Detect integer exponents stored as double.
__ TryDoubleToInt32Exact(scratch, double_exponent, scratch2,
double_scratch);
__ beq(&int_exponent, Label::kNear);
if (exponent_type() == ON_STACK) {
// Detect square root case. Crankshaft detects constant +/-0.5 at
// compile time and uses DoMathPowHalf instead. We then skip this check
// for non-constant cases of +/-0.5 as these hardly occur.
Label not_plus_half, not_minus_inf1, not_minus_inf2;
// Test for 0.5.
__ LoadDoubleLiteral(double_scratch, 0.5, scratch);
__ cdbr(double_exponent, double_scratch);
__ bne(¬_plus_half, Label::kNear);
// Calculates square root of base. Check for the special case of
// Math.pow(-Infinity, 0.5) == Infinity (ECMA spec, 15.8.2.13).
__ LoadDoubleLiteral(double_scratch, -V8_INFINITY, scratch);
__ cdbr(double_base, double_scratch);
__ bne(¬_minus_inf1, Label::kNear);
__ lcdbr(double_result, double_scratch);
__ b(&done);
__ bind(¬_minus_inf1);
// Add +0 to convert -0 to +0.
__ ldr(double_scratch, double_base);
__ lzdr(kDoubleRegZero);
__ adbr(double_scratch, kDoubleRegZero);
__ sqdbr(double_result, double_scratch);
__ b(&done);
__ bind(¬_plus_half);
__ LoadDoubleLiteral(double_scratch, -0.5, scratch);
__ cdbr(double_exponent, double_scratch);
__ bne(&call_runtime);
// Calculates square root of base. Check for the special case of
// Math.pow(-Infinity, -0.5) == 0 (ECMA spec, 15.8.2.13).
__ LoadDoubleLiteral(double_scratch, -V8_INFINITY, scratch);
__ cdbr(double_base, double_scratch);
__ bne(¬_minus_inf2, Label::kNear);
__ ldr(double_result, kDoubleRegZero);
__ b(&done);
__ bind(¬_minus_inf2);
// Add +0 to convert -0 to +0.
__ ldr(double_scratch, double_base);
__ lzdr(kDoubleRegZero);
__ adbr(double_scratch, kDoubleRegZero);
__ LoadDoubleLiteral(double_result, 1.0, scratch);
__ sqdbr(double_scratch, double_scratch);
__ ddbr(double_result, double_scratch);
__ b(&done);
}
__ push(r14);
{
AllowExternalCallThatCantCauseGC scope(masm);
__ PrepareCallCFunction(0, 2, scratch);
__ MovToFloatParameters(double_base, double_exponent);
__ CallCFunction(
ExternalReference::power_double_double_function(isolate()), 0, 2);
}
__ pop(r14);
__ MovFromFloatResult(double_result);
__ b(&done);
}
// Calculate power with integer exponent.
__ bind(&int_exponent);
// Get two copies of exponent in the registers scratch and exponent.
if (exponent_type() == INTEGER) {
__ LoadRR(scratch, exponent);
} else {
// Exponent has previously been stored into scratch as untagged integer.
__ LoadRR(exponent, scratch);
}
__ ldr(double_scratch, double_base); // Back up base.
__ LoadImmP(scratch2, Operand(1));
__ ConvertIntToDouble(scratch2, double_result);
// Get absolute value of exponent.
Label positive_exponent;
__ CmpP(scratch, Operand::Zero());
__ bge(&positive_exponent, Label::kNear);
__ LoadComplementRR(scratch, scratch);
__ bind(&positive_exponent);
Label while_true, no_carry, loop_end;
__ bind(&while_true);
__ mov(scratch2, Operand(1));
__ AndP(scratch2, scratch);
__ beq(&no_carry, Label::kNear);
__ mdbr(double_result, double_scratch);
__ bind(&no_carry);
__ ShiftRightArithP(scratch, scratch, Operand(1));
__ beq(&loop_end, Label::kNear);
__ mdbr(double_scratch, double_scratch);
__ b(&while_true);
__ bind(&loop_end);
__ CmpP(exponent, Operand::Zero());
__ bge(&done);
// get 1/double_result:
__ ldr(double_scratch, double_result);
__ LoadImmP(scratch2, Operand(1));
__ ConvertIntToDouble(scratch2, double_result);
__ ddbr(double_result, double_scratch);
// Test whether result is zero. Bail out to check for subnormal result.
// Due to subnormals, x^-y == (1/x)^y does not hold in all cases.
__ lzdr(kDoubleRegZero);
__ cdbr(double_result, kDoubleRegZero);
__ bne(&done, Label::kNear);
// double_exponent may not containe the exponent value if the input was a
// smi. We set it with exponent value before bailing out.
__ ConvertIntToDouble(exponent, double_exponent);
// Returning or bailing out.
if (exponent_type() == ON_STACK) {
// The arguments are still on the stack.
__ bind(&call_runtime);
__ TailCallRuntime(Runtime::kMathPowRT);
// The stub is called from non-optimized code, which expects the result
// as heap number in exponent.
__ bind(&done);
__ AllocateHeapNumber(heapnumber, scratch, scratch2, heapnumbermap,
&call_runtime);
__ StoreDouble(double_result,
FieldMemOperand(heapnumber, HeapNumber::kValueOffset));
DCHECK(heapnumber.is(r2));
__ Ret(2);
} else {
__ push(r14);
{
AllowExternalCallThatCantCauseGC scope(masm);
__ PrepareCallCFunction(0, 2, scratch);
__ MovToFloatParameters(double_base, double_exponent);
__ CallCFunction(
ExternalReference::power_double_double_function(isolate()), 0, 2);
}
__ pop(r14);
__ MovFromFloatResult(double_result);
__ bind(&done);
__ Ret();
}
}
bool CEntryStub::NeedsImmovableCode() { return true; }
void CodeStub::GenerateStubsAheadOfTime(Isolate* isolate) {
CEntryStub::GenerateAheadOfTime(isolate);
StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(isolate);
StubFailureTrampolineStub::GenerateAheadOfTime(isolate);
ArrayConstructorStubBase::GenerateStubsAheadOfTime(isolate);
CreateAllocationSiteStub::GenerateAheadOfTime(isolate);
CreateWeakCellStub::GenerateAheadOfTime(isolate);
BinaryOpICStub::GenerateAheadOfTime(isolate);
StoreRegistersStateStub::GenerateAheadOfTime(isolate);
RestoreRegistersStateStub::GenerateAheadOfTime(isolate);
BinaryOpICWithAllocationSiteStub::GenerateAheadOfTime(isolate);
StoreFastElementStub::GenerateAheadOfTime(isolate);
TypeofStub::GenerateAheadOfTime(isolate);
}
void StoreRegistersStateStub::GenerateAheadOfTime(Isolate* isolate) {
StoreRegistersStateStub stub(isolate);
stub.GetCode();
}
void RestoreRegistersStateStub::GenerateAheadOfTime(Isolate* isolate) {
RestoreRegistersStateStub stub(isolate);
stub.GetCode();
}
void CodeStub::GenerateFPStubs(Isolate* isolate) {
SaveFPRegsMode mode = kSaveFPRegs;
CEntryStub(isolate, 1, mode).GetCode();
StoreBufferOverflowStub(isolate, mode).GetCode();
isolate->set_fp_stubs_generated(true);
}
void CEntryStub::GenerateAheadOfTime(Isolate* isolate) {
CEntryStub stub(isolate, 1, kDontSaveFPRegs);
stub.GetCode();
}
void CEntryStub::Generate(MacroAssembler* masm) {
// Called from JavaScript; parameters are on stack as if calling JS function.
// r2: number of arguments including receiver
// r3: pointer to builtin function
// fp: frame pointer (restored after C call)
// sp: stack pointer (restored as callee's sp after C call)
// cp: current context (C callee-saved)
//
// If argv_in_register():
// r4: pointer to the first argument
ProfileEntryHookStub::MaybeCallEntryHook(masm);
__ LoadRR(r7, r3);
if (argv_in_register()) {
// Move argv into the correct register.
__ LoadRR(r3, r4);
} else {
// Compute the argv pointer.
__ ShiftLeftP(r3, r2, Operand(kPointerSizeLog2));
__ lay(r3, MemOperand(r3, sp, -kPointerSize));
}
// Enter the exit frame that transitions from JavaScript to C++.
FrameScope scope(masm, StackFrame::MANUAL);
// Need at least one extra slot for return address location.
int arg_stack_space = 1;
// Pass buffer for return value on stack if necessary
bool needs_return_buffer =
result_size() > 2 ||
(result_size() == 2 && !ABI_RETURNS_OBJECTPAIR_IN_REGS);
if (needs_return_buffer) {
arg_stack_space += result_size();
}
#if V8_TARGET_ARCH_S390X
// 64-bit linux pass Argument object by reference not value
arg_stack_space += 2;
#endif
__ EnterExitFrame(save_doubles(), arg_stack_space);
// Store a copy of argc, argv in callee-saved registers for later.
__ LoadRR(r6, r2);
__ LoadRR(r8, r3);
// r2, r6: number of arguments including receiver (C callee-saved)
// r3, r8: pointer to the first argument
// r7: pointer to builtin function (C callee-saved)
// Result returned in registers or stack, depending on result size and ABI.
Register isolate_reg = r4;
if (needs_return_buffer) {
// The return value is 16-byte non-scalar value.
// Use frame storage reserved by calling function to pass return
// buffer as implicit first argument in R2. Shfit original parameters
// by one register each.
__ LoadRR(r4, r3);
__ LoadRR(r3, r2);
__ la(r2, MemOperand(sp, (kStackFrameExtraParamSlot + 1) * kPointerSize));
isolate_reg = r5;
}
// Call C built-in.
__ mov(isolate_reg, Operand(ExternalReference::isolate_address(isolate())));
Register target = r7;
// To let the GC traverse the return address of the exit frames, we need to
// know where the return address is. The CEntryStub is unmovable, so
// we can store the address on the stack to be able to find it again and
// we never have to restore it, because it will not change.
{
Label return_label;
__ larl(r14, &return_label); // Generate the return addr of call later.
__ StoreP(r14, MemOperand(sp, kStackFrameRASlot * kPointerSize));
// zLinux ABI requires caller's frame to have sufficient space for callee
// preserved regsiter save area.
// __ lay(sp, MemOperand(sp, -kCalleeRegisterSaveAreaSize));
__ positions_recorder()->WriteRecordedPositions();
__ b(target);
__ bind(&return_label);
// __ la(sp, MemOperand(sp, +kCalleeRegisterSaveAreaSize));
}
// If return value is on the stack, pop it to registers.
if (needs_return_buffer) {
if (result_size() > 2) __ LoadP(r4, MemOperand(r2, 2 * kPointerSize));
__ LoadP(r3, MemOperand(r2, kPointerSize));
__ LoadP(r2, MemOperand(r2));
}
// Check result for exception sentinel.
Label exception_returned;
__ CompareRoot(r2, Heap::kExceptionRootIndex);
__ beq(&exception_returned, Label::kNear);
// Check that there is no pending exception, otherwise we
// should have returned the exception sentinel.
if (FLAG_debug_code) {
Label okay;
ExternalReference pending_exception_address(
Isolate::kPendingExceptionAddress, isolate());
__ mov(r1, Operand(pending_exception_address));
__ LoadP(r1, MemOperand(r1));
__ CompareRoot(r1, Heap::kTheHoleValueRootIndex);
// Cannot use check here as it attempts to generate call into runtime.
__ beq(&okay, Label::kNear);
__ stop("Unexpected pending exception");
__ bind(&okay);
}
// Exit C frame and return.
// r2:r3: result
// sp: stack pointer
// fp: frame pointer
Register argc;
if (argv_in_register()) {
// We don't want to pop arguments so set argc to no_reg.
argc = no_reg;
} else {
// r6: still holds argc (callee-saved).
argc = r6;
}
__ LeaveExitFrame(save_doubles(), argc, true);
__ b(r14);
// Handling of exception.
__ bind(&exception_returned);
ExternalReference pending_handler_context_address(
Isolate::kPendingHandlerContextAddress, isolate());
ExternalReference pending_handler_code_address(
Isolate::kPendingHandlerCodeAddress, isolate());
ExternalReference pending_handler_offset_address(
Isolate::kPendingHandlerOffsetAddress, isolate());
ExternalReference pending_handler_fp_address(
Isolate::kPendingHandlerFPAddress, isolate());
ExternalReference pending_handler_sp_address(
Isolate::kPendingHandlerSPAddress, isolate());
// Ask the runtime for help to determine the handler. This will set r3 to
// contain the current pending exception, don't clobber it.
ExternalReference find_handler(Runtime::kUnwindAndFindExceptionHandler,
isolate());
{
FrameScope scope(masm, StackFrame::MANUAL);
__ PrepareCallCFunction(3, 0, r2);
__ LoadImmP(r2, Operand::Zero());
__ LoadImmP(r3, Operand::Zero());
__ mov(r4, Operand(ExternalReference::isolate_address(isolate())));
__ CallCFunction(find_handler, 3);
}
// Retrieve the handler context, SP and FP.
__ mov(cp, Operand(pending_handler_context_address));
__ LoadP(cp, MemOperand(cp));
__ mov(sp, Operand(pending_handler_sp_address));
__ LoadP(sp, MemOperand(sp));
__ mov(fp, Operand(pending_handler_fp_address));
__ LoadP(fp, MemOperand(fp));
// If the handler is a JS frame, restore the context to the frame. Note that
// the context will be set to (cp == 0) for non-JS frames.
Label skip;
__ CmpP(cp, Operand::Zero());
__ beq(&skip, Label::kNear);
__ StoreP(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
__ bind(&skip);
// Compute the handler entry address and jump to it.
__ mov(r3, Operand(pending_handler_code_address));
__ LoadP(r3, MemOperand(r3));
__ mov(r4, Operand(pending_handler_offset_address));
__ LoadP(r4, MemOperand(r4));
__ AddP(r3, r3, Operand(Code::kHeaderSize - kHeapObjectTag)); // Code start
__ AddP(ip, r3, r4);
__ Jump(ip);
}
void JSEntryStub::Generate(MacroAssembler* masm) {
// r2: code entry
// r3: function
// r4: receiver
// r5: argc
// r6: argv
Label invoke, handler_entry, exit;
ProfileEntryHookStub::MaybeCallEntryHook(masm);
// saving floating point registers
#if V8_TARGET_ARCH_S390X
// 64bit ABI requires f8 to f15 be saved
__ lay(sp, MemOperand(sp, -8 * kDoubleSize));
__ std(d8, MemOperand(sp));
__ std(d9, MemOperand(sp, 1 * kDoubleSize));
__ std(d10, MemOperand(sp, 2 * kDoubleSize));
__ std(d11, MemOperand(sp, 3 * kDoubleSize));
__ std(d12, MemOperand(sp, 4 * kDoubleSize));
__ std(d13, MemOperand(sp, 5 * kDoubleSize));
__ std(d14, MemOperand(sp, 6 * kDoubleSize));
__ std(d15, MemOperand(sp, 7 * kDoubleSize));
#else
// 31bit ABI requires you to store f4 and f6:
// http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_s390.html#AEN417
__ lay(sp, MemOperand(sp, -2 * kDoubleSize));
__ std(d4, MemOperand(sp));
__ std(d6, MemOperand(sp, kDoubleSize));
#endif
// zLinux ABI
// Incoming parameters:
// r2: code entry
// r3: function
// r4: receiver
// r5: argc
// r6: argv
// Requires us to save the callee-preserved registers r6-r13
// General convention is to also save r14 (return addr) and
// sp/r15 as well in a single STM/STMG
__ lay(sp, MemOperand(sp, -10 * kPointerSize));
__ StoreMultipleP(r6, sp, MemOperand(sp, 0));
// Set up the reserved register for 0.0.
// __ LoadDoubleLiteral(kDoubleRegZero, 0.0, r0);
// Push a frame with special values setup to mark it as an entry frame.
// Bad FP (-1)
// SMI Marker
// SMI Marker
// kCEntryFPAddress
// Frame type
__ lay(sp, MemOperand(sp, -5 * kPointerSize));
// Push a bad frame pointer to fail if it is used.
__ LoadImmP(r10, Operand(-1));
int marker = type();
__ LoadSmiLiteral(r9, Smi::FromInt(marker));
__ LoadSmiLiteral(r8, Smi::FromInt(marker));
// Save copies of the top frame descriptor on the stack.
__ mov(r7, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
__ LoadP(r7, MemOperand(r7));
__ StoreMultipleP(r7, r10, MemOperand(sp, kPointerSize));
// Set up frame pointer for the frame to be pushed.
// Need to add kPointerSize, because sp has one extra
// frame already for the frame type being pushed later.
__ lay(fp,
MemOperand(sp, -EntryFrameConstants::kCallerFPOffset + kPointerSize));
// If this is the outermost JS call, set js_entry_sp value.
Label non_outermost_js;
ExternalReference js_entry_sp(Isolate::kJSEntrySPAddress, isolate());
__ mov(r7, Operand(ExternalReference(js_entry_sp)));
__ LoadAndTestP(r8, MemOperand(r7));
__ bne(&non_outermost_js, Label::kNear);
__ StoreP(fp, MemOperand(r7));
__ LoadSmiLiteral(ip, Smi::FromInt(StackFrame::OUTERMOST_JSENTRY_FRAME));
Label cont;
__ b(&cont, Label::kNear);
__ bind(&non_outermost_js);
__ LoadSmiLiteral(ip, Smi::FromInt(StackFrame::INNER_JSENTRY_FRAME));
__ bind(&cont);
__ StoreP(ip, MemOperand(sp)); // frame-type
// Jump to a faked try block that does the invoke, with a faked catch
// block that sets the pending exception.
__ b(&invoke, Label::kNear);
__ bind(&handler_entry);
handler_offset_ = handler_entry.pos();
// Caught exception: Store result (exception) in the pending exception
// field in the JSEnv and return a failure sentinel. Coming in here the
// fp will be invalid because the PushStackHandler below sets it to 0 to
// signal the existence of the JSEntry frame.
__ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
isolate())));
__ StoreP(r2, MemOperand(ip));
__ LoadRoot(r2, Heap::kExceptionRootIndex);
__ b(&exit, Label::kNear);
// Invoke: Link this frame into the handler chain.
__ bind(&invoke);
// Must preserve r2-r6.
__ PushStackHandler();
// If an exception not caught by another handler occurs, this handler
// returns control to the code after the b(&invoke) above, which
// restores all kCalleeSaved registers (including cp and fp) to their
// saved values before returning a failure to C.
// Clear any pending exceptions.
__ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
isolate())));
__ mov(r7, Operand(isolate()->factory()->the_hole_value()));
__ StoreP(r7, MemOperand(ip));
// Invoke the function by calling through JS entry trampoline builtin.
// Notice that we cannot store a reference to the trampoline code directly in
// this stub, because runtime stubs are not traversed when doing GC.
// Expected registers by Builtins::JSEntryTrampoline
// r2: code entry
// r3: function
// r4: receiver
// r5: argc
// r6: argv
if (type() == StackFrame::ENTRY_CONSTRUCT) {
ExternalReference construct_entry(Builtins::kJSConstructEntryTrampoline,
isolate());
__ mov(ip, Operand(construct_entry));
} else {
ExternalReference entry(Builtins::kJSEntryTrampoline, isolate());
__ mov(ip, Operand(entry));
}
__ LoadP(ip, MemOperand(ip)); // deref address
// Branch and link to JSEntryTrampoline.
// the address points to the start of the code object, skip the header
__ AddP(ip, Operand(Code::kHeaderSize - kHeapObjectTag));
Label return_addr;
// __ basr(r14, ip);
__ larl(r14, &return_addr);
__ b(ip);
__ bind(&return_addr);
// Unlink this frame from the handler chain.
__ PopStackHandler();
__ bind(&exit); // r2 holds result
// Check if the current stack frame is marked as the outermost JS frame.
Label non_outermost_js_2;
__ pop(r7);
__ CmpSmiLiteral(r7, Smi::FromInt(StackFrame::OUTERMOST_JSENTRY_FRAME), r0);
__ bne(&non_outermost_js_2, Label::kNear);
__ mov(r8, Operand::Zero());
__ mov(r7, Operand(ExternalReference(js_entry_sp)));
__ StoreP(r8, MemOperand(r7));
__ bind(&non_outermost_js_2);
// Restore the top frame descriptors from the stack.
__ pop(r5);
__ mov(ip, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
__ StoreP(r5, MemOperand(ip));
// Reset the stack to the callee saved registers.
__ lay(sp, MemOperand(sp, -EntryFrameConstants::kCallerFPOffset));
// Reload callee-saved preserved regs, return address reg (r14) and sp
__ LoadMultipleP(r6, sp, MemOperand(sp, 0));
__ la(sp, MemOperand(sp, 10 * kPointerSize));
// saving floating point registers
#if V8_TARGET_ARCH_S390X
// 64bit ABI requires f8 to f15 be saved
__ ld(d8, MemOperand(sp));
__ ld(d9, MemOperand(sp, 1 * kDoubleSize));
__ ld(d10, MemOperand(sp, 2 * kDoubleSize));
__ ld(d11, MemOperand(sp, 3 * kDoubleSize));
__ ld(d12, MemOperand(sp, 4 * kDoubleSize));
__ ld(d13, MemOperand(sp, 5 * kDoubleSize));
__ ld(d14, MemOperand(sp, 6 * kDoubleSize));
__ ld(d15, MemOperand(sp, 7 * kDoubleSize));
__ la(sp, MemOperand(sp, 8 * kDoubleSize));
#else
// 31bit ABI requires you to store f4 and f6:
// http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_s390.html#AEN417
__ ld(d4, MemOperand(sp));
__ ld(d6, MemOperand(sp, kDoubleSize));
__ la(sp, MemOperand(sp, 2 * kDoubleSize));
#endif
__ b(r14);
}
void InstanceOfStub::Generate(MacroAssembler* masm) {
Register const object = r3; // Object (lhs).
Register const function = r2; // Function (rhs).
Register const object_map = r4; // Map of {object}.
Register const function_map = r5; // Map of {function}.
Register const function_prototype = r6; // Prototype of {function}.
Register const scratch = r7;
DCHECK(object.is(InstanceOfDescriptor::LeftRegister()));
DCHECK(function.is(InstanceOfDescriptor::RightRegister()));
// Check if {object} is a smi.
Label object_is_smi;
__ JumpIfSmi(object, &object_is_smi);
// Lookup the {function} and the {object} map in the global instanceof cache.
// Note: This is safe because we clear the global instanceof cache whenever
// we change the prototype of any object.
Label fast_case, slow_case;
__ LoadP(object_map, FieldMemOperand(object, HeapObject::kMapOffset));
__ CompareRoot(function, Heap::kInstanceofCacheFunctionRootIndex);
__ bne(&fast_case);
__ CompareRoot(object_map, Heap::kInstanceofCacheMapRootIndex);
__ bne(&fast_case);
__ LoadRoot(r2, Heap::kInstanceofCacheAnswerRootIndex);
__ Ret();
// If {object} is a smi we can safely return false if {function} is a JS
// function, otherwise we have to miss to the runtime and throw an exception.
__ bind(&object_is_smi);
__ JumpIfSmi(function, &slow_case);
__ CompareObjectType(function, function_map, scratch, JS_FUNCTION_TYPE);
__ bne(&slow_case);
__ LoadRoot(r2, Heap::kFalseValueRootIndex);
__ Ret();
// Fast-case: The {function} must be a valid JSFunction.
__ bind(&fast_case);
__ JumpIfSmi(function, &slow_case);
__ CompareObjectType(function, function_map, scratch, JS_FUNCTION_TYPE);
__ bne(&slow_case);
// Go to the runtime if the function is not a constructor.
__ LoadlB(scratch, FieldMemOperand(function_map, Map::kBitFieldOffset));
__ TestBit(scratch, Map::kIsConstructor, r0);
__ beq(&slow_case);
// Ensure that {function} has an instance prototype.
__ TestBit(scratch, Map::kHasNonInstancePrototype, r0);
__ bne(&slow_case);
// Get the "prototype" (or initial map) of the {function}.
__ LoadP(function_prototype,
FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
__ AssertNotSmi(function_prototype);
// Resolve the prototype if the {function} has an initial map. Afterwards the
// {function_prototype} will be either the JSReceiver prototype object or the
// hole value, which means that no instances of the {function} were created so
// far and hence we should return false.
Label function_prototype_valid;
__ CompareObjectType(function_prototype, scratch, scratch, MAP_TYPE);
__ bne(&function_prototype_valid);
__ LoadP(function_prototype,
FieldMemOperand(function_prototype, Map::kPrototypeOffset));
__ bind(&function_prototype_valid);
__ AssertNotSmi(function_prototype);
// Update the global instanceof cache with the current {object} map and
// {function}. The cached answer will be set when it is known below.
__ StoreRoot(function, Heap::kInstanceofCacheFunctionRootIndex);
__ StoreRoot(object_map, Heap::kInstanceofCacheMapRootIndex);
// Loop through the prototype chain looking for the {function} prototype.
// Assume true, and change to false if not found.
Register const object_instance_type = function_map;
Register const map_bit_field = function_map;
Register const null = scratch;
Register const result = r2;
Label done, loop, fast_runtime_fallback;
__ LoadRoot(result, Heap::kTrueValueRootIndex);
__ LoadRoot(null, Heap::kNullValueRootIndex);
__ bind(&loop);
// Check if the object needs to be access checked.
__ LoadlB(map_bit_field, FieldMemOperand(object_map, Map::kBitFieldOffset));
__ TestBit(map_bit_field, Map::kIsAccessCheckNeeded, r0);
__ bne(&fast_runtime_fallback);
// Check if the current object is a Proxy.
__ CompareInstanceType(object_map, object_instance_type, JS_PROXY_TYPE);
__ beq(&fast_runtime_fallback);
__ LoadP(object, FieldMemOperand(object_map, Map::kPrototypeOffset));
__ CmpP(object, function_prototype);
__ beq(&done);
__ CmpP(object, null);
__ LoadP(object_map, FieldMemOperand(object, HeapObject::kMapOffset));
__ bne(&loop);
__ LoadRoot(result, Heap::kFalseValueRootIndex);
__ bind(&done);
__ StoreRoot(result, Heap::kInstanceofCacheAnswerRootIndex);
__ Ret();
// Found Proxy or access check needed: Call the runtime
__ bind(&fast_runtime_fallback);
__ Push(object, function_prototype);
// Invalidate the instanceof cache.
__ LoadSmiLiteral(scratch, Smi::FromInt(0));
__ StoreRoot(scratch, Heap::kInstanceofCacheFunctionRootIndex);
__ TailCallRuntime(Runtime::kHasInPrototypeChain);
// Slow-case: Call the %InstanceOf runtime function.
__ bind(&slow_case);
__ Push(object, function);
__ TailCallRuntime(is_es6_instanceof() ? Runtime::kOrdinaryHasInstance
: Runtime::kInstanceOf);
}
void FunctionPrototypeStub::Generate(MacroAssembler* masm) {
Label miss;
Register receiver = LoadDescriptor::ReceiverRegister();
// Ensure that the vector and slot registers won't be clobbered before
// calling the miss handler.
DCHECK(!AreAliased(r6, r7, LoadWithVectorDescriptor::VectorRegister(),
LoadWithVectorDescriptor::SlotRegister()));
NamedLoadHandlerCompiler::GenerateLoadFunctionPrototype(masm, receiver, r6,
r7, &miss);
__ bind(&miss);
PropertyAccessCompiler::TailCallBuiltin(
masm, PropertyAccessCompiler::MissBuiltin(Code::LOAD_IC));
}
void LoadIndexedStringStub::Generate(MacroAssembler* masm) {
// Return address is in lr.
Label miss;
Register receiver = LoadDescriptor::ReceiverRegister();
Register index = LoadDescriptor::NameRegister();
Register scratch = r7;
Register result = r2;
DCHECK(!scratch.is(receiver) && !scratch.is(index));
DCHECK(!scratch.is(LoadWithVectorDescriptor::VectorRegister()) &&
result.is(LoadWithVectorDescriptor::SlotRegister()));
// StringCharAtGenerator doesn't use the result register until it's passed
// the different miss possibilities. If it did, we would have a conflict
// when FLAG_vector_ics is true.
StringCharAtGenerator char_at_generator(receiver, index, scratch, result,
&miss, // When not a string.
&miss, // When not a number.
&miss, // When index out of range.
STRING_INDEX_IS_ARRAY_INDEX,
RECEIVER_IS_STRING);
char_at_generator.GenerateFast(masm);
__ Ret();
StubRuntimeCallHelper call_helper;
char_at_generator.GenerateSlow(masm, PART_OF_IC_HANDLER, call_helper);
__ bind(&miss);
PropertyAccessCompiler::TailCallBuiltin(
masm, PropertyAccessCompiler::MissBuiltin(Code::KEYED_LOAD_IC));
}
void RegExpExecStub::Generate(MacroAssembler* masm) {
// Just jump directly to runtime if native RegExp is not selected at compile
// time or if regexp entry in generated code is turned off runtime switch or
// at compilation.
#ifdef V8_INTERPRETED_REGEXP
__ TailCallRuntime(Runtime::kRegExpExec);
#else // V8_INTERPRETED_REGEXP
// Stack frame on entry.
// sp[0]: last_match_info (expected JSArray)
// sp[4]: previous index
// sp[8]: subject string
// sp[12]: JSRegExp object
const int kLastMatchInfoOffset = 0 * kPointerSize;
const int kPreviousIndexOffset = 1 * kPointerSize;
const int kSubjectOffset = 2 * kPointerSize;
const int kJSRegExpOffset = 3 * kPointerSize;
Label runtime, br_over, encoding_type_UC16;
// Allocation of registers for this function. These are in callee save
// registers and will be preserved by the call to the native RegExp code, as
// this code is called using the normal C calling convention. When calling
// directly from generated code the native RegExp code will not do a GC and
// therefore the content of these registers are safe to use after the call.
Register subject = r6;
Register regexp_data = r7;
Register last_match_info_elements = r8;
Register code = r9;
__ CleanseP(r14);
// Ensure register assigments are consistent with callee save masks
DCHECK(subject.bit() & kCalleeSaved);
DCHECK(regexp_data.bit() & kCalleeSaved);
DCHECK(last_match_info_elements.bit() & kCalleeSaved);
DCHECK(code.bit() & kCalleeSaved);
// Ensure that a RegExp stack is allocated.
ExternalReference address_of_regexp_stack_memory_address =
ExternalReference::address_of_regexp_stack_memory_address(isolate());
ExternalReference address_of_regexp_stack_memory_size =
ExternalReference::address_of_regexp_stack_memory_size(isolate());
__ mov(r2, Operand(address_of_regexp_stack_memory_size));
__ LoadAndTestP(r2, MemOperand(r2));
__ beq(&runtime);
// Check that the first argument is a JSRegExp object.
__ LoadP(r2, MemOperand(sp, kJSRegExpOffset));
__ JumpIfSmi(r2, &runtime);
__ CompareObjectType(r2, r3, r3, JS_REGEXP_TYPE);
__ bne(&runtime);
// Check that the RegExp has been compiled (data contains a fixed array).
__ LoadP(regexp_data, FieldMemOperand(r2, JSRegExp::kDataOffset));
if (FLAG_debug_code) {
__ TestIfSmi(regexp_data);
__ Check(ne, kUnexpectedTypeForRegExpDataFixedArrayExpected, cr0);
__ CompareObjectType(regexp_data, r2, r2, FIXED_ARRAY_TYPE);
__ Check(eq, kUnexpectedTypeForRegExpDataFixedArrayExpected);
}
// regexp_data: RegExp data (FixedArray)
// Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
__ LoadP(r2, FieldMemOperand(regexp_data, JSRegExp::kDataTagOffset));
// DCHECK(Smi::FromInt(JSRegExp::IRREGEXP) < (char *)0xffffu);
__ CmpSmiLiteral(r2, Smi::FromInt(JSRegExp::IRREGEXP), r0);
__ bne(&runtime);
// regexp_data: RegExp data (FixedArray)
// Check that the number of captures fit in the static offsets vector buffer.
__ LoadP(r4,
FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
// Check (number_of_captures + 1) * 2 <= offsets vector size
// Or number_of_captures * 2 <= offsets vector size - 2
// SmiToShortArrayOffset accomplishes the multiplication by 2 and
// SmiUntag (which is a nop for 32-bit).
__ SmiToShortArrayOffset(r4, r4);
STATIC_ASSERT(Isolate::kJSRegexpStaticOffsetsVectorSize >= 2);
__ CmpLogicalP(r4, Operand(Isolate::kJSRegexpStaticOffsetsVectorSize - 2));
__ bgt(&runtime);
// Reset offset for possibly sliced string.
__ LoadImmP(ip, Operand::Zero());
__ LoadP(subject, MemOperand(sp, kSubjectOffset));
__ JumpIfSmi(subject, &runtime);
__ LoadRR(r5, subject); // Make a copy of the original subject string.
__ LoadP(r2, FieldMemOperand(subject, HeapObject::kMapOffset));
__ LoadlB(r2, FieldMemOperand(r2, Map::kInstanceTypeOffset));
// subject: subject string
// r5: subject string
// r2: subject string instance type
// regexp_data: RegExp data (FixedArray)
// Handle subject string according to its encoding and representation:
// (1) Sequential string? If yes, go to (5).
// (2) Anything but sequential or cons? If yes, go to (6).
// (3) Cons string. If the string is flat, replace subject with first string.
// Otherwise bailout.
// (4) Is subject external? If yes, go to (7).
// (5) Sequential string. Load regexp code according to encoding.
// (E) Carry on.
/// [...]
// Deferred code at the end of the stub:
// (6) Not a long external string? If yes, go to (8).
// (7) External string. Make it, offset-wise, look like a sequential string.
// Go to (5).
// (8) Short external string or not a string? If yes, bail out to runtime.
// (9) Sliced string. Replace subject with parent. Go to (4).
Label seq_string /* 5 */, external_string /* 7 */, check_underlying /* 4 */,
not_seq_nor_cons /* 6 */, not_long_external /* 8 */;
// (1) Sequential string? If yes, go to (5).
STATIC_ASSERT((kIsNotStringMask | kStringRepresentationMask |
kShortExternalStringMask) == 0x93);
__ mov(r3, Operand(kIsNotStringMask | kStringRepresentationMask |
kShortExternalStringMask));
__ AndP(r3, r2);
STATIC_ASSERT((kStringTag | kSeqStringTag) == 0);
__ beq(&seq_string); // Go to (5).
// (2) Anything but sequential or cons? If yes, go to (6).
STATIC_ASSERT(kConsStringTag < kExternalStringTag);
STATIC_ASSERT(kSlicedStringTag > kExternalStringTag);
STATIC_ASSERT(kIsNotStringMask > kExternalStringTag);
STATIC_ASSERT(kShortExternalStringTag > kExternalStringTag);
STATIC_ASSERT(kExternalStringTag < 0xffffu);
__ CmpP(r3, Operand(kExternalStringTag));
__ bge(¬_seq_nor_cons); // Go to (6).
// (3) Cons string. Check that it's flat.
// Replace subject with first string and reload instance type.
__ LoadP(r2, FieldMemOperand(subject, ConsString::kSecondOffset));
__ CompareRoot(r2, Heap::kempty_stringRootIndex);
__ bne(&runtime);
__ LoadP(subject, FieldMemOperand(subject, ConsString::kFirstOffset));
// (4) Is subject external? If yes, go to (7).
__ bind(&check_underlying);
__ LoadP(r2, FieldMemOperand(subject, HeapObject::kMapOffset));
__ LoadlB(r2, FieldMemOperand(r2, Map::kInstanceTypeOffset));
STATIC_ASSERT(kSeqStringTag == 0);
STATIC_ASSERT(kStringRepresentationMask == 3);
__ tmll(r2, Operand(kStringRepresentationMask));
// The underlying external string is never a short external string.
STATIC_ASSERT(ExternalString::kMaxShortLength < ConsString::kMinLength);
STATIC_ASSERT(ExternalString::kMaxShortLength < SlicedString::kMinLength);
__ bne(&external_string); // Go to (7).
// (5) Sequential string. Load regexp code according to encoding.
__ bind(&seq_string);
// subject: sequential subject string (or look-alike, external string)
// r5: original subject string
// Load previous index and check range before r5 is overwritten. We have to
// use r5 instead of subject here because subject might have been only made
// to look like a sequential string when it actually is an external string.
__ LoadP(r3, MemOperand(sp, kPreviousIndexOffset));
__ JumpIfNotSmi(r3, &runtime);
__ LoadP(r5, FieldMemOperand(r5, String::kLengthOffset));
__ CmpLogicalP(r5, r3);
__ ble(&runtime);
__ SmiUntag(r3);
STATIC_ASSERT(4 == kOneByteStringTag);
STATIC_ASSERT(kTwoByteStringTag == 0);
STATIC_ASSERT(kStringEncodingMask == 4);
__ ExtractBitMask(r5, r2, kStringEncodingMask, SetRC);
__ beq(&encoding_type_UC16, Label::kNear);
__ LoadP(code,
FieldMemOperand(regexp_data, JSRegExp::kDataOneByteCodeOffset));
__ b(&br_over, Label::kNear);
__ bind(&encoding_type_UC16);
__ LoadP(code, FieldMemOperand(regexp_data, JSRegExp::kDataUC16CodeOffset));
__ bind(&br_over);
// (E) Carry on. String handling is done.
// code: irregexp code
// Check that the irregexp code has been generated for the actual string
// encoding. If it has, the field contains a code object otherwise it contains
// a smi (code flushing support).
__ JumpIfSmi(code, &runtime);
// r3: previous index
// r5: encoding of subject string (1 if one_byte, 0 if two_byte);
// code: Address of generated regexp code
// subject: Subject string
// regexp_data: RegExp data (FixedArray)
// All checks done. Now push arguments for native regexp code.
__ IncrementCounter(isolate()->counters()->regexp_entry_native(), 1, r2, r4);
// Isolates: note we add an additional parameter here (isolate pointer).
const int kRegExpExecuteArguments = 10;
const int kParameterRegisters = 5;
__ EnterExitFrame(false, kRegExpExecuteArguments - kParameterRegisters);
// Stack pointer now points to cell where return address is to be written.
// Arguments are before that on the stack or in registers.
// Argument 10 (in stack parameter area): Pass current isolate address.
__ mov(r2, Operand(ExternalReference::isolate_address(isolate())));
__ StoreP(r2, MemOperand(sp, kStackFrameExtraParamSlot * kPointerSize +
4 * kPointerSize));
// Argument 9 is a dummy that reserves the space used for
// the return address added by the ExitFrame in native calls.
__ mov(r2, Operand::Zero());
__ StoreP(r2, MemOperand(sp, kStackFrameExtraParamSlot * kPointerSize +
3 * kPointerSize));
// Argument 8: Indicate that this is a direct call from JavaScript.
__ mov(r2, Operand(1));
__ StoreP(r2, MemOperand(sp, kStackFrameExtraParamSlot * kPointerSize +
2 * kPointerSize));
// Argument 7: Start (high end) of backtracking stack memory area.
__ mov(r2, Operand(address_of_regexp_stack_memory_address));
__ LoadP(r2, MemOperand(r2, 0));
__ mov(r1, Operand(address_of_regexp_stack_memory_size));
__ LoadP(r1, MemOperand(r1, 0));
__ AddP(r2, r1);
__ StoreP(r2, MemOperand(sp, kStackFrameExtraParamSlot * kPointerSize +
1 * kPointerSize));
// Argument 6: Set the number of capture registers to zero to force
// global egexps to behave as non-global. This does not affect non-global
// regexps.
__ mov(r2, Operand::Zero());
__ StoreP(r2, MemOperand(sp, kStackFrameExtraParamSlot * kPointerSize +
0 * kPointerSize));
// Argument 1 (r2): Subject string.
// Load the length from the original subject string from the previous stack
// frame. Therefore we have to use fp, which points exactly to 15 pointer
// sizes below the previous sp. (Because creating a new stack frame pushes
// the previous fp onto the stack and moves up sp by 2 * kPointerSize and
// 13 registers saved on the stack previously)
__ LoadP(r2, MemOperand(fp, kSubjectOffset + 2 * kPointerSize));
// Argument 2 (r3): Previous index.
// Already there
__ AddP(r1, subject, Operand(SeqString::kHeaderSize - kHeapObjectTag));
// Argument 5 (r6): static offsets vector buffer.
__ mov(
r6,
Operand(ExternalReference::address_of_static_offsets_vector(isolate())));
// For arguments 4 (r5) and 3 (r4) get string length, calculate start of data
// and calculate the shift of the index (0 for one-byte and 1 for two byte).
__ XorP(r5, Operand(1));
// If slice offset is not 0, load the length from the original sliced string.
// Argument 3, r4: Start of string data
// Prepare start and end index of the input.
__ ShiftLeftP(ip, ip, r5);
__ AddP(ip, r1, ip);
__ ShiftLeftP(r4, r3, r5);
__ AddP(r4, ip, r4);
// Argument 4, r5: End of string data
__ LoadP(r1, FieldMemOperand(r2, String::kLengthOffset));
__ SmiUntag(r1);
__ ShiftLeftP(r0, r1, r5);
__ AddP(r5, ip, r0);
// Locate the code entry and call it.
__ AddP(code, Operand(Code::kHeaderSize - kHeapObjectTag));
DirectCEntryStub stub(isolate());
stub.GenerateCall(masm, code);
__ LeaveExitFrame(false, no_reg, true);
// r2: result (int32)
// subject: subject string -- needed to reload
__ LoadP(subject, MemOperand(sp, kSubjectOffset));
// regexp_data: RegExp data (callee saved)
// last_match_info_elements: Last match info elements (callee saved)
// Check the result.
Label success;
__ Cmp32(r2, Operand(1));
// We expect exactly one result since we force the called regexp to behave
// as non-global.
__ beq(&success);
Label failure;
__ Cmp32(r2, Operand(NativeRegExpMacroAssembler::FAILURE));
__ beq(&failure);
__ Cmp32(r2, Operand(NativeRegExpMacroAssembler::EXCEPTION));
// If not exception it can only be retry. Handle that in the runtime system.
__ bne(&runtime);
// Result must now be exception. If there is no pending exception already a
// stack overflow (on the backtrack stack) was detected in RegExp code but
// haven't created the exception yet. Handle that in the runtime system.
// TODO(592): Rerunning the RegExp to get the stack overflow exception.
__ mov(r3, Operand(isolate()->factory()->the_hole_value()));
__ mov(r4, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
isolate())));
__ LoadP(r2, MemOperand(r4, 0));
__ CmpP(r2, r3);
__ beq(&runtime);
// For exception, throw the exception again.
__ TailCallRuntime(Runtime::kRegExpExecReThrow);
__ bind(&failure);
// For failure and exception return null.
__ mov(r2, Operand(isolate()->factory()->null_value()));
__ la(sp, MemOperand(sp, (4 * kPointerSize)));
__ Ret();
// Process the result from the native regexp code.
__ bind(&success);
__ LoadP(r3,
FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
// Calculate number of capture registers (number_of_captures + 1) * 2.
// SmiToShortArrayOffset accomplishes the multiplication by 2 and
// SmiUntag (which is a nop for 32-bit).
__ SmiToShortArrayOffset(r3, r3);
__ AddP(r3, Operand(2));
__ LoadP(r2, MemOperand(sp, kLastMatchInfoOffset));
__ JumpIfSmi(r2, &runtime);
__ CompareObjectType(r2, r4, r4, JS_ARRAY_TYPE);
__ bne(&runtime);
// Check that the JSArray is in fast case.
__ LoadP(last_match_info_elements,
FieldMemOperand(r2, JSArray::kElementsOffset));
__ LoadP(r2,
FieldMemOperand(last_match_info_elements, HeapObject::kMapOffset));
__ CompareRoot(r2, Heap::kFixedArrayMapRootIndex);
__ bne(&runtime);
// Check that the last match info has space for the capture registers and the
// additional information.
__ LoadP(
r2, FieldMemOperand(last_match_info_elements, FixedArray::kLengthOffset));
__ AddP(r4, r3, Operand(RegExpImpl::kLastMatchOverhead));
__ SmiUntag(r0, r2);
__ CmpP(r4, r0);
__ bgt(&runtime);
// r3: number of capture registers
// subject: subject string
// Store the capture count.
__ SmiTag(r4, r3);
__ StoreP(r4, FieldMemOperand(last_match_info_elements,
RegExpImpl::kLastCaptureCountOffset));
// Store last subject and last input.
__ StoreP(subject, FieldMemOperand(last_match_info_elements,
RegExpImpl::kLastSubjectOffset));
__ LoadRR(r4, subject);
__ RecordWriteField(last_match_info_elements, RegExpImpl::kLastSubjectOffset,
subject, r9, kLRHasNotBeenSaved, kDontSaveFPRegs);
__ LoadRR(subject, r4);
__ StoreP(subject, FieldMemOperand(last_match_info_elements,
RegExpImpl::kLastInputOffset));
__ RecordWriteField(last_match_info_elements, RegExpImpl::kLastInputOffset,
subject, r9, kLRHasNotBeenSaved, kDontSaveFPRegs);
// Get the static offsets vector filled by the native regexp code.
ExternalReference address_of_static_offsets_vector =
ExternalReference::address_of_static_offsets_vector(isolate());
__ mov(r4, Operand(address_of_static_offsets_vector));
// r3: number of capture registers
// r4: offsets vector
Label next_capture;
// Capture register counter starts from number of capture registers and
// counts down until wraping after zero.
__ AddP(
r2, last_match_info_elements,
Operand(RegExpImpl::kFirstCaptureOffset - kHeapObjectTag - kPointerSize));
__ AddP(r4, Operand(-kIntSize)); // bias down for lwzu
__ bind(&next_capture);
// Read the value from the static offsets vector buffer.
__ ly(r5, MemOperand(r4, kIntSize));
__ lay(r4, MemOperand(r4, kIntSize));
// Store the smi value in the last match info.
__ SmiTag(r5);
__ StoreP(r5, MemOperand(r2, kPointerSize));
__ lay(r2, MemOperand(r2, kPointerSize));
__ BranchOnCount(r3, &next_capture);
// Return last match info.
__ LoadP(r2, MemOperand(sp, kLastMatchInfoOffset));
__ la(sp, MemOperand(sp, (4 * kPointerSize)));
__ Ret();
// Do the runtime call to execute the regexp.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kRegExpExec);
// Deferred code for string handling.
// (6) Not a long external string? If yes, go to (8).
__ bind(¬_seq_nor_cons);
// Compare flags are still set.
__ bgt(¬_long_external); // Go to (8).
// (7) External string. Make it, offset-wise, look like a sequential string.
__ bind(&external_string);
__ LoadP(r2, FieldMemOperand(subject, HeapObject::kMapOffset));
__ LoadlB(r2, FieldMemOperand(r2, Map::kInstanceTypeOffset));
if (FLAG_debug_code) {
// Assert that we do not have a cons or slice (indirect strings) here.
// Sequential strings have already been ruled out.
STATIC_ASSERT(kIsIndirectStringMask == 1);
__ tmll(r2, Operand(kIsIndirectStringMask));
__ Assert(eq, kExternalStringExpectedButNotFound, cr0);
}
__ LoadP(subject,
FieldMemOperand(subject, ExternalString::kResourceDataOffset));
// Move the pointer so that offset-wise, it looks like a sequential string.
STATIC_ASSERT(SeqTwoByteString::kHeaderSize == SeqOneByteString::kHeaderSize);
__ SubP(subject, subject,
Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
__ b(&seq_string); // Go to (5).
// (8) Short external string or not a string? If yes, bail out to runtime.
__ bind(¬_long_external);
STATIC_ASSERT(kNotStringTag != 0 && kShortExternalStringTag != 0);
__ mov(r0, Operand(kIsNotStringMask | kShortExternalStringMask));
__ AndP(r0, r3);
__ bne(&runtime);
// (9) Sliced string. Replace subject with parent. Go to (4).
// Load offset into ip and replace subject string with parent.
__ LoadP(ip, FieldMemOperand(subject, SlicedString::kOffsetOffset));
__ SmiUntag(ip);
__ LoadP(subject, FieldMemOperand(subject, SlicedString::kParentOffset));
__ b(&check_underlying); // Go to (4).
#endif // V8_INTERPRETED_REGEXP
}
static void CallStubInRecordCallTarget(MacroAssembler* masm, CodeStub* stub) {
// r2 : number of arguments to the construct function
// r3 : the function to call
// r4 : feedback vector
// r5 : slot in feedback vector (Smi)
FrameScope scope(masm, StackFrame::INTERNAL);
// Number-of-arguments register must be smi-tagged to call out.
__ SmiTag(r2);
__ Push(r5, r4, r3, r2);
__ CallStub(stub);
__ Pop(r5, r4, r3, r2);
__ SmiUntag(r2);
}
static void GenerateRecordCallTarget(MacroAssembler* masm) {
// Cache the called function in a feedback vector slot. Cache states
// are uninitialized, monomorphic (indicated by a JSFunction), and
// megamorphic.
// r2 : number of arguments to the construct function
// r3 : the function to call
// r4 : feedback vector
// r5 : slot in feedback vector (Smi)
Label initialize, done, miss, megamorphic, not_array_function;
DCHECK_EQ(*TypeFeedbackVector::MegamorphicSentinel(masm->isolate()),
masm->isolate()->heap()->megamorphic_symbol());
DCHECK_EQ(*TypeFeedbackVector::UninitializedSentinel(masm->isolate()),
masm->isolate()->heap()->uninitialized_symbol());
// Load the cache state into r7.
__ SmiToPtrArrayOffset(r7, r5);
__ AddP(r7, r4, r7);
__ LoadP(r7, FieldMemOperand(r7, FixedArray::kHeaderSize));
// A monomorphic cache hit or an already megamorphic state: invoke the
// function without changing the state.
// We don't know if r7 is a WeakCell or a Symbol, but it's harmless to read at
// this position in a symbol (see static asserts in type-feedback-vector.h).
Label check_allocation_site;
Register feedback_map = r8;
Register weak_value = r9;
__ LoadP(weak_value, FieldMemOperand(r7, WeakCell::kValueOffset));
__ CmpP(r3, weak_value);
__ beq(&done);
__ CompareRoot(r7, Heap::kmegamorphic_symbolRootIndex);
__ beq(&done);
__ LoadP(feedback_map, FieldMemOperand(r7, HeapObject::kMapOffset));
__ CompareRoot(feedback_map, Heap::kWeakCellMapRootIndex);
__ bne(&check_allocation_site);
// If the weak cell is cleared, we have a new chance to become monomorphic.
__ JumpIfSmi(weak_value, &initialize);
__ b(&megamorphic);
__ bind(&check_allocation_site);
// If we came here, we need to see if we are the array function.
// If we didn't have a matching function, and we didn't find the megamorph
// sentinel, then we have in the slot either some other function or an
// AllocationSite.
__ CompareRoot(feedback_map, Heap::kAllocationSiteMapRootIndex);
__ bne(&miss);
// Make sure the function is the Array() function
__ LoadNativeContextSlot(Context::ARRAY_FUNCTION_INDEX, r7);
__ CmpP(r3, r7);
__ bne(&megamorphic);
__ b(&done);
__ bind(&miss);
// A monomorphic miss (i.e, here the cache is not uninitialized) goes
// megamorphic.
__ CompareRoot(r7, Heap::kuninitialized_symbolRootIndex);
__ beq(&initialize);
// MegamorphicSentinel is an immortal immovable object (undefined) so no
// write-barrier is needed.
__ bind(&megamorphic);
__ SmiToPtrArrayOffset(r7, r5);
__ AddP(r7, r4, r7);
__ LoadRoot(ip, Heap::kmegamorphic_symbolRootIndex);
__ StoreP(ip, FieldMemOperand(r7, FixedArray::kHeaderSize), r0);
__ jmp(&done);
// An uninitialized cache is patched with the function
__ bind(&initialize);
// Make sure the function is the Array() function.
__ LoadNativeContextSlot(Context::ARRAY_FUNCTION_INDEX, r7);
__ CmpP(r3, r7);
__ bne(¬_array_function);
// The target function is the Array constructor,
// Create an AllocationSite if we don't already have it, store it in the
// slot.
CreateAllocationSiteStub create_stub(masm->isolate());
CallStubInRecordCallTarget(masm, &create_stub);
__ b(&done);
__ bind(¬_array_function);
CreateWeakCellStub weak_cell_stub(masm->isolate());
CallStubInRecordCallTarget(masm, &weak_cell_stub);
__ bind(&done);
}
void CallConstructStub::Generate(MacroAssembler* masm) {
// r2 : number of arguments
// r3 : the function to call
// r4 : feedback vector
// r5 : slot in feedback vector (Smi, for RecordCallTarget)
Label non_function;
// Check that the function is not a smi.
__ JumpIfSmi(r3, &non_function);
// Check that the function is a JSFunction.
__ CompareObjectType(r3, r7, r7, JS_FUNCTION_TYPE);
__ bne(&non_function);
GenerateRecordCallTarget(masm);
__ SmiToPtrArrayOffset(r7, r5);
__ AddP(r7, r4, r7);
// Put the AllocationSite from the feedback vector into r4, or undefined.
__ LoadP(r4, FieldMemOperand(r7, FixedArray::kHeaderSize));
__ LoadP(r7, FieldMemOperand(r4, AllocationSite::kMapOffset));
__ CompareRoot(r7, Heap::kAllocationSiteMapRootIndex);
Label feedback_register_initialized;
__ beq(&feedback_register_initialized);
__ LoadRoot(r4, Heap::kUndefinedValueRootIndex);
__ bind(&feedback_register_initialized);
__ AssertUndefinedOrAllocationSite(r4, r7);
// Pass function as new target.
__ LoadRR(r5, r3);
// Tail call to the function-specific construct stub (still in the caller
// context at this point).
__ LoadP(r6, FieldMemOperand(r3, JSFunction::kSharedFunctionInfoOffset));
__ LoadP(r6, FieldMemOperand(r6, SharedFunctionInfo::kConstructStubOffset));
__ AddP(ip, r6, Operand(Code::kHeaderSize - kHeapObjectTag));
__ JumpToJSEntry(ip);
__ bind(&non_function);
__ LoadRR(r5, r3);
__ Jump(isolate()->builtins()->Construct(), RelocInfo::CODE_TARGET);
}
void CallICStub::HandleArrayCase(MacroAssembler* masm, Label* miss) {
// r3 - function
// r5 - slot id
// r4 - vector
// r6 - allocation site (loaded from vector[slot])
__ LoadNativeContextSlot(Context::ARRAY_FUNCTION_INDEX, r7);
__ CmpP(r3, r7);
__ bne(miss);
__ mov(r2, Operand(arg_count()));
// Increment the call count for monomorphic function calls.
const int count_offset = FixedArray::kHeaderSize + kPointerSize;
__ SmiToPtrArrayOffset(r7, r5);
__ AddP(r4, r4, r7);
__ LoadP(r5, FieldMemOperand(r4, count_offset));
__ AddSmiLiteral(r5, r5, Smi::FromInt(CallICNexus::kCallCountIncrement), r0);
__ StoreP(r5, FieldMemOperand(r4, count_offset), r0);
__ LoadRR(r4, r6);
__ LoadRR(r5, r3);
ArrayConstructorStub stub(masm->isolate(), arg_count());
__ TailCallStub(&stub);
}
void CallICStub::Generate(MacroAssembler* masm) {
// r3 - function
// r5 - slot id (Smi)
// r4 - vector
Label extra_checks_or_miss, call, call_function;
int argc = arg_count();
ParameterCount actual(argc);
// The checks. First, does r3 match the recorded monomorphic target?
__ SmiToPtrArrayOffset(r8, r5);
__ AddP(r8, r4, r8);
__ LoadP(r6, FieldMemOperand(r8, FixedArray::kHeaderSize));
// We don't know that we have a weak cell. We might have a private symbol
// or an AllocationSite, but the memory is safe to examine.
// AllocationSite::kTransitionInfoOffset - contains a Smi or pointer to
// FixedArray.
// WeakCell::kValueOffset - contains a JSFunction or Smi(0)
// Symbol::kHashFieldSlot - if the low bit is 1, then the hash is not
// computed, meaning that it can't appear to be a pointer. If the low bit is
// 0, then hash is computed, but the 0 bit prevents the field from appearing
// to be a pointer.
STATIC_ASSERT(WeakCell::kSize >= kPointerSize);
STATIC_ASSERT(AllocationSite::kTransitionInfoOffset ==
WeakCell::kValueOffset &&
WeakCell::kValueOffset == Symbol::kHashFieldSlot);
__ LoadP(r7, FieldMemOperand(r6, WeakCell::kValueOffset));
__ CmpP(r3, r7);
__ bne(&extra_checks_or_miss, Label::kNear);
// The compare above could have been a SMI/SMI comparison. Guard against this
// convincing us that we have a monomorphic JSFunction.
__ JumpIfSmi(r3, &extra_checks_or_miss);
// Increment the call count for monomorphic function calls.
const int count_offset = FixedArray::kHeaderSize + kPointerSize;
__ LoadP(r5, FieldMemOperand(r8, count_offset));
__ AddSmiLiteral(r5, r5, Smi::FromInt(CallICNexus::kCallCountIncrement), r0);
__ StoreP(r5, FieldMemOperand(r8, count_offset), r0);
__ bind(&call_function);
__ mov(r2, Operand(argc));
__ Jump(masm->isolate()->builtins()->CallFunction(convert_mode(),
tail_call_mode()),
RelocInfo::CODE_TARGET);
__ bind(&extra_checks_or_miss);
Label uninitialized, miss, not_allocation_site;
__ CompareRoot(r6, Heap::kmegamorphic_symbolRootIndex);
__ beq(&call);
// Verify that r6 contains an AllocationSite
__ LoadP(r7, FieldMemOperand(r6, HeapObject::kMapOffset));
__ CompareRoot(r7, Heap::kAllocationSiteMapRootIndex);
__ bne(¬_allocation_site);
// We have an allocation site.
HandleArrayCase(masm, &miss);
__ bind(¬_allocation_site);
// The following cases attempt to handle MISS cases without going to the
// runtime.
if (FLAG_trace_ic) {
__ b(&miss);
}
__ CompareRoot(r6, Heap::kuninitialized_symbolRootIndex);
__ beq(&uninitialized);
// We are going megamorphic. If the feedback is a JSFunction, it is fine
// to handle it here. More complex cases are dealt with in the runtime.
__ AssertNotSmi(r6);
__ CompareObjectType(r6, r7, r7, JS_FUNCTION_TYPE);
__ bne(&miss);
__ LoadRoot(ip, Heap::kmegamorphic_symbolRootIndex);
__ StoreP(ip, FieldMemOperand(r8, FixedArray::kHeaderSize), r0);
__ bind(&call);
__ mov(r2, Operand(argc));
__ Jump(masm->isolate()->builtins()->Call(convert_mode(), tail_call_mode()),
RelocInfo::CODE_TARGET);
__ bind(&uninitialized);
// We are going monomorphic, provided we actually have a JSFunction.
__ JumpIfSmi(r3, &miss);
// Goto miss case if we do not have a function.
__ CompareObjectType(r3, r6, r6, JS_FUNCTION_TYPE);
__ bne(&miss);
// Make sure the function is not the Array() function, which requires special
// behavior on MISS.
__ LoadNativeContextSlot(Context::ARRAY_FUNCTION_INDEX, r6);
__ CmpP(r3, r6);
__ beq(&miss);
// Make sure the function belongs to the same native context.
__ LoadP(r6, FieldMemOperand(r3, JSFunction::kContextOffset));
__ LoadP(r6, ContextMemOperand(r6, Context::NATIVE_CONTEXT_INDEX));
__ LoadP(ip, NativeContextMemOperand());
__ CmpP(r6, ip);
__ bne(&miss);
// Initialize the call counter.
__ LoadSmiLiteral(r7, Smi::FromInt(CallICNexus::kCallCountIncrement));
__ StoreP(r7, FieldMemOperand(r8, count_offset), r0);
// Store the function. Use a stub since we need a frame for allocation.
// r4 - vector
// r5 - slot
// r3 - function
{
FrameScope scope(masm, StackFrame::INTERNAL);
CreateWeakCellStub create_stub(masm->isolate());
__ Push(r3);
__ CallStub(&create_stub);
__ Pop(r3);
}
__ b(&call_function);
// We are here because tracing is on or we encountered a MISS case we can't
// handle here.
__ bind(&miss);
GenerateMiss(masm);
__ b(&call);
}
void CallICStub::GenerateMiss(MacroAssembler* masm) {
FrameScope scope(masm, StackFrame::INTERNAL);
// Push the function and feedback info.
__ Push(r3, r4, r5);
// Call the entry.
__ CallRuntime(Runtime::kCallIC_Miss);
// Move result to r3 and exit the internal frame.
__ LoadRR(r3, r2);
}
// StringCharCodeAtGenerator
void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) {
// If the receiver is a smi trigger the non-string case.
if (check_mode_ == RECEIVER_IS_UNKNOWN) {
__ JumpIfSmi(object_, receiver_not_string_);
// Fetch the instance type of the receiver into result register.
__ LoadP(result_, FieldMemOperand(object_, HeapObject::kMapOffset));
__ LoadlB(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset));
// If the receiver is not a string trigger the non-string case.
__ mov(r0, Operand(kIsNotStringMask));
__ AndP(r0, result_);
__ bne(receiver_not_string_);
}
// If the index is non-smi trigger the non-smi case.
__ JumpIfNotSmi(index_, &index_not_smi_);
__ bind(&got_smi_index_);
// Check for index out of range.
__ LoadP(ip, FieldMemOperand(object_, String::kLengthOffset));
__ CmpLogicalP(ip, index_);
__ ble(index_out_of_range_);
__ SmiUntag(index_);
StringCharLoadGenerator::Generate(masm, object_, index_, result_,
&call_runtime_);
__ SmiTag(result_);
__ bind(&exit_);
}
void StringCharCodeAtGenerator::GenerateSlow(
MacroAssembler* masm, EmbedMode embed_mode,
const RuntimeCallHelper& call_helper) {
__ Abort(kUnexpectedFallthroughToCharCodeAtSlowCase);
// Index is not a smi.
__ bind(&index_not_smi_);
// If index is a heap number, try converting it to an integer.
__ CheckMap(index_, result_, Heap::kHeapNumberMapRootIndex, index_not_number_,
DONT_DO_SMI_CHECK);
call_helper.BeforeCall(masm);
if (embed_mode == PART_OF_IC_HANDLER) {
__ Push(LoadWithVectorDescriptor::VectorRegister(),
LoadWithVectorDescriptor::SlotRegister(), object_, index_);
} else {
// index_ is consumed by runtime conversion function.
__ Push(object_, index_);
}
if (index_flags_ == STRING_INDEX_IS_NUMBER) {
__ CallRuntime(Runtime::kNumberToIntegerMapMinusZero);
} else {
DCHECK(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX);
// NumberToSmi discards numbers that are not exact integers.
__ CallRuntime(Runtime::kNumberToSmi);
}
// Save the conversion result before the pop instructions below
// have a chance to overwrite it.
__ Move(index_, r2);
if (embed_mode == PART_OF_IC_HANDLER) {
__ Pop(LoadWithVectorDescriptor::VectorRegister(),
LoadWithVectorDescriptor::SlotRegister(), object_);
} else {
__ pop(object_);
}
// Reload the instance type.
__ LoadP(result_, FieldMemOperand(object_, HeapObject::kMapOffset));
__ LoadlB(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset));
call_helper.AfterCall(masm);
// If index is still not a smi, it must be out of range.
__ JumpIfNotSmi(index_, index_out_of_range_);
// Otherwise, return to the fast path.
__ b(&got_smi_index_);
// Call runtime. We get here when the receiver is a string and the
// index is a number, but the code of getting the actual character
// is too complex (e.g., when the string needs to be flattened).
__ bind(&call_runtime_);
call_helper.BeforeCall(masm);
__ SmiTag(index_);
__ Push(object_, index_);
__ CallRuntime(Runtime::kStringCharCodeAtRT);
__ Move(result_, r2);
call_helper.AfterCall(masm);
__ b(&exit_);
__ Abort(kUnexpectedFallthroughFromCharCodeAtSlowCase);
}
// -------------------------------------------------------------------------
// StringCharFromCodeGenerator
void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) {
// Fast case of Heap::LookupSingleCharacterStringFromCode.
DCHECK(base::bits::IsPowerOfTwo32(String::kMaxOneByteCharCodeU + 1));
__ LoadSmiLiteral(r0, Smi::FromInt(~String::kMaxOneByteCharCodeU));
__ OrP(r0, r0, Operand(kSmiTagMask));
__ AndP(r0, code_, r0);
__ bne(&slow_case_);
__ LoadRoot(result_, Heap::kSingleCharacterStringCacheRootIndex);
// At this point code register contains smi tagged one-byte char code.
__ LoadRR(r0, code_);
__ SmiToPtrArrayOffset(code_, code_);
__ AddP(result_, code_);
__ LoadRR(code_, r0);
__ LoadP(result_, FieldMemOperand(result_, FixedArray::kHeaderSize));
__ CompareRoot(result_, Heap::kUndefinedValueRootIndex);
__ beq(&slow_case_);
__ bind(&exit_);
}
void StringCharFromCodeGenerator::GenerateSlow(
MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
__ Abort(kUnexpectedFallthroughToCharFromCodeSlowCase);
__ bind(&slow_case_);
call_helper.BeforeCall(masm);
__ push(code_);
__ CallRuntime(Runtime::kStringCharFromCode);
__ Move(result_, r2);
call_helper.AfterCall(masm);
__ b(&exit_);
__ Abort(kUnexpectedFallthroughFromCharFromCodeSlowCase);
}
enum CopyCharactersFlags { COPY_ASCII = 1, DEST_ALWAYS_ALIGNED = 2 };
void StringHelper::GenerateCopyCharacters(MacroAssembler* masm, Register dest,
Register src, Register count,
Register scratch,
String::Encoding encoding) {
if (FLAG_debug_code) {
// Check that destination is word aligned.
__ mov(r0, Operand(kPointerAlignmentMask));
__ AndP(r0, dest);
__ Check(eq, kDestinationOfCopyNotAligned, cr0);
}
// Nothing to do for zero characters.
Label done;
if (encoding == String::TWO_BYTE_ENCODING) {
// double the length
__ AddP(count, count, count);
__ beq(&done, Label::kNear);
} else {
__ CmpP(count, Operand::Zero());
__ beq(&done, Label::kNear);
}
// Copy count bytes from src to dst.
Label byte_loop;
// TODO(joransiu): Convert into MVC loop
__ bind(&byte_loop);
__ LoadlB(scratch, MemOperand(src));
__ la(src, MemOperand(src, 1));
__ stc(scratch, MemOperand(dest));
__ la(dest, MemOperand(dest, 1));
__ BranchOnCount(count, &byte_loop);
__ bind(&done);
}
void SubStringStub::Generate(MacroAssembler* masm) {
Label runtime;
// Stack frame on entry.
// lr: return address
// sp[0]: to
// sp[4]: from
// sp[8]: string
// This stub is called from the native-call %_SubString(...), so
// nothing can be assumed about the arguments. It is tested that:
// "string" is a sequential string,
// both "from" and "to" are smis, and
// 0 <= from <= to <= string.length.
// If any of these assumptions fail, we call the runtime system.
const int kToOffset = 0 * kPointerSize;
const int kFromOffset = 1 * kPointerSize;
const int kStringOffset = 2 * kPointerSize;
__ LoadP(r4, MemOperand(sp, kToOffset));
__ LoadP(r5, MemOperand(sp, kFromOffset));
// If either to or from had the smi tag bit set, then fail to generic runtime
__ JumpIfNotSmi(r4, &runtime);
__ JumpIfNotSmi(r5, &runtime);
__ SmiUntag(r4);
__ SmiUntag(r5);
// Both r4 and r5 are untagged integers.
// We want to bailout to runtime here if From is negative.
__ blt(&runtime); // From < 0.
__ CmpLogicalP(r5, r4);
__ bgt(&runtime); // Fail if from > to.
__ SubP(r4, r4, r5);
// Make sure first argument is a string.
__ LoadP(r2, MemOperand(sp, kStringOffset));
__ JumpIfSmi(r2, &runtime);
Condition is_string = masm->IsObjectStringType(r2, r3);
__ b(NegateCondition(is_string), &runtime);
Label single_char;
__ CmpP(r4, Operand(1));
__ b(eq, &single_char);
// Short-cut for the case of trivial substring.
Label return_r2;
// r2: original string
// r4: result string length
__ LoadP(r6, FieldMemOperand(r2, String::kLengthOffset));
__ SmiUntag(r0, r6);
__ CmpLogicalP(r4, r0);
// Return original string.
__ beq(&return_r2);
// Longer than original string's length or negative: unsafe arguments.
__ bgt(&runtime);
// Shorter than original string's length: an actual substring.
// Deal with different string types: update the index if necessary
// and put the underlying string into r7.
// r2: original string
// r3: instance type
// r4: length
// r5: from index (untagged)
Label underlying_unpacked, sliced_string, seq_or_external_string;
// If the string is not indirect, it can only be sequential or external.
STATIC_ASSERT(kIsIndirectStringMask == (kSlicedStringTag & kConsStringTag));
STATIC_ASSERT(kIsIndirectStringMask != 0);
__ mov(r0, Operand(kIsIndirectStringMask));
__ AndP(r0, r3);
__ beq(&seq_or_external_string);
__ mov(r0, Operand(kSlicedNotConsMask));
__ AndP(r0, r3);
__ bne(&sliced_string);
// Cons string. Check whether it is flat, then fetch first part.
__ LoadP(r7, FieldMemOperand(r2, ConsString::kSecondOffset));
__ CompareRoot(r7, Heap::kempty_stringRootIndex);
__ bne(&runtime);
__ LoadP(r7, FieldMemOperand(r2, ConsString::kFirstOffset));
// Update instance type.
__ LoadP(r3, FieldMemOperand(r7, HeapObject::kMapOffset));
__ LoadlB(r3, FieldMemOperand(r3, Map::kInstanceTypeOffset));
__ b(&underlying_unpacked);
__ bind(&sliced_string);
// Sliced string. Fetch parent and correct start index by offset.
__ LoadP(r7, FieldMemOperand(r2, SlicedString::kParentOffset));
__ LoadP(r6, FieldMemOperand(r2, SlicedString::kOffsetOffset));
__ SmiUntag(r3, r6);
__ AddP(r5, r3); // Add offset to index.
// Update instance type.
__ LoadP(r3, FieldMemOperand(r7, HeapObject::kMapOffset));
__ LoadlB(r3, FieldMemOperand(r3, Map::kInstanceTypeOffset));
__ b(&underlying_unpacked);
__ bind(&seq_or_external_string);
// Sequential or external string. Just move string to the expected register.
__ LoadRR(r7, r2);
__ bind(&underlying_unpacked);
if (FLAG_string_slices) {
Label copy_routine;
// r7: underlying subject string
// r3: instance type of underlying subject string
// r4: length
// r5: adjusted start index (untagged)
__ CmpP(r4, Operand(SlicedString::kMinLength));
// Short slice. Copy instead of slicing.
__ blt(©_routine);
// Allocate new sliced string. At this point we do not reload the instance
// type including the string encoding because we simply rely on the info
// provided by the original string. It does not matter if the original
// string's encoding is wrong because we always have to recheck encoding of
// the newly created string's parent anyways due to externalized strings.
Label two_byte_slice, set_slice_header;
STATIC_ASSERT((kStringEncodingMask & kOneByteStringTag) != 0);
STATIC_ASSERT((kStringEncodingMask & kTwoByteStringTag) == 0);
__ mov(r0, Operand(kStringEncodingMask));
__ AndP(r0, r3);
__ beq(&two_byte_slice);
__ AllocateOneByteSlicedString(r2, r4, r8, r9, &runtime);
__ b(&set_slice_header);
__ bind(&two_byte_slice);
__ AllocateTwoByteSlicedString(r2, r4, r8, r9, &runtime);
__ bind(&set_slice_header);
__ SmiTag(r5);
__ StoreP(r7, FieldMemOperand(r2, SlicedString::kParentOffset));
__ StoreP(r5, FieldMemOperand(r2, SlicedString::kOffsetOffset));
__ b(&return_r2);
__ bind(©_routine);
}
// r7: underlying subject string
// r3: instance type of underlying subject string
// r4: length
// r5: adjusted start index (untagged)
Label two_byte_sequential, sequential_string, allocate_result;
STATIC_ASSERT(kExternalStringTag != 0);
STATIC_ASSERT(kSeqStringTag == 0);
__ mov(r0, Operand(kExternalStringTag));
__ AndP(r0, r3);
__ beq(&sequential_string);
// Handle external string.
// Rule out short external strings.
STATIC_ASSERT(kShortExternalStringTag != 0);
__ mov(r0, Operand(kShortExternalStringTag));
__ AndP(r0, r3);
__ bne(&runtime);
__ LoadP(r7, FieldMemOperand(r7, ExternalString::kResourceDataOffset));
// r7 already points to the first character of underlying string.
__ b(&allocate_result);
__ bind(&sequential_string);
// Locate first character of underlying subject string.
STATIC_ASSERT(SeqTwoByteString::kHeaderSize == SeqOneByteString::kHeaderSize);
__ AddP(r7, Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
__ bind(&allocate_result);
// Sequential acii string. Allocate the result.
STATIC_ASSERT((kOneByteStringTag & kStringEncodingMask) != 0);
__ mov(r0, Operand(kStringEncodingMask));
__ AndP(r0, r3);
__ beq(&two_byte_sequential);
// Allocate and copy the resulting one-byte string.
__ AllocateOneByteString(r2, r4, r6, r8, r9, &runtime);
// Locate first character of substring to copy.
__ AddP(r7, r5);
// Locate first character of result.
__ AddP(r3, r2, Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
// r2: result string
// r3: first character of result string
// r4: result string length
// r7: first character of substring to copy
STATIC_ASSERT((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
StringHelper::GenerateCopyCharacters(masm, r3, r7, r4, r5,
String::ONE_BYTE_ENCODING);
__ b(&return_r2);
// Allocate and copy the resulting two-byte string.
__ bind(&two_byte_sequential);
__ AllocateTwoByteString(r2, r4, r6, r8, r9, &runtime);
// Locate first character of substring to copy.
__ ShiftLeftP(r3, r5, Operand(1));
__ AddP(r7, r3);
// Locate first character of result.
__ AddP(r3, r2, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
// r2: result string.
// r3: first character of result.
// r4: result length.
// r7: first character of substring to copy.
STATIC_ASSERT((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
StringHelper::GenerateCopyCharacters(masm, r3, r7, r4, r5,
String::TWO_BYTE_ENCODING);
__ bind(&return_r2);
Counters* counters = isolate()->counters();
__ IncrementCounter(counters->sub_string_native(), 1, r5, r6);
__ Drop(3);
__ Ret();
// Just jump to runtime to create the sub string.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kSubString);
__ bind(&single_char);
// r2: original string
// r3: instance type
// r4: length
// r5: from index (untagged)
__ SmiTag(r5, r5);
StringCharAtGenerator generator(r2, r5, r4, r2, &runtime, &runtime, &runtime,
STRING_INDEX_IS_NUMBER, RECEIVER_IS_STRING);
generator.GenerateFast(masm);
__ Drop(3);
__ Ret();
generator.SkipSlow(masm, &runtime);
}
void ToNumberStub::Generate(MacroAssembler* masm) {
// The ToNumber stub takes one argument in r2.
STATIC_ASSERT(kSmiTag == 0);
__ TestIfSmi(r2);
__ Ret(eq);
__ CompareObjectType(r2, r3, r3, HEAP_NUMBER_TYPE);
// r2: receiver
// r3: receiver instance type
Label not_heap_number;
__ bne(¬_heap_number);
__ Ret();
__ bind(¬_heap_number);
NonNumberToNumberStub stub(masm->isolate());
__ TailCallStub(&stub);
}
void NonNumberToNumberStub::Generate(MacroAssembler* masm) {
// The NonNumberToNumber stub takes one argument in r2.
__ AssertNotNumber(r2);
__ CompareObjectType(r2, r3, r3, FIRST_NONSTRING_TYPE);
// r2: receiver
// r3: receiver instance type
StringToNumberStub stub(masm->isolate());
__ TailCallStub(&stub, lt);
Label not_oddball;
__ CmpP(r3, Operand(ODDBALL_TYPE));
__ bne(¬_oddball, Label::kNear);
__ LoadP(r2, FieldMemOperand(r2, Oddball::kToNumberOffset));
__ b(r14);
__ bind(¬_oddball);
__ push(r2); // Push argument.
__ TailCallRuntime(Runtime::kToNumber);
}
void StringToNumberStub::Generate(MacroAssembler* masm) {
// The StringToNumber stub takes one argument in r2.
__ AssertString(r2);
// Check if string has a cached array index.
Label runtime;
__ LoadlW(r4, FieldMemOperand(r2, String::kHashFieldOffset));
__ And(r0, r4, Operand(String::kContainsCachedArrayIndexMask));
__ bne(&runtime);
__ IndexFromHash(r4, r2);
__ Ret();
__ bind(&runtime);
__ push(r2); // Push argument.
__ TailCallRuntime(Runtime::kStringToNumber);
}
void ToStringStub::Generate(MacroAssembler* masm) {
// The ToString stub takes one argument in r2.
Label done;
Label is_number;
__ JumpIfSmi(r2, &is_number);
__ CompareObjectType(r2, r3, r3, FIRST_NONSTRING_TYPE);
// r2: receiver
// r3: receiver instance type
__ blt(&done);
Label not_heap_number;
__ CmpP(r3, Operand(HEAP_NUMBER_TYPE));
__ bne(¬_heap_number);
__ bind(&is_number);
NumberToStringStub stub(isolate());
__ TailCallStub(&stub);
__ bind(¬_heap_number);
Label not_oddball;
__ CmpP(r3, Operand(ODDBALL_TYPE));
__ bne(¬_oddball);
__ LoadP(r2, FieldMemOperand(r2, Oddball::kToStringOffset));
__ Ret();
__ bind(¬_oddball);
__ push(r2); // Push argument.
__ TailCallRuntime(Runtime::kToString);
__ bind(&done);
__ Ret();
}
void ToNameStub::Generate(MacroAssembler* masm) {
// The ToName stub takes one argument in r2.
Label is_number;
__ JumpIfSmi(r2, &is_number);
STATIC_ASSERT(FIRST_NAME_TYPE == FIRST_TYPE);
__ CompareObjectType(r2, r3, r3, LAST_NAME_TYPE);
// r2: receiver
// r3: receiver instance type
__ Ret(le);
Label not_heap_number;
__ CmpP(r3, Operand(HEAP_NUMBER_TYPE));
__ bne(¬_heap_number);
__ bind(&is_number);
NumberToStringStub stub(isolate());
__ TailCallStub(&stub);
__ bind(¬_heap_number);
Label not_oddball;
__ CmpP(r3, Operand(ODDBALL_TYPE));
__ bne(¬_oddball);
__ LoadP(r2, FieldMemOperand(r2, Oddball::kToStringOffset));
__ Ret();
__ bind(¬_oddball);
__ push(r2); // Push argument.
__ TailCallRuntime(Runtime::kToName);
}
void StringHelper::GenerateFlatOneByteStringEquals(MacroAssembler* masm,
Register left,
Register right,
Register scratch1,
Register scratch2) {
Register length = scratch1;
// Compare lengths.
Label strings_not_equal, check_zero_length;
__ LoadP(length, FieldMemOperand(left, String::kLengthOffset));
__ LoadP(scratch2, FieldMemOperand(right, String::kLengthOffset));
__ CmpP(length, scratch2);
__ beq(&check_zero_length);
__ bind(&strings_not_equal);
__ LoadSmiLiteral(r2, Smi::FromInt(NOT_EQUAL));
__ Ret();
// Check if the length is zero.
Label compare_chars;
__ bind(&check_zero_length);
STATIC_ASSERT(kSmiTag == 0);
__ CmpP(length, Operand::Zero());
__ bne(&compare_chars);
__ LoadSmiLiteral(r2, Smi::FromInt(EQUAL));
__ Ret();
// Compare characters.
__ bind(&compare_chars);
GenerateOneByteCharsCompareLoop(masm, left, right, length, scratch2,
&strings_not_equal);
// Characters are equal.
__ LoadSmiLiteral(r2, Smi::FromInt(EQUAL));
__ Ret();
}
void StringHelper::GenerateCompareFlatOneByteStrings(
MacroAssembler* masm, Register left, Register right, Register scratch1,
Register scratch2, Register scratch3) {
Label skip, result_not_equal, compare_lengths;
// Find minimum length and length difference.
__ LoadP(scratch1, FieldMemOperand(left, String::kLengthOffset));
__ LoadP(scratch2, FieldMemOperand(right, String::kLengthOffset));
__ SubP(scratch3, scratch1, scratch2 /*, LeaveOE, SetRC*/);
// Removing RC looks okay here.
Register length_delta = scratch3;
__ ble(&skip, Label::kNear);
__ LoadRR(scratch1, scratch2);
__ bind(&skip);
Register min_length = scratch1;
STATIC_ASSERT(kSmiTag == 0);
__ CmpP(min_length, Operand::Zero());
__ beq(&compare_lengths);
// Compare loop.
GenerateOneByteCharsCompareLoop(masm, left, right, min_length, scratch2,
&result_not_equal);
// Compare lengths - strings up to min-length are equal.
__ bind(&compare_lengths);
DCHECK(Smi::FromInt(EQUAL) == static_cast<Smi*>(0));
// Use length_delta as result if it's zero.
__ LoadRR(r2, length_delta);
__ CmpP(length_delta, Operand::Zero());
__ bind(&result_not_equal);
// Conditionally update the result based either on length_delta or
// the last comparion performed in the loop above.
Label less_equal, equal;
__ ble(&less_equal);
__ LoadSmiLiteral(r2, Smi::FromInt(GREATER));
__ Ret();
__ bind(&less_equal);
__ beq(&equal);
__ LoadSmiLiteral(r2, Smi::FromInt(LESS));
__ bind(&equal);
__ Ret();
}
void StringHelper::GenerateOneByteCharsCompareLoop(
MacroAssembler* masm, Register left, Register right, Register length,
Register scratch1, Label* chars_not_equal) {
// Change index to run from -length to -1 by adding length to string
// start. This means that loop ends when index reaches zero, which
// doesn't need an additional compare.
__ SmiUntag(length);
__ AddP(scratch1, length,
Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
__ AddP(left, scratch1);
__ AddP(right, scratch1);
__ LoadComplementRR(length, length);
Register index = length; // index = -length;
// Compare loop.
Label loop;
__ bind(&loop);
__ LoadlB(scratch1, MemOperand(left, index));
__ LoadlB(r0, MemOperand(right, index));
__ CmpP(scratch1, r0);
__ bne(chars_not_equal);
__ AddP(index, Operand(1));
__ CmpP(index, Operand::Zero());
__ bne(&loop);
}
void BinaryOpICWithAllocationSiteStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r3 : left
// -- r2 : right
// r3: second string
// -----------------------------------
// Load r4 with the allocation site. We stick an undefined dummy value here
// and replace it with the real allocation site later when we instantiate this
// stub in BinaryOpICWithAllocationSiteStub::GetCodeCopyFromTemplate().
__ Move(r4, handle(isolate()->heap()->undefined_value()));
// Make sure that we actually patched the allocation site.
if (FLAG_debug_code) {
__ TestIfSmi(r4);
__ Assert(ne, kExpectedAllocationSite, cr0);
__ push(r4);
__ LoadP(r4, FieldMemOperand(r4, HeapObject::kMapOffset));
__ CompareRoot(r4, Heap::kAllocationSiteMapRootIndex);
__ pop(r4);
__ Assert(eq, kExpectedAllocationSite);
}
// Tail call into the stub that handles binary operations with allocation
// sites.
BinaryOpWithAllocationSiteStub stub(isolate(), state());
__ TailCallStub(&stub);
}
void CompareICStub::GenerateBooleans(MacroAssembler* masm) {
DCHECK_EQ(CompareICState::BOOLEAN, state());
Label miss;
__ CheckMap(r3, r4, Heap::kBooleanMapRootIndex, &miss, DO_SMI_CHECK);
__ CheckMap(r2, r5, Heap::kBooleanMapRootIndex, &miss, DO_SMI_CHECK);
if (!Token::IsEqualityOp(op())) {
__ LoadP(r3, FieldMemOperand(r3, Oddball::kToNumberOffset));
__ AssertSmi(r3);
__ LoadP(r2, FieldMemOperand(r2, Oddball::kToNumberOffset));
__ AssertSmi(r2);
}
__ SubP(r2, r3, r2);
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void CompareICStub::GenerateSmis(MacroAssembler* masm) {
DCHECK(state() == CompareICState::SMI);
Label miss;
__ OrP(r4, r3, r2);
__ JumpIfNotSmi(r4, &miss);
if (GetCondition() == eq) {
// For equality we do not care about the sign of the result.
// __ sub(r2, r2, r3, SetCC);
__ SubP(r2, r2, r3);
} else {
// Untag before subtracting to avoid handling overflow.
__ SmiUntag(r3);
__ SmiUntag(r2);
__ SubP(r2, r3, r2);
}
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void CompareICStub::GenerateNumbers(MacroAssembler* masm) {
DCHECK(state() == CompareICState::NUMBER);
Label generic_stub;
Label unordered, maybe_undefined1, maybe_undefined2;
Label miss;
Label equal, less_than;
if (left() == CompareICState::SMI) {
__ JumpIfNotSmi(r3, &miss);
}
if (right() == CompareICState::SMI) {
__ JumpIfNotSmi(r2, &miss);
}
// Inlining the double comparison and falling back to the general compare
// stub if NaN is involved.
// Load left and right operand.
Label done, left, left_smi, right_smi;
__ JumpIfSmi(r2, &right_smi);
__ CheckMap(r2, r4, Heap::kHeapNumberMapRootIndex, &maybe_undefined1,
DONT_DO_SMI_CHECK);
__ LoadDouble(d1, FieldMemOperand(r2, HeapNumber::kValueOffset));
__ b(&left);
__ bind(&right_smi);
__ SmiToDouble(d1, r2);
__ bind(&left);
__ JumpIfSmi(r3, &left_smi);
__ CheckMap(r3, r4, Heap::kHeapNumberMapRootIndex, &maybe_undefined2,
DONT_DO_SMI_CHECK);
__ LoadDouble(d0, FieldMemOperand(r3, HeapNumber::kValueOffset));
__ b(&done);
__ bind(&left_smi);
__ SmiToDouble(d0, r3);
__ bind(&done);
// Compare operands
__ cdbr(d0, d1);
// Don't base result on status bits when a NaN is involved.
__ bunordered(&unordered);
// Return a result of -1, 0, or 1, based on status bits.
__ beq(&equal);
__ blt(&less_than);
// assume greater than
__ LoadImmP(r2, Operand(GREATER));
__ Ret();
__ bind(&equal);
__ LoadImmP(r2, Operand(EQUAL));
__ Ret();
__ bind(&less_than);
__ LoadImmP(r2, Operand(LESS));
__ Ret();
__ bind(&unordered);
__ bind(&generic_stub);
CompareICStub stub(isolate(), op(), CompareICState::GENERIC,
CompareICState::GENERIC, CompareICState::GENERIC);
__ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
__ bind(&maybe_undefined1);
if (Token::IsOrderedRelationalCompareOp(op())) {
__ CompareRoot(r2, Heap::kUndefinedValueRootIndex);
__ bne(&miss);
__ JumpIfSmi(r3, &unordered);
__ CompareObjectType(r3, r4, r4, HEAP_NUMBER_TYPE);
__ bne(&maybe_undefined2);
__ b(&unordered);
}
__ bind(&maybe_undefined2);
if (Token::IsOrderedRelationalCompareOp(op())) {
__ CompareRoot(r3, Heap::kUndefinedValueRootIndex);
__ beq(&unordered);
}
__ bind(&miss);
GenerateMiss(masm);
}
void CompareICStub::GenerateInternalizedStrings(MacroAssembler* masm) {
DCHECK(state() == CompareICState::INTERNALIZED_STRING);
Label miss, not_equal;
// Registers containing left and right operands respectively.
Register left = r3;
Register right = r2;
Register tmp1 = r4;
Register tmp2 = r5;
// Check that both operands are heap objects.
__ JumpIfEitherSmi(left, right, &miss);
// Check that both operands are symbols.
__ LoadP(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
__ LoadP(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
__ LoadlB(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
__ LoadlB(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
__ OrP(tmp1, tmp1, tmp2);
__ AndP(r0, tmp1, Operand(kIsNotStringMask | kIsNotInternalizedMask));
__ bne(&miss);
// Internalized strings are compared by identity.
__ CmpP(left, right);
__ bne(¬_equal);
// Make sure r2 is non-zero. At this point input operands are
// guaranteed to be non-zero.
DCHECK(right.is(r2));
STATIC_ASSERT(EQUAL == 0);
STATIC_ASSERT(kSmiTag == 0);
__ LoadSmiLiteral(r2, Smi::FromInt(EQUAL));
__ bind(¬_equal);
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void CompareICStub::GenerateUniqueNames(MacroAssembler* masm) {
DCHECK(state() == CompareICState::UNIQUE_NAME);
DCHECK(GetCondition() == eq);
Label miss;
// Registers containing left and right operands respectively.
Register left = r3;
Register right = r2;
Register tmp1 = r4;
Register tmp2 = r5;
// Check that both operands are heap objects.
__ JumpIfEitherSmi(left, right, &miss);
// Check that both operands are unique names. This leaves the instance
// types loaded in tmp1 and tmp2.
__ LoadP(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
__ LoadP(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
__ LoadlB(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
__ LoadlB(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
__ JumpIfNotUniqueNameInstanceType(tmp1, &miss);
__ JumpIfNotUniqueNameInstanceType(tmp2, &miss);
// Unique names are compared by identity.
__ CmpP(left, right);
__ bne(&miss);
// Make sure r2 is non-zero. At this point input operands are
// guaranteed to be non-zero.
DCHECK(right.is(r2));
STATIC_ASSERT(EQUAL == 0);
STATIC_ASSERT(kSmiTag == 0);
__ LoadSmiLiteral(r2, Smi::FromInt(EQUAL));
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void CompareICStub::GenerateStrings(MacroAssembler* masm) {
DCHECK(state() == CompareICState::STRING);
Label miss, not_identical, is_symbol;
bool equality = Token::IsEqualityOp(op());
// Registers containing left and right operands respectively.
Register left = r3;
Register right = r2;
Register tmp1 = r4;
Register tmp2 = r5;
Register tmp3 = r6;
Register tmp4 = r7;
// Check that both operands are heap objects.
__ JumpIfEitherSmi(left, right, &miss);
// Check that both operands are strings. This leaves the instance
// types loaded in tmp1 and tmp2.
__ LoadP(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
__ LoadP(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
__ LoadlB(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
__ LoadlB(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
STATIC_ASSERT(kNotStringTag != 0);
__ OrP(tmp3, tmp1, tmp2);
__ AndP(r0, tmp3, Operand(kIsNotStringMask));
__ bne(&miss);
// Fast check for identical strings.
__ CmpP(left, right);
STATIC_ASSERT(EQUAL == 0);
STATIC_ASSERT(kSmiTag == 0);
__ bne(¬_identical);
__ LoadSmiLiteral(r2, Smi::FromInt(EQUAL));
__ Ret();
__ bind(¬_identical);
// Handle not identical strings.
// Check that both strings are internalized strings. If they are, we're done
// because we already know they are not identical. We know they are both
// strings.
if (equality) {
DCHECK(GetCondition() == eq);
STATIC_ASSERT(kInternalizedTag == 0);
__ OrP(tmp3, tmp1, tmp2);
__ AndP(r0, tmp3, Operand(kIsNotInternalizedMask));
__ bne(&is_symbol);
// Make sure r2 is non-zero. At this point input operands are
// guaranteed to be non-zero.
DCHECK(right.is(r2));
__ Ret();
__ bind(&is_symbol);
}
// Check that both strings are sequential one-byte.
Label runtime;
__ JumpIfBothInstanceTypesAreNotSequentialOneByte(tmp1, tmp2, tmp3, tmp4,
&runtime);
// Compare flat one-byte strings. Returns when done.
if (equality) {
StringHelper::GenerateFlatOneByteStringEquals(masm, left, right, tmp1,
tmp2);
} else {
StringHelper::GenerateCompareFlatOneByteStrings(masm, left, right, tmp1,
tmp2, tmp3);
}
// Handle more complex cases in runtime.
__ bind(&runtime);
if (equality) {
{
FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
__ Push(left, right);
__ CallRuntime(Runtime::kStringEqual);
}
__ LoadRoot(r3, Heap::kTrueValueRootIndex);
__ SubP(r2, r2, r3);
__ Ret();
} else {
__ Push(left, right);
__ TailCallRuntime(Runtime::kStringCompare);
}
__ bind(&miss);
GenerateMiss(masm);
}
void CompareICStub::GenerateReceivers(MacroAssembler* masm) {
DCHECK_EQ(CompareICState::RECEIVER, state());
Label miss;
__ AndP(r4, r3, r2);
__ JumpIfSmi(r4, &miss);
STATIC_ASSERT(LAST_TYPE == LAST_JS_RECEIVER_TYPE);
__ CompareObjectType(r2, r4, r4, FIRST_JS_RECEIVER_TYPE);
__ blt(&miss);
__ CompareObjectType(r3, r4, r4, FIRST_JS_RECEIVER_TYPE);
__ blt(&miss);
DCHECK(GetCondition() == eq);
__ SubP(r2, r2, r3);
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void CompareICStub::GenerateKnownReceivers(MacroAssembler* masm) {
Label miss;
Handle<WeakCell> cell = Map::WeakCellForMap(known_map_);
__ AndP(r4, r3, r2);
__ JumpIfSmi(r4, &miss);
__ GetWeakValue(r6, cell);
__ LoadP(r4, FieldMemOperand(r2, HeapObject::kMapOffset));
__ LoadP(r5, FieldMemOperand(r3, HeapObject::kMapOffset));
__ CmpP(r4, r6);
__ bne(&miss);
__ CmpP(r5, r6);
__ bne(&miss);
if (Token::IsEqualityOp(op())) {
__ SubP(r2, r2, r3);
__ Ret();
} else {
if (op() == Token::LT || op() == Token::LTE) {
__ LoadSmiLiteral(r4, Smi::FromInt(GREATER));
} else {
__ LoadSmiLiteral(r4, Smi::FromInt(LESS));
}
__ Push(r3, r2, r4);
__ TailCallRuntime(Runtime::kCompare);
}
__ bind(&miss);
GenerateMiss(masm);
}
void CompareICStub::GenerateMiss(MacroAssembler* masm) {
{
// Call the runtime system in a fresh internal frame.
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(r3, r2);
__ Push(r3, r2);
__ LoadSmiLiteral(r0, Smi::FromInt(op()));
__ push(r0);
__ CallRuntime(Runtime::kCompareIC_Miss);
// Compute the entry point of the rewritten stub.
__ AddP(r4, r2, Operand(Code::kHeaderSize - kHeapObjectTag));
// Restore registers.
__ Pop(r3, r2);
}
__ JumpToJSEntry(r4);
}
// This stub is paired with DirectCEntryStub::GenerateCall
void DirectCEntryStub::Generate(MacroAssembler* masm) {
__ CleanseP(r14);
// Statement positions are expected to be recorded when the target
// address is loaded.
__ positions_recorder()->WriteRecordedPositions();
__ b(ip); // Callee will return to R14 directly
}
void DirectCEntryStub::GenerateCall(MacroAssembler* masm, Register target) {
#if ABI_USES_FUNCTION_DESCRIPTORS && !defined(USE_SIMULATOR)
// Native AIX/S390X Linux use a function descriptor.
__ LoadP(ToRegister(ABI_TOC_REGISTER), MemOperand(target, kPointerSize));
__ LoadP(target, MemOperand(target, 0)); // Instruction address
#else
// ip needs to be set for DirectCEentryStub::Generate, and also
// for ABI_CALL_VIA_IP.
__ Move(ip, target);
#endif
__ call(GetCode(), RelocInfo::CODE_TARGET); // Call the stub.
}
void NameDictionaryLookupStub::GenerateNegativeLookup(
MacroAssembler* masm, Label* miss, Label* done, Register receiver,
Register properties, Handle<Name> name, Register scratch0) {
DCHECK(name->IsUniqueName());
// If names of slots in range from 1 to kProbes - 1 for the hash value are
// not equal to the name and kProbes-th slot is not used (its name is the
// undefined value), it guarantees the hash table doesn't contain the
// property. It's true even if some slots represent deleted properties
// (their names are the hole value).
for (int i = 0; i < kInlinedProbes; i++) {
// scratch0 points to properties hash.
// Compute the masked index: (hash + i + i * i) & mask.
Register index = scratch0;
// Capacity is smi 2^n.
__ LoadP(index, FieldMemOperand(properties, kCapacityOffset));
__ SubP(index, Operand(1));
__ LoadSmiLiteral(
ip, Smi::FromInt(name->Hash() + NameDictionary::GetProbeOffset(i)));
__ AndP(index, ip);
// Scale the index by multiplying by the entry size.
STATIC_ASSERT(NameDictionary::kEntrySize == 3);
__ ShiftLeftP(ip, index, Operand(1));
__ AddP(index, ip); // index *= 3.
Register entity_name = scratch0;
// Having undefined at this place means the name is not contained.
Register tmp = properties;
__ SmiToPtrArrayOffset(ip, index);
__ AddP(tmp, properties, ip);
__ LoadP(entity_name, FieldMemOperand(tmp, kElementsStartOffset));
DCHECK(!tmp.is(entity_name));
__ CompareRoot(entity_name, Heap::kUndefinedValueRootIndex);
__ beq(done);
// Stop if found the property.
__ CmpP(entity_name, Operand(Handle<Name>(name)));
__ beq(miss);
Label good;
__ CompareRoot(entity_name, Heap::kTheHoleValueRootIndex);
__ beq(&good);
// Check if the entry name is not a unique name.
__ LoadP(entity_name, FieldMemOperand(entity_name, HeapObject::kMapOffset));
__ LoadlB(entity_name,
FieldMemOperand(entity_name, Map::kInstanceTypeOffset));
__ JumpIfNotUniqueNameInstanceType(entity_name, miss);
__ bind(&good);
// Restore the properties.
__ LoadP(properties,
FieldMemOperand(receiver, JSObject::kPropertiesOffset));
}
const int spill_mask = (r0.bit() | r8.bit() | r7.bit() | r6.bit() | r5.bit() |
r4.bit() | r3.bit() | r2.bit());
__ LoadRR(r0, r14);
__ MultiPush(spill_mask);
__ LoadP(r2, FieldMemOperand(receiver, JSObject::kPropertiesOffset));
__ mov(r3, Operand(Handle<Name>(name)));
NameDictionaryLookupStub stub(masm->isolate(), NEGATIVE_LOOKUP);
__ CallStub(&stub);
__ CmpP(r2, Operand::Zero());
__ MultiPop(spill_mask); // MultiPop does not touch condition flags
__ LoadRR(r14, r0);
__ beq(done);
__ bne(miss);
}
// Probe the name dictionary in the |elements| register. Jump to the
// |done| label if a property with the given name is found. Jump to
// the |miss| label otherwise.
// If lookup was successful |scratch2| will be equal to elements + 4 * index.
void NameDictionaryLookupStub::GeneratePositiveLookup(
MacroAssembler* masm, Label* miss, Label* done, Register elements,
Register name, Register scratch1, Register scratch2) {
DCHECK(!elements.is(scratch1));
DCHECK(!elements.is(scratch2));
DCHECK(!name.is(scratch1));
DCHECK(!name.is(scratch2));
__ AssertName(name);
// Compute the capacity mask.
__ LoadP(scratch1, FieldMemOperand(elements, kCapacityOffset));
__ SmiUntag(scratch1); // convert smi to int
__ SubP(scratch1, Operand(1));
// Generate an unrolled loop that performs a few probes before
// giving up. Measurements done on Gmail indicate that 2 probes
// cover ~93% of loads from dictionaries.
for (int i = 0; i < kInlinedProbes; i++) {
// Compute the masked index: (hash + i + i * i) & mask.
__ LoadlW(scratch2, FieldMemOperand(name, String::kHashFieldOffset));
if (i > 0) {
// Add the probe offset (i + i * i) left shifted to avoid right shifting
// the hash in a separate instruction. The value hash + i + i * i is right
// shifted in the following and instruction.
DCHECK(NameDictionary::GetProbeOffset(i) <
1 << (32 - Name::kHashFieldOffset));
__ AddP(scratch2,
Operand(NameDictionary::GetProbeOffset(i) << Name::kHashShift));
}
__ srl(scratch2, Operand(String::kHashShift));
__ AndP(scratch2, scratch1);
// Scale the index by multiplying by the entry size.
STATIC_ASSERT(NameDictionary::kEntrySize == 3);
// scratch2 = scratch2 * 3.
__ ShiftLeftP(ip, scratch2, Operand(1));
__ AddP(scratch2, ip);
// Check if the key is identical to the name.
__ ShiftLeftP(ip, scratch2, Operand(kPointerSizeLog2));
__ AddP(scratch2, elements, ip);
__ LoadP(ip, FieldMemOperand(scratch2, kElementsStartOffset));
__ CmpP(name, ip);
__ beq(done);
}
const int spill_mask = (r0.bit() | r8.bit() | r7.bit() | r6.bit() | r5.bit() |
r4.bit() | r3.bit() | r2.bit()) &
~(scratch1.bit() | scratch2.bit());
__ LoadRR(r0, r14);
__ MultiPush(spill_mask);
if (name.is(r2)) {
DCHECK(!elements.is(r3));
__ LoadRR(r3, name);
__ LoadRR(r2, elements);
} else {
__ LoadRR(r2, elements);
__ LoadRR(r3, name);
}
NameDictionaryLookupStub stub(masm->isolate(), POSITIVE_LOOKUP);
__ CallStub(&stub);
__ LoadRR(r1, r2);
__ LoadRR(scratch2, r4);
__ MultiPop(spill_mask);
__ LoadRR(r14, r0);
__ CmpP(r1, Operand::Zero());
__ bne(done);
__ beq(miss);
}
void NameDictionaryLookupStub::Generate(MacroAssembler* masm) {
// This stub overrides SometimesSetsUpAFrame() to return false. That means
// we cannot call anything that could cause a GC from this stub.
// Registers:
// result: NameDictionary to probe
// r3: key
// dictionary: NameDictionary to probe.
// index: will hold an index of entry if lookup is successful.
// might alias with result_.
// Returns:
// result_ is zero if lookup failed, non zero otherwise.
Register result = r2;
Register dictionary = r2;
Register key = r3;
Register index = r4;
Register mask = r5;
Register hash = r6;
Register undefined = r7;
Register entry_key = r8;
Register scratch = r8;
Label in_dictionary, maybe_in_dictionary, not_in_dictionary;
__ LoadP(mask, FieldMemOperand(dictionary, kCapacityOffset));
__ SmiUntag(mask);
__ SubP(mask, Operand(1));
__ LoadlW(hash, FieldMemOperand(key, String::kHashFieldOffset));
__ LoadRoot(undefined, Heap::kUndefinedValueRootIndex);
for (int i = kInlinedProbes; i < kTotalProbes; i++) {
// Compute the masked index: (hash + i + i * i) & mask.
// Capacity is smi 2^n.
if (i > 0) {
// Add the probe offset (i + i * i) left shifted to avoid right shifting
// the hash in a separate instruction. The value hash + i + i * i is right
// shifted in the following and instruction.
DCHECK(NameDictionary::GetProbeOffset(i) <
1 << (32 - Name::kHashFieldOffset));
__ AddP(index, hash,
Operand(NameDictionary::GetProbeOffset(i) << Name::kHashShift));
} else {
__ LoadRR(index, hash);
}
__ ShiftRight(r0, index, Operand(String::kHashShift));
__ AndP(index, r0, mask);
// Scale the index by multiplying by the entry size.
STATIC_ASSERT(NameDictionary::kEntrySize == 3);
__ ShiftLeftP(scratch, index, Operand(1));
__ AddP(index, scratch); // index *= 3.
__ ShiftLeftP(scratch, index, Operand(kPointerSizeLog2));
__ AddP(index, dictionary, scratch);
__ LoadP(entry_key, FieldMemOperand(index, kElementsStartOffset));
// Having undefined at this place means the name is not contained.
__ CmpP(entry_key, undefined);
__ beq(¬_in_dictionary);
// Stop if found the property.
__ CmpP(entry_key, key);
__ beq(&in_dictionary);
if (i != kTotalProbes - 1 && mode() == NEGATIVE_LOOKUP) {
// Check if the entry name is not a unique name.
__ LoadP(entry_key, FieldMemOperand(entry_key, HeapObject::kMapOffset));
__ LoadlB(entry_key,
FieldMemOperand(entry_key, Map::kInstanceTypeOffset));
__ JumpIfNotUniqueNameInstanceType(entry_key, &maybe_in_dictionary);
}
}
__ bind(&maybe_in_dictionary);
// If we are doing negative lookup then probing failure should be
// treated as a lookup success. For positive lookup probing failure
// should be treated as lookup failure.
if (mode() == POSITIVE_LOOKUP) {
__ LoadImmP(result, Operand::Zero());
__ Ret();
}
__ bind(&in_dictionary);
__ LoadImmP(result, Operand(1));
__ Ret();
__ bind(¬_in_dictionary);
__ LoadImmP(result, Operand::Zero());
__ Ret();
}
void StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(
Isolate* isolate) {
StoreBufferOverflowStub stub1(isolate, kDontSaveFPRegs);
stub1.GetCode();
// Hydrogen code stubs need stub2 at snapshot time.
StoreBufferOverflowStub stub2(isolate, kSaveFPRegs);
stub2.GetCode();
}
// Takes the input in 3 registers: address_ value_ and object_. A pointer to
// the value has just been written into the object, now this stub makes sure
// we keep the GC informed. The word in the object where the value has been
// written is in the address register.
void RecordWriteStub::Generate(MacroAssembler* masm) {
Label skip_to_incremental_noncompacting;
Label skip_to_incremental_compacting;
// The first two branch instructions are generated with labels so as to
// get the offset fixed up correctly by the bind(Label*) call. We patch
// it back and forth between branch condition True and False
// when we start and stop incremental heap marking.
// See RecordWriteStub::Patch for details.
// Clear the bit, branch on True for NOP action initially
__ b(CC_NOP, &skip_to_incremental_noncompacting);
__ b(CC_NOP, &skip_to_incremental_compacting);
if (remembered_set_action() == EMIT_REMEMBERED_SET) {
__ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
MacroAssembler::kReturnAtEnd);
}
__ Ret();
__ bind(&skip_to_incremental_noncompacting);
GenerateIncremental(masm, INCREMENTAL);
__ bind(&skip_to_incremental_compacting);
GenerateIncremental(masm, INCREMENTAL_COMPACTION);
// Initial mode of the stub is expected to be STORE_BUFFER_ONLY.
// Will be checked in IncrementalMarking::ActivateGeneratedStub.
// patching not required on S390 as the initial path is effectively NOP
}
void RecordWriteStub::GenerateIncremental(MacroAssembler* masm, Mode mode) {
regs_.Save(masm);
if (remembered_set_action() == EMIT_REMEMBERED_SET) {
Label dont_need_remembered_set;
__ LoadP(regs_.scratch0(), MemOperand(regs_.address(), 0));
__ JumpIfNotInNewSpace(regs_.scratch0(), // Value.
regs_.scratch0(), &dont_need_remembered_set);
__ JumpIfInNewSpace(regs_.object(), regs_.scratch0(),
&dont_need_remembered_set);
// First notify the incremental marker if necessary, then update the
// remembered set.
CheckNeedsToInformIncrementalMarker(
masm, kUpdateRememberedSetOnNoNeedToInformIncrementalMarker, mode);
InformIncrementalMarker(masm);
regs_.Restore(masm);
__ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
MacroAssembler::kReturnAtEnd);
__ bind(&dont_need_remembered_set);
}
CheckNeedsToInformIncrementalMarker(
masm, kReturnOnNoNeedToInformIncrementalMarker, mode);
InformIncrementalMarker(masm);
regs_.Restore(masm);
__ Ret();
}
void RecordWriteStub::InformIncrementalMarker(MacroAssembler* masm) {
regs_.SaveCallerSaveRegisters(masm, save_fp_regs_mode());
int argument_count = 3;
__ PrepareCallCFunction(argument_count, regs_.scratch0());
Register address =
r2.is(regs_.address()) ? regs_.scratch0() : regs_.address();
DCHECK(!address.is(regs_.object()));
DCHECK(!address.is(r2));
__ LoadRR(address, regs_.address());
__ LoadRR(r2, regs_.object());
__ LoadRR(r3, address);
__ mov(r4, Operand(ExternalReference::isolate_address(isolate())));
AllowExternalCallThatCantCauseGC scope(masm);
__ CallCFunction(
ExternalReference::incremental_marking_record_write_function(isolate()),
argument_count);
regs_.RestoreCallerSaveRegisters(masm, save_fp_regs_mode());
}
void RecordWriteStub::CheckNeedsToInformIncrementalMarker(
MacroAssembler* masm, OnNoNeedToInformIncrementalMarker on_no_need,
Mode mode) {
Label on_black;
Label need_incremental;
Label need_incremental_pop_scratch;
DCHECK((~Page::kPageAlignmentMask & 0xffff) == 0);
__ AndP(regs_.scratch0(), regs_.object(), Operand(~Page::kPageAlignmentMask));
__ LoadP(
regs_.scratch1(),
MemOperand(regs_.scratch0(), MemoryChunk::kWriteBarrierCounterOffset));
__ SubP(regs_.scratch1(), regs_.scratch1(), Operand(1));
__ StoreP(
regs_.scratch1(),
MemOperand(regs_.scratch0(), MemoryChunk::kWriteBarrierCounterOffset));
__ CmpP(regs_.scratch1(), Operand::Zero()); // S390, we could do better here
__ blt(&need_incremental);
// Let's look at the color of the object: If it is not black we don't have
// to inform the incremental marker.
__ JumpIfBlack(regs_.object(), regs_.scratch0(), regs_.scratch1(), &on_black);
regs_.Restore(masm);
if (on_no_need == kUpdateRememberedSetOnNoNeedToInformIncrementalMarker) {
__ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
MacroAssembler::kReturnAtEnd);
} else {
__ Ret();
}
__ bind(&on_black);
// Get the value from the slot.
__ LoadP(regs_.scratch0(), MemOperand(regs_.address(), 0));
if (mode == INCREMENTAL_COMPACTION) {
Label ensure_not_white;
__ CheckPageFlag(regs_.scratch0(), // Contains value.
regs_.scratch1(), // Scratch.
MemoryChunk::kEvacuationCandidateMask, eq,
&ensure_not_white);
__ CheckPageFlag(regs_.object(),
regs_.scratch1(), // Scratch.
MemoryChunk::kSkipEvacuationSlotsRecordingMask, eq,
&need_incremental);
__ bind(&ensure_not_white);
}
// We need extra registers for this, so we push the object and the address
// register temporarily.
__ Push(regs_.object(), regs_.address());
__ JumpIfWhite(regs_.scratch0(), // The value.
regs_.scratch1(), // Scratch.
regs_.object(), // Scratch.
regs_.address(), // Scratch.
&need_incremental_pop_scratch);
__ Pop(regs_.object(), regs_.address());
regs_.Restore(masm);
if (on_no_need == kUpdateRememberedSetOnNoNeedToInformIncrementalMarker) {
__ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
MacroAssembler::kReturnAtEnd);
} else {
__ Ret();
}
__ bind(&need_incremental_pop_scratch);
__ Pop(regs_.object(), regs_.address());
__ bind(&need_incremental);
// Fall through when we need to inform the incremental marker.
}
void StubFailureTrampolineStub::Generate(MacroAssembler* masm) {
CEntryStub ces(isolate(), 1, kSaveFPRegs);
__ Call(ces.GetCode(), RelocInfo::CODE_TARGET);
int parameter_count_offset =
StubFailureTrampolineFrameConstants::kArgumentsLengthOffset;
__ LoadP(r3, MemOperand(fp, parameter_count_offset));
if (function_mode() == JS_FUNCTION_STUB_MODE) {
__ AddP(r3, Operand(1));
}
masm->LeaveFrame(StackFrame::STUB_FAILURE_TRAMPOLINE);
__ ShiftLeftP(r3, r3, Operand(kPointerSizeLog2));
__ la(sp, MemOperand(r3, sp));
__ Ret();
}
void LoadICTrampolineStub::Generate(MacroAssembler* masm) {
__ EmitLoadTypeFeedbackVector(LoadWithVectorDescriptor::VectorRegister());
LoadICStub stub(isolate(), state());
stub.GenerateForTrampoline(masm);
}
void KeyedLoadICTrampolineStub::Generate(MacroAssembler* masm) {
__ EmitLoadTypeFeedbackVector(LoadWithVectorDescriptor::VectorRegister());
KeyedLoadICStub stub(isolate(), state());
stub.GenerateForTrampoline(masm);
}
void CallICTrampolineStub::Generate(MacroAssembler* masm) {
__ EmitLoadTypeFeedbackVector(r4);
CallICStub stub(isolate(), state());
__ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
}
void LoadICStub::Generate(MacroAssembler* masm) { GenerateImpl(masm, false); }
void LoadICStub::GenerateForTrampoline(MacroAssembler* masm) {
GenerateImpl(masm, true);
}
static void HandleArrayCases(MacroAssembler* masm, Register feedback,
Register receiver_map, Register scratch1,
Register scratch2, bool is_polymorphic,
Label* miss) {
// feedback initially contains the feedback array
Label next_loop, prepare_next;
Label start_polymorphic;
Register cached_map = scratch1;
__ LoadP(cached_map,
FieldMemOperand(feedback, FixedArray::OffsetOfElementAt(0)));
__ LoadP(cached_map, FieldMemOperand(cached_map, WeakCell::kValueOffset));
__ CmpP(receiver_map, cached_map);
__ bne(&start_polymorphic, Label::kNear);
// found, now call handler.
Register handler = feedback;
__ LoadP(handler,
FieldMemOperand(feedback, FixedArray::OffsetOfElementAt(1)));
__ AddP(ip, handler, Operand(Code::kHeaderSize - kHeapObjectTag));
__ Jump(ip);
Register length = scratch2;
__ bind(&start_polymorphic);
__ LoadP(length, FieldMemOperand(feedback, FixedArray::kLengthOffset));
if (!is_polymorphic) {
// If the IC could be monomorphic we have to make sure we don't go past the
// end of the feedback array.
__ CmpSmiLiteral(length, Smi::FromInt(2), r0);
__ beq(miss);
}
Register too_far = length;
Register pointer_reg = feedback;
// +-----+------+------+-----+-----+ ... ----+
// | map | len | wm0 | h0 | wm1 | hN |
// +-----+------+------+-----+-----+ ... ----+
// 0 1 2 len-1
// ^ ^
// | |
// pointer_reg too_far
// aka feedback scratch2
// also need receiver_map
// use cached_map (scratch1) to look in the weak map values.
__ SmiToPtrArrayOffset(r0, length);
__ AddP(too_far, feedback, r0);
__ AddP(too_far, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
__ AddP(pointer_reg, feedback,
Operand(FixedArray::OffsetOfElementAt(2) - kHeapObjectTag));
__ bind(&next_loop);
__ LoadP(cached_map, MemOperand(pointer_reg));
__ LoadP(cached_map, FieldMemOperand(cached_map, WeakCell::kValueOffset));
__ CmpP(receiver_map, cached_map);
__ bne(&prepare_next, Label::kNear);
__ LoadP(handler, MemOperand(pointer_reg, kPointerSize));
__ AddP(ip, handler, Operand(Code::kHeaderSize - kHeapObjectTag));
__ Jump(ip);
__ bind(&prepare_next);
__ AddP(pointer_reg, Operand(kPointerSize * 2));
__ CmpP(pointer_reg, too_far);
__ blt(&next_loop, Label::kNear);
// We exhausted our array of map handler pairs.
__ b(miss);
}
static void HandleMonomorphicCase(MacroAssembler* masm, Register receiver,
Register receiver_map, Register feedback,
Register vector, Register slot,
Register scratch, Label* compare_map,
Label* load_smi_map, Label* try_array) {
__ JumpIfSmi(receiver, load_smi_map);
__ LoadP(receiver_map, FieldMemOperand(receiver, HeapObject::kMapOffset));
__ bind(compare_map);
Register cached_map = scratch;
// Move the weak map into the weak_cell register.
__ LoadP(cached_map, FieldMemOperand(feedback, WeakCell::kValueOffset));
__ CmpP(cached_map, receiver_map);
__ bne(try_array);
Register handler = feedback;
__ SmiToPtrArrayOffset(r1, slot);
__ LoadP(handler,
FieldMemOperand(r1, vector, FixedArray::kHeaderSize + kPointerSize));
__ AddP(ip, handler, Operand(Code::kHeaderSize - kHeapObjectTag));
__ Jump(ip);
}
void LoadICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
Register receiver = LoadWithVectorDescriptor::ReceiverRegister(); // r3
Register name = LoadWithVectorDescriptor::NameRegister(); // r4
Register vector = LoadWithVectorDescriptor::VectorRegister(); // r5
Register slot = LoadWithVectorDescriptor::SlotRegister(); // r2
Register feedback = r6;
Register receiver_map = r7;
Register scratch1 = r8;
__ SmiToPtrArrayOffset(r1, slot);
__ LoadP(feedback, FieldMemOperand(r1, vector, FixedArray::kHeaderSize));
// Try to quickly handle the monomorphic case without knowing for sure
// if we have a weak cell in feedback. We do know it's safe to look
// at WeakCell::kValueOffset.
Label try_array, load_smi_map, compare_map;
Label not_array, miss;
HandleMonomorphicCase(masm, receiver, receiver_map, feedback, vector, slot,
scratch1, &compare_map, &load_smi_map, &try_array);
// Is it a fixed array?
__ bind(&try_array);
__ LoadP(scratch1, FieldMemOperand(feedback, HeapObject::kMapOffset));
__ CompareRoot(scratch1, Heap::kFixedArrayMapRootIndex);
__ bne(¬_array, Label::kNear);
HandleArrayCases(masm, feedback, receiver_map, scratch1, r9, true, &miss);
__ bind(¬_array);
__ CompareRoot(feedback, Heap::kmegamorphic_symbolRootIndex);
__ bne(&miss);
Code::Flags code_flags =
Code::RemoveHolderFromFlags(Code::ComputeHandlerFlags(Code::LOAD_IC));
masm->isolate()->stub_cache()->GenerateProbe(masm, Code::LOAD_IC, code_flags,
receiver, name, feedback,
receiver_map, scratch1, r9);
__ bind(&miss);
LoadIC::GenerateMiss(masm);
__ bind(&load_smi_map);
__ LoadRoot(receiver_map, Heap::kHeapNumberMapRootIndex);
__ b(&compare_map);
}
void KeyedLoadICStub::Generate(MacroAssembler* masm) {
GenerateImpl(masm, false);
}
void KeyedLoadICStub::GenerateForTrampoline(MacroAssembler* masm) {
GenerateImpl(masm, true);
}
void KeyedLoadICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
Register receiver = LoadWithVectorDescriptor::ReceiverRegister(); // r3
Register key = LoadWithVectorDescriptor::NameRegister(); // r4
Register vector = LoadWithVectorDescriptor::VectorRegister(); // r5
Register slot = LoadWithVectorDescriptor::SlotRegister(); // r2
Register feedback = r6;
Register receiver_map = r7;
Register scratch1 = r8;
__ SmiToPtrArrayOffset(r1, slot);
__ LoadP(feedback, FieldMemOperand(r1, vector, FixedArray::kHeaderSize));
// Try to quickly handle the monomorphic case without knowing for sure
// if we have a weak cell in feedback. We do know it's safe to look
// at WeakCell::kValueOffset.
Label try_array, load_smi_map, compare_map;
Label not_array, miss;
HandleMonomorphicCase(masm, receiver, receiver_map, feedback, vector, slot,
scratch1, &compare_map, &load_smi_map, &try_array);
__ bind(&try_array);
// Is it a fixed array?
__ LoadP(scratch1, FieldMemOperand(feedback, HeapObject::kMapOffset));
__ CompareRoot(scratch1, Heap::kFixedArrayMapRootIndex);
__ bne(¬_array);
// We have a polymorphic element handler.
Label polymorphic, try_poly_name;
__ bind(&polymorphic);
HandleArrayCases(masm, feedback, receiver_map, scratch1, r9, true, &miss);
__ bind(¬_array);
// Is it generic?
__ CompareRoot(feedback, Heap::kmegamorphic_symbolRootIndex);
__ bne(&try_poly_name);
Handle<Code> megamorphic_stub =
KeyedLoadIC::ChooseMegamorphicStub(masm->isolate(), GetExtraICState());
__ Jump(megamorphic_stub, RelocInfo::CODE_TARGET);
__ bind(&try_poly_name);
// We might have a name in feedback, and a fixed array in the next slot.
__ CmpP(key, feedback);
__ bne(&miss);
// If the name comparison succeeded, we know we have a fixed array with
// at least one map/handler pair.
__ SmiToPtrArrayOffset(r1, slot);
__ LoadP(feedback,
FieldMemOperand(r1, vector, FixedArray::kHeaderSize + kPointerSize));
HandleArrayCases(masm, feedback, receiver_map, scratch1, r9, false, &miss);
__ bind(&miss);
KeyedLoadIC::GenerateMiss(masm);
__ bind(&load_smi_map);
__ LoadRoot(receiver_map, Heap::kHeapNumberMapRootIndex);
__ b(&compare_map);
}
void VectorStoreICTrampolineStub::Generate(MacroAssembler* masm) {
__ EmitLoadTypeFeedbackVector(VectorStoreICDescriptor::VectorRegister());
VectorStoreICStub stub(isolate(), state());
stub.GenerateForTrampoline(masm);
}
void VectorKeyedStoreICTrampolineStub::Generate(MacroAssembler* masm) {
__ EmitLoadTypeFeedbackVector(VectorStoreICDescriptor::VectorRegister());
VectorKeyedStoreICStub stub(isolate(), state());
stub.GenerateForTrampoline(masm);
}
void VectorStoreICStub::Generate(MacroAssembler* masm) {
GenerateImpl(masm, false);
}
void VectorStoreICStub::GenerateForTrampoline(MacroAssembler* masm) {
GenerateImpl(masm, true);
}
void VectorStoreICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
Register receiver = VectorStoreICDescriptor::ReceiverRegister(); // r3
Register key = VectorStoreICDescriptor::NameRegister(); // r4
Register vector = VectorStoreICDescriptor::VectorRegister(); // r5
Register slot = VectorStoreICDescriptor::SlotRegister(); // r6
DCHECK(VectorStoreICDescriptor::ValueRegister().is(r2)); // r2
Register feedback = r7;
Register receiver_map = r8;
Register scratch1 = r9;
__ SmiToPtrArrayOffset(r0, slot);
__ AddP(feedback, vector, r0);
__ LoadP(feedback, FieldMemOperand(feedback, FixedArray::kHeaderSize));
// Try to quickly handle the monomorphic case without knowing for sure
// if we have a weak cell in feedback. We do know it's safe to look
// at WeakCell::kValueOffset.
Label try_array, load_smi_map, compare_map;
Label not_array, miss;
HandleMonomorphicCase(masm, receiver, receiver_map, feedback, vector, slot,
scratch1, &compare_map, &load_smi_map, &try_array);
// Is it a fixed array?
__ bind(&try_array);
__ LoadP(scratch1, FieldMemOperand(feedback, HeapObject::kMapOffset));
__ CompareRoot(scratch1, Heap::kFixedArrayMapRootIndex);
__ bne(¬_array);
Register scratch2 = ip;
HandleArrayCases(masm, feedback, receiver_map, scratch1, scratch2, true,
&miss);
__ bind(¬_array);
__ CompareRoot(feedback, Heap::kmegamorphic_symbolRootIndex);
__ bne(&miss);
Code::Flags code_flags =
Code::RemoveHolderFromFlags(Code::ComputeHandlerFlags(Code::STORE_IC));
masm->isolate()->stub_cache()->GenerateProbe(
masm, Code::STORE_IC, code_flags, receiver, key, feedback, receiver_map,
scratch1, scratch2);
__ bind(&miss);
StoreIC::GenerateMiss(masm);
__ bind(&load_smi_map);
__ LoadRoot(receiver_map, Heap::kHeapNumberMapRootIndex);
__ b(&compare_map);
}
void VectorKeyedStoreICStub::Generate(MacroAssembler* masm) {
GenerateImpl(masm, false);
}
void VectorKeyedStoreICStub::GenerateForTrampoline(MacroAssembler* masm) {
GenerateImpl(masm, true);
}
static void HandlePolymorphicStoreCase(MacroAssembler* masm, Register feedback,
Register receiver_map, Register scratch1,
Register scratch2, Label* miss) {
// feedback initially contains the feedback array
Label next_loop, prepare_next;
Label start_polymorphic;
Label transition_call;
Register cached_map = scratch1;
Register too_far = scratch2;
Register pointer_reg = feedback;
__ LoadP(too_far, FieldMemOperand(feedback, FixedArray::kLengthOffset));
// +-----+------+------+-----+-----+-----+ ... ----+
// | map | len | wm0 | wt0 | h0 | wm1 | hN |
// +-----+------+------+-----+-----+ ----+ ... ----+
// 0 1 2 len-1
// ^ ^
// | |
// pointer_reg too_far
// aka feedback scratch2
// also need receiver_map
// use cached_map (scratch1) to look in the weak map values.
__ SmiToPtrArrayOffset(r0, too_far);
__ AddP(too_far, feedback, r0);
__ AddP(too_far, too_far, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
__ AddP(pointer_reg, feedback,
Operand(FixedArray::OffsetOfElementAt(0) - kHeapObjectTag));
__ bind(&next_loop);
__ LoadP(cached_map, MemOperand(pointer_reg));
__ LoadP(cached_map, FieldMemOperand(cached_map, WeakCell::kValueOffset));
__ CmpP(receiver_map, cached_map);
__ bne(&prepare_next);
// Is it a transitioning store?
__ LoadP(too_far, MemOperand(pointer_reg, kPointerSize));
__ CompareRoot(too_far, Heap::kUndefinedValueRootIndex);
__ bne(&transition_call);
__ LoadP(pointer_reg, MemOperand(pointer_reg, kPointerSize * 2));
__ AddP(ip, pointer_reg, Operand(Code::kHeaderSize - kHeapObjectTag));
__ Jump(ip);
__ bind(&transition_call);
__ LoadP(too_far, FieldMemOperand(too_far, WeakCell::kValueOffset));
__ JumpIfSmi(too_far, miss);
__ LoadP(receiver_map, MemOperand(pointer_reg, kPointerSize * 2));
// Load the map into the correct register.
DCHECK(feedback.is(VectorStoreTransitionDescriptor::MapRegister()));
__ LoadRR(feedback, too_far);
__ AddP(ip, receiver_map, Operand(Code::kHeaderSize - kHeapObjectTag));
__ Jump(ip);
__ bind(&prepare_next);
__ AddP(pointer_reg, pointer_reg, Operand(kPointerSize * 3));
__ CmpLogicalP(pointer_reg, too_far);
__ blt(&next_loop);
// We exhausted our array of map handler pairs.
__ b(miss);
}
void VectorKeyedStoreICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
Register receiver = VectorStoreICDescriptor::ReceiverRegister(); // r3
Register key = VectorStoreICDescriptor::NameRegister(); // r4
Register vector = VectorStoreICDescriptor::VectorRegister(); // r5
Register slot = VectorStoreICDescriptor::SlotRegister(); // r6
DCHECK(VectorStoreICDescriptor::ValueRegister().is(r2)); // r2
Register feedback = r7;
Register receiver_map = r8;
Register scratch1 = r9;
__ SmiToPtrArrayOffset(r0, slot);
__ AddP(feedback, vector, r0);
__ LoadP(feedback, FieldMemOperand(feedback, FixedArray::kHeaderSize));
// Try to quickly handle the monomorphic case without knowing for sure
// if we have a weak cell in feedback. We do know it's safe to look
// at WeakCell::kValueOffset.
Label try_array, load_smi_map, compare_map;
Label not_array, miss;
HandleMonomorphicCase(masm, receiver, receiver_map, feedback, vector, slot,
scratch1, &compare_map, &load_smi_map, &try_array);
__ bind(&try_array);
// Is it a fixed array?
__ LoadP(scratch1, FieldMemOperand(feedback, HeapObject::kMapOffset));
__ CompareRoot(scratch1, Heap::kFixedArrayMapRootIndex);
__ bne(¬_array);
// We have a polymorphic element handler.
Label polymorphic, try_poly_name;
__ bind(&polymorphic);
Register scratch2 = ip;
HandlePolymorphicStoreCase(masm, feedback, receiver_map, scratch1, scratch2,
&miss);
__ bind(¬_array);
// Is it generic?
__ CompareRoot(feedback, Heap::kmegamorphic_symbolRootIndex);
__ bne(&try_poly_name);
Handle<Code> megamorphic_stub =
KeyedStoreIC::ChooseMegamorphicStub(masm->isolate(), GetExtraICState());
__ Jump(megamorphic_stub, RelocInfo::CODE_TARGET);
__ bind(&try_poly_name);
// We might have a name in feedback, and a fixed array in the next slot.
__ CmpP(key, feedback);
__ bne(&miss);
// If the name comparison succeeded, we know we have a fixed array with
// at least one map/handler pair.
__ SmiToPtrArrayOffset(r0, slot);
__ AddP(feedback, vector, r0);
__ LoadP(feedback,
FieldMemOperand(feedback, FixedArray::kHeaderSize + kPointerSize));
HandleArrayCases(masm, feedback, receiver_map, scratch1, scratch2, false,
&miss);
__ bind(&miss);
KeyedStoreIC::GenerateMiss(masm);
__ bind(&load_smi_map);
__ LoadRoot(receiver_map, Heap::kHeapNumberMapRootIndex);
__ b(&compare_map);
}
void ProfileEntryHookStub::MaybeCallEntryHook(MacroAssembler* masm) {
if (masm->isolate()->function_entry_hook() != NULL) {
PredictableCodeSizeScope predictable(masm,
#if V8_TARGET_ARCH_S390X
40);
#elif V8_HOST_ARCH_S390
36);
#else
32);
#endif
ProfileEntryHookStub stub(masm->isolate());
__ CleanseP(r14);
__ Push(r14, ip);
__ CallStub(&stub); // BRASL
__ Pop(r14, ip);
}
}
void ProfileEntryHookStub::Generate(MacroAssembler* masm) {
// The entry hook is a "push lr" instruction (LAY+ST/STG), followed by a call.
#if V8_TARGET_ARCH_S390X
const int32_t kReturnAddressDistanceFromFunctionStart =
Assembler::kCallTargetAddressOffset + 18; // LAY + STG * 2
#elif V8_HOST_ARCH_S390
const int32_t kReturnAddressDistanceFromFunctionStart =
Assembler::kCallTargetAddressOffset + 18; // NILH + LAY + ST * 2
#else
const int32_t kReturnAddressDistanceFromFunctionStart =
Assembler::kCallTargetAddressOffset + 14; // LAY + ST * 2
#endif
// This should contain all kJSCallerSaved registers.
const RegList kSavedRegs = kJSCallerSaved | // Caller saved registers.
r7.bit(); // Saved stack pointer.
// We also save r14+ip, so count here is one higher than the mask indicates.
const int32_t kNumSavedRegs = kNumJSCallerSaved + 3;
// Save all caller-save registers as this may be called from anywhere.
__ CleanseP(r14);
__ LoadRR(ip, r14);
__ MultiPush(kSavedRegs | ip.bit());
// Compute the function's address for the first argument.
__ SubP(r2, ip, Operand(kReturnAddressDistanceFromFunctionStart));
// The caller's return address is two slots above the saved temporaries.
// Grab that for the second argument to the hook.
__ lay(r3, MemOperand(sp, kNumSavedRegs * kPointerSize));
// Align the stack if necessary.
int frame_alignment = masm->ActivationFrameAlignment();
if (frame_alignment > kPointerSize) {
__ LoadRR(r7, sp);
DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
__ ClearRightImm(sp, sp, Operand(WhichPowerOf2(frame_alignment)));
}
#if !defined(USE_SIMULATOR)
uintptr_t entry_hook =
reinterpret_cast<uintptr_t>(isolate()->function_entry_hook());
__ mov(ip, Operand(entry_hook));
#if ABI_USES_FUNCTION_DESCRIPTORS
// Function descriptor
__ LoadP(ToRegister(ABI_TOC_REGISTER), MemOperand(ip, kPointerSize));
__ LoadP(ip, MemOperand(ip, 0));
// ip already set.
#endif
#endif
// zLinux ABI requires caller's frame to have sufficient space for callee
// preserved regsiter save area.
__ LoadImmP(r0, Operand::Zero());
__ StoreP(r0, MemOperand(sp, -kCalleeRegisterSaveAreaSize -
kNumRequiredStackFrameSlots * kPointerSize));
__ lay(sp, MemOperand(sp, -kCalleeRegisterSaveAreaSize -
kNumRequiredStackFrameSlots * kPointerSize));
#if defined(USE_SIMULATOR)
// Under the simulator we need to indirect the entry hook through a
// trampoline function at a known address.
// It additionally takes an isolate as a third parameter
__ mov(r4, Operand(ExternalReference::isolate_address(isolate())));
ApiFunction dispatcher(FUNCTION_ADDR(EntryHookTrampoline));
__ mov(ip, Operand(ExternalReference(
&dispatcher, ExternalReference::BUILTIN_CALL, isolate())));
#endif
__ Call(ip);
// zLinux ABI requires caller's frame to have sufficient space for callee
// preserved regsiter save area.
__ la(sp, MemOperand(sp, kCalleeRegisterSaveAreaSize +
kNumRequiredStackFrameSlots * kPointerSize));
// Restore the stack pointer if needed.
if (frame_alignment > kPointerSize) {
__ LoadRR(sp, r7);
}
// Also pop lr to get Ret(0).
__ MultiPop(kSavedRegs | ip.bit());
__ LoadRR(r14, ip);
__ Ret();
}
template <class T>
static void CreateArrayDispatch(MacroAssembler* masm,
AllocationSiteOverrideMode mode) {
if (mode == DISABLE_ALLOCATION_SITES) {
T stub(masm->isolate(), GetInitialFastElementsKind(), mode);
__ TailCallStub(&stub);
} else if (mode == DONT_OVERRIDE) {
int last_index =
GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND);
for (int i = 0; i <= last_index; ++i) {
ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
__ CmpP(r5, Operand(kind));
T stub(masm->isolate(), kind);
__ TailCallStub(&stub, eq);
}
// If we reached this point there is a problem.
__ Abort(kUnexpectedElementsKindInArrayConstructor);
} else {
UNREACHABLE();
}
}
static void CreateArrayDispatchOneArgument(MacroAssembler* masm,
AllocationSiteOverrideMode mode) {
// r4 - allocation site (if mode != DISABLE_ALLOCATION_SITES)
// r5 - kind (if mode != DISABLE_ALLOCATION_SITES)
// r2 - number of arguments
// r3 - constructor?
// sp[0] - last argument
Label normal_sequence;
if (mode == DONT_OVERRIDE) {
STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
STATIC_ASSERT(FAST_ELEMENTS == 2);
STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
STATIC_ASSERT(FAST_DOUBLE_ELEMENTS == 4);
STATIC_ASSERT(FAST_HOLEY_DOUBLE_ELEMENTS == 5);
// is the low bit set? If so, we are holey and that is good.
__ AndP(r0, r5, Operand(1));
__ bne(&normal_sequence);
}
// look at the first argument
__ LoadP(r7, MemOperand(sp, 0));
__ CmpP(r7, Operand::Zero());
__ beq(&normal_sequence);
if (mode == DISABLE_ALLOCATION_SITES) {
ElementsKind initial = GetInitialFastElementsKind();
ElementsKind holey_initial = GetHoleyElementsKind(initial);
ArraySingleArgumentConstructorStub stub_holey(
masm->isolate(), holey_initial, DISABLE_ALLOCATION_SITES);
__ TailCallStub(&stub_holey);
__ bind(&normal_sequence);
ArraySingleArgumentConstructorStub stub(masm->isolate(), initial,
DISABLE_ALLOCATION_SITES);
__ TailCallStub(&stub);
} else if (mode == DONT_OVERRIDE) {
// We are going to create a holey array, but our kind is non-holey.
// Fix kind and retry (only if we have an allocation site in the slot).
__ AddP(r5, r5, Operand(1));
if (FLAG_debug_code) {
__ LoadP(r7, FieldMemOperand(r4, 0));
__ CompareRoot(r7, Heap::kAllocationSiteMapRootIndex);
__ Assert(eq, kExpectedAllocationSite);
}
// Save the resulting elements kind in type info. We can't just store r5
// in the AllocationSite::transition_info field because elements kind is
// restricted to a portion of the field...upper bits need to be left alone.
STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0);
__ LoadP(r6, FieldMemOperand(r4, AllocationSite::kTransitionInfoOffset));
__ AddSmiLiteral(r6, r6, Smi::FromInt(kFastElementsKindPackedToHoley), r0);
__ StoreP(r6, FieldMemOperand(r4, AllocationSite::kTransitionInfoOffset));
__ bind(&normal_sequence);
int last_index =
GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND);
for (int i = 0; i <= last_index; ++i) {
ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
__ CmpP(r5, Operand(kind));
ArraySingleArgumentConstructorStub stub(masm->isolate(), kind);
__ TailCallStub(&stub, eq);
}
// If we reached this point there is a problem.
__ Abort(kUnexpectedElementsKindInArrayConstructor);
} else {
UNREACHABLE();
}
}
template <class T>
static void ArrayConstructorStubAheadOfTimeHelper(Isolate* isolate) {
int to_index =
GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND);
for (int i = 0; i <= to_index; ++i) {
ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
T stub(isolate, kind);
stub.GetCode();
if (AllocationSite::GetMode(kind) != DONT_TRACK_ALLOCATION_SITE) {
T stub1(isolate, kind, DISABLE_ALLOCATION_SITES);
stub1.GetCode();
}
}
}
void ArrayConstructorStubBase::GenerateStubsAheadOfTime(Isolate* isolate) {
ArrayConstructorStubAheadOfTimeHelper<ArrayNoArgumentConstructorStub>(
isolate);
ArrayConstructorStubAheadOfTimeHelper<ArraySingleArgumentConstructorStub>(
isolate);
ArrayConstructorStubAheadOfTimeHelper<ArrayNArgumentsConstructorStub>(
isolate);
}
void InternalArrayConstructorStubBase::GenerateStubsAheadOfTime(
Isolate* isolate) {
ElementsKind kinds[2] = {FAST_ELEMENTS, FAST_HOLEY_ELEMENTS};
for (int i = 0; i < 2; i++) {
// For internal arrays we only need a few things
InternalArrayNoArgumentConstructorStub stubh1(isolate, kinds[i]);
stubh1.GetCode();
InternalArraySingleArgumentConstructorStub stubh2(isolate, kinds[i]);
stubh2.GetCode();
InternalArrayNArgumentsConstructorStub stubh3(isolate, kinds[i]);
stubh3.GetCode();
}
}
void ArrayConstructorStub::GenerateDispatchToArrayStub(
MacroAssembler* masm, AllocationSiteOverrideMode mode) {
if (argument_count() == ANY) {
Label not_zero_case, not_one_case;
__ CmpP(r2, Operand::Zero());
__ bne(¬_zero_case);
CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode);
__ bind(¬_zero_case);
__ CmpP(r2, Operand(1));
__ bgt(¬_one_case);
CreateArrayDispatchOneArgument(masm, mode);
__ bind(¬_one_case);
CreateArrayDispatch<ArrayNArgumentsConstructorStub>(masm, mode);
} else if (argument_count() == NONE) {
CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode);
} else if (argument_count() == ONE) {
CreateArrayDispatchOneArgument(masm, mode);
} else if (argument_count() == MORE_THAN_ONE) {
CreateArrayDispatch<ArrayNArgumentsConstructorStub>(masm, mode);
} else {
UNREACHABLE();
}
}
void ArrayConstructorStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r2 : argc (only if argument_count() == ANY)
// -- r3 : constructor
// -- r4 : AllocationSite or undefined
// -- r5 : new target
// -- sp[0] : return address
// -- sp[4] : last argument
// -----------------------------------
if (FLAG_debug_code) {
// The array construct code is only set for the global and natives
// builtin Array functions which always have maps.
// Initial map for the builtin Array function should be a map.
__ LoadP(r6, FieldMemOperand(r3, JSFunction::kPrototypeOrInitialMapOffset));
// Will both indicate a NULL and a Smi.
__ TestIfSmi(r6);
__ Assert(ne, kUnexpectedInitialMapForArrayFunction, cr0);
__ CompareObjectType(r6, r6, r7, MAP_TYPE);
__ Assert(eq, kUnexpectedInitialMapForArrayFunction);
// We should either have undefined in r4 or a valid AllocationSite
__ AssertUndefinedOrAllocationSite(r4, r6);
}
// Enter the context of the Array function.
__ LoadP(cp, FieldMemOperand(r3, JSFunction::kContextOffset));
Label subclassing;
__ CmpP(r5, r3);
__ bne(&subclassing, Label::kNear);
Label no_info;
// Get the elements kind and case on that.
__ CompareRoot(r4, Heap::kUndefinedValueRootIndex);
__ beq(&no_info);
__ LoadP(r5, FieldMemOperand(r4, AllocationSite::kTransitionInfoOffset));
__ SmiUntag(r5);
STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0);
__ AndP(r5, Operand(AllocationSite::ElementsKindBits::kMask));
GenerateDispatchToArrayStub(masm, DONT_OVERRIDE);
__ bind(&no_info);
GenerateDispatchToArrayStub(masm, DISABLE_ALLOCATION_SITES);
__ bind(&subclassing);
switch (argument_count()) {
case ANY:
case MORE_THAN_ONE:
__ ShiftLeftP(r1, r2, Operand(kPointerSizeLog2));
__ StoreP(r3, MemOperand(sp, r1));
__ AddP(r2, r2, Operand(3));
break;
case NONE:
__ StoreP(r3, MemOperand(sp, 0 * kPointerSize));
__ LoadImmP(r2, Operand(3));
break;
case ONE:
__ StoreP(r3, MemOperand(sp, 1 * kPointerSize));
__ LoadImmP(r2, Operand(4));
break;
}
__ Push(r5, r4);
__ JumpToExternalReference(ExternalReference(Runtime::kNewArray, isolate()));
}
void InternalArrayConstructorStub::GenerateCase(MacroAssembler* masm,
ElementsKind kind) {
__ CmpLogicalP(r2, Operand(1));
InternalArrayNoArgumentConstructorStub stub0(isolate(), kind);
__ TailCallStub(&stub0, lt);
InternalArrayNArgumentsConstructorStub stubN(isolate(), kind);
__ TailCallStub(&stubN, gt);
if (IsFastPackedElementsKind(kind)) {
// We might need to create a holey array
// look at the first argument
__ LoadP(r5, MemOperand(sp, 0));
__ CmpP(r5, Operand::Zero());
InternalArraySingleArgumentConstructorStub stub1_holey(
isolate(), GetHoleyElementsKind(kind));
__ TailCallStub(&stub1_holey, ne);
}
InternalArraySingleArgumentConstructorStub stub1(isolate(), kind);
__ TailCallStub(&stub1);
}
void InternalArrayConstructorStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r2 : argc
// -- r3 : constructor
// -- sp[0] : return address
// -- sp[4] : last argument
// -----------------------------------
if (FLAG_debug_code) {
// The array construct code is only set for the global and natives
// builtin Array functions which always have maps.
// Initial map for the builtin Array function should be a map.
__ LoadP(r5, FieldMemOperand(r3, JSFunction::kPrototypeOrInitialMapOffset));
// Will both indicate a NULL and a Smi.
__ TestIfSmi(r5);
__ Assert(ne, kUnexpectedInitialMapForArrayFunction, cr0);
__ CompareObjectType(r5, r5, r6, MAP_TYPE);
__ Assert(eq, kUnexpectedInitialMapForArrayFunction);
}
// Figure out the right elements kind
__ LoadP(r5, FieldMemOperand(r3, JSFunction::kPrototypeOrInitialMapOffset));
// Load the map's "bit field 2" into |result|.
__ LoadlB(r5, FieldMemOperand(r5, Map::kBitField2Offset));
// Retrieve elements_kind from bit field 2.
__ DecodeField<Map::ElementsKindBits>(r5);
if (FLAG_debug_code) {
Label done;
__ CmpP(r5, Operand(FAST_ELEMENTS));
__ beq(&done);
__ CmpP(r5, Operand(FAST_HOLEY_ELEMENTS));
__ Assert(eq, kInvalidElementsKindForInternalArrayOrInternalPackedArray);
__ bind(&done);
}
Label fast_elements_case;
__ CmpP(r5, Operand(FAST_ELEMENTS));
__ beq(&fast_elements_case);
GenerateCase(masm, FAST_HOLEY_ELEMENTS);
__ bind(&fast_elements_case);
GenerateCase(masm, FAST_ELEMENTS);
}
void FastNewObjectStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r3 : target
// -- r5 : new target
// -- cp : context
// -- lr : return address
// -----------------------------------
__ AssertFunction(r3);
__ AssertReceiver(r5);
// Verify that the new target is a JSFunction.
Label new_object;
__ CompareObjectType(r5, r4, r4, JS_FUNCTION_TYPE);
__ bne(&new_object);
// Load the initial map and verify that it's in fact a map.
__ LoadP(r4, FieldMemOperand(r5, JSFunction::kPrototypeOrInitialMapOffset));
__ JumpIfSmi(r4, &new_object);
__ CompareObjectType(r4, r2, r2, MAP_TYPE);
__ bne(&new_object);
// Fall back to runtime if the target differs from the new target's
// initial map constructor.
__ LoadP(r2, FieldMemOperand(r4, Map::kConstructorOrBackPointerOffset));
__ CmpP(r2, r3);
__ bne(&new_object);
// Allocate the JSObject on the heap.
Label allocate, done_allocate;
__ LoadlB(r6, FieldMemOperand(r4, Map::kInstanceSizeOffset));
__ Allocate(r6, r2, r7, r8, &allocate, SIZE_IN_WORDS);
__ bind(&done_allocate);
// Initialize the JSObject fields.
__ StoreP(r4, MemOperand(r2, JSObject::kMapOffset));
__ LoadRoot(r5, Heap::kEmptyFixedArrayRootIndex);
__ StoreP(r5, MemOperand(r2, JSObject::kPropertiesOffset));
__ StoreP(r5, MemOperand(r2, JSObject::kElementsOffset));
STATIC_ASSERT(JSObject::kHeaderSize == 3 * kPointerSize);
__ AddP(r3, r2, Operand(JSObject::kHeaderSize));
// ----------- S t a t e -------------
// -- r2 : result (untagged)
// -- r3 : result fields (untagged)
// -- r7 : result end (untagged)
// -- r4 : initial map
// -- cp : context
// -- lr : return address
// -----------------------------------
// Perform in-object slack tracking if requested.
Label slack_tracking;
STATIC_ASSERT(Map::kNoSlackTracking == 0);
__ LoadRoot(r8, Heap::kUndefinedValueRootIndex);
__ LoadlW(r5, FieldMemOperand(r4, Map::kBitField3Offset));
__ DecodeField<Map::ConstructionCounter>(r9, r5);
__ LoadAndTestP(r9, r9);
__ bne(&slack_tracking);
{
// Initialize all in-object fields with undefined.
__ InitializeFieldsWithFiller(r3, r7, r8);
// Add the object tag to make the JSObject real.
__ AddP(r2, r2, Operand(kHeapObjectTag));
__ Ret();
}
__ bind(&slack_tracking);
{
// Decrease generous allocation count.
STATIC_ASSERT(Map::ConstructionCounter::kNext == 32);
__ Add32(r5, r5, Operand(-(1 << Map::ConstructionCounter::kShift)));
__ StoreW(r5, FieldMemOperand(r4, Map::kBitField3Offset));
// Initialize the in-object fields with undefined.
__ LoadlB(r6, FieldMemOperand(r4, Map::kUnusedPropertyFieldsOffset));
__ ShiftLeftP(r6, r6, Operand(kPointerSizeLog2));
__ SubP(r6, r7, r6);
__ InitializeFieldsWithFiller(r3, r6, r8);
// Initialize the remaining (reserved) fields with one pointer filler map.
__ LoadRoot(r8, Heap::kOnePointerFillerMapRootIndex);
__ InitializeFieldsWithFiller(r3, r7, r8);
// Add the object tag to make the JSObject real.
__ AddP(r2, r2, Operand(kHeapObjectTag));
// Check if we can finalize the instance size.
__ CmpP(r9, Operand(Map::kSlackTrackingCounterEnd));
__ Ret(ne);
// Finalize the instance size.
{
FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
__ Push(r2, r4);
__ CallRuntime(Runtime::kFinalizeInstanceSize);
__ Pop(r2);
}
__ Ret();
}
// Fall back to %AllocateInNewSpace.
__ bind(&allocate);
{
FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
STATIC_ASSERT(kSmiTag == 0);
__ ShiftLeftP(r6, r6,
Operand(kPointerSizeLog2 + kSmiTagSize + kSmiShiftSize));
__ Push(r4, r6);
__ CallRuntime(Runtime::kAllocateInNewSpace);
__ Pop(r4);
}
__ SubP(r2, r2, Operand(kHeapObjectTag));
__ LoadlB(r7, FieldMemOperand(r4, Map::kInstanceSizeOffset));
__ ShiftLeftP(r7, r7, Operand(kPointerSizeLog2));
__ AddP(r7, r2, r7);
__ b(&done_allocate);
// Fall back to %NewObject.
__ bind(&new_object);
__ Push(r3, r5);
__ TailCallRuntime(Runtime::kNewObject);
}
void FastNewRestParameterStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r3 : function
// -- cp : context
// -- fp : frame pointer
// -- lr : return address
// -----------------------------------
__ AssertFunction(r3);
// For Ignition we need to skip all possible handler/stub frames until
// we reach the JavaScript frame for the function (similar to what the
// runtime fallback implementation does). So make r4 point to that
// JavaScript frame.
{
Label loop, loop_entry;
__ LoadRR(r4, fp);
__ b(&loop_entry);
__ bind(&loop);
__ LoadP(r4, MemOperand(r4, StandardFrameConstants::kCallerFPOffset));
__ bind(&loop_entry);
__ LoadP(ip, MemOperand(r4, StandardFrameConstants::kFunctionOffset));
__ CmpP(ip, r3);
__ bne(&loop);
}
// Check if we have rest parameters (only possible if we have an
// arguments adaptor frame below the function frame).
Label no_rest_parameters;
__ LoadP(r4, MemOperand(r4, StandardFrameConstants::kCallerFPOffset));
__ LoadP(ip, MemOperand(r4, CommonFrameConstants::kContextOrFrameTypeOffset));
__ CmpSmiLiteral(ip, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR), r0);
__ bne(&no_rest_parameters);
// Check if the arguments adaptor frame contains more arguments than
// specified by the function's internal formal parameter count.
Label rest_parameters;
__ LoadP(r2, MemOperand(r4, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ LoadP(r3, FieldMemOperand(r3, JSFunction::kSharedFunctionInfoOffset));
__ LoadW(
r3, FieldMemOperand(r3, SharedFunctionInfo::kFormalParameterCountOffset));
#if V8_TARGET_ARCH_S390X
__ SmiTag(r3);
#endif
__ SubP(r2, r2, r3);
__ bgt(&rest_parameters);
// Return an empty rest parameter array.
__ bind(&no_rest_parameters);
{
// ----------- S t a t e -------------
// -- cp : context
// -- lr : return address
// -----------------------------------
// Allocate an empty rest parameter array.
Label allocate, done_allocate;
__ Allocate(JSArray::kSize, r2, r3, r4, &allocate, TAG_OBJECT);
__ bind(&done_allocate);
// Setup the rest parameter array in r0.
__ LoadNativeContextSlot(Context::JS_ARRAY_FAST_ELEMENTS_MAP_INDEX, r3);
__ StoreP(r3, FieldMemOperand(r2, JSArray::kMapOffset), r0);
__ LoadRoot(r3, Heap::kEmptyFixedArrayRootIndex);
__ StoreP(r3, FieldMemOperand(r2, JSArray::kPropertiesOffset), r0);
__ StoreP(r3, FieldMemOperand(r2, JSArray::kElementsOffset), r0);
__ LoadImmP(r3, Operand::Zero());
__ StoreP(r3, FieldMemOperand(r2, JSArray::kLengthOffset), r0);
STATIC_ASSERT(JSArray::kSize == 4 * kPointerSize);
__ Ret();
// Fall back to %AllocateInNewSpace.
__ bind(&allocate);
{
FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
__ Push(Smi::FromInt(JSArray::kSize));
__ CallRuntime(Runtime::kAllocateInNewSpace);
}
__ b(&done_allocate);
}
__ bind(&rest_parameters);
{
// Compute the pointer to the first rest parameter (skippping the receiver).
__ SmiToPtrArrayOffset(r8, r2);
__ AddP(r4, r4, r8);
__ AddP(r4, r4, Operand(StandardFrameConstants::kCallerSPOffset));
// ----------- S t a t e -------------
// -- cp : context
// -- r2 : number of rest parameters (tagged)
// -- r4 : pointer just past first rest parameters
// -- r8 : size of rest parameters
// -- lr : return address
// -----------------------------------
// Allocate space for the rest parameter array plus the backing store.
Label allocate, done_allocate;
__ mov(r3, Operand(JSArray::kSize + FixedArray::kHeaderSize));
__ AddP(r3, r3, r8);
__ Allocate(r3, r5, r6, r7, &allocate, TAG_OBJECT);
__ bind(&done_allocate);
// Setup the elements array in r5.
__ LoadRoot(r3, Heap::kFixedArrayMapRootIndex);
__ StoreP(r3, FieldMemOperand(r5, FixedArray::kMapOffset), r0);
__ StoreP(r2, FieldMemOperand(r5, FixedArray::kLengthOffset), r0);
__ AddP(r6, r5,
Operand(FixedArray::kHeaderSize - kHeapObjectTag - kPointerSize));
{
Label loop;
__ SmiUntag(r1, r2);
// __ mtctr(r0);
__ bind(&loop);
__ lay(r4, MemOperand(r4, -kPointerSize));
__ LoadP(ip, MemOperand(r4));
__ la(r6, MemOperand(r6, kPointerSize));
__ StoreP(ip, MemOperand(r6));
// __ bdnz(&loop);
__ BranchOnCount(r1, &loop);
__ AddP(r6, r6, Operand(kPointerSize));
}
// Setup the rest parameter array in r6.
__ LoadNativeContextSlot(Context::JS_ARRAY_FAST_ELEMENTS_MAP_INDEX, r3);
__ StoreP(r3, MemOperand(r6, JSArray::kMapOffset));
__ LoadRoot(r3, Heap::kEmptyFixedArrayRootIndex);
__ StoreP(r3, MemOperand(r6, JSArray::kPropertiesOffset));
__ StoreP(r5, MemOperand(r6, JSArray::kElementsOffset));
__ StoreP(r2, MemOperand(r6, JSArray::kLengthOffset));
STATIC_ASSERT(JSArray::kSize == 4 * kPointerSize);
__ AddP(r2, r6, Operand(kHeapObjectTag));
__ Ret();
// Fall back to %AllocateInNewSpace.
__ bind(&allocate);
{
FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
__ SmiTag(r3);
__ Push(r2, r4, r3);
__ CallRuntime(Runtime::kAllocateInNewSpace);
__ LoadRR(r5, r2);
__ Pop(r2, r4);
}
__ b(&done_allocate);
}
}
void FastNewSloppyArgumentsStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r3 : function
// -- cp : context
// -- fp : frame pointer
// -- lr : return address
// -----------------------------------
__ AssertFunction(r3);
// TODO(bmeurer): Cleanup to match the FastNewStrictArgumentsStub.
__ LoadP(r4, FieldMemOperand(r3, JSFunction::kSharedFunctionInfoOffset));
__ LoadW(
r4, FieldMemOperand(r4, SharedFunctionInfo::kFormalParameterCountOffset));
#if V8_TARGET_ARCH_S390X
__ SmiTag(r4);
#endif
__ SmiToPtrArrayOffset(r5, r4);
__ AddP(r5, fp, r5);
__ AddP(r5, r5, Operand(StandardFrameConstants::kCallerSPOffset));
// r3 : function
// r4 : number of parameters (tagged)
// r5 : parameters pointer
// Registers used over whole function:
// r7 : arguments count (tagged)
// r8 : mapped parameter count (tagged)
// Check if the calling frame is an arguments adaptor frame.
Label adaptor_frame, try_allocate, runtime;
__ LoadP(r6, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
__ LoadP(r2, MemOperand(r6, CommonFrameConstants::kContextOrFrameTypeOffset));
__ CmpSmiLiteral(r2, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR), r0);
__ beq(&adaptor_frame);
// No adaptor, parameter count = argument count.
__ LoadRR(r7, r4);
__ LoadRR(r8, r4);
__ b(&try_allocate);
// We have an adaptor frame. Patch the parameters pointer.
__ bind(&adaptor_frame);
__ LoadP(r7, MemOperand(r6, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ SmiToPtrArrayOffset(r5, r7);
__ AddP(r5, r5, r6);
__ AddP(r5, r5, Operand(StandardFrameConstants::kCallerSPOffset));
// r7 = argument count (tagged)
// r8 = parameter count (tagged)
// Compute the mapped parameter count = min(r4, r7) in r8.
__ CmpP(r4, r7);
Label skip;
__ LoadRR(r8, r4);
__ blt(&skip);
__ LoadRR(r8, r7);
__ bind(&skip);
__ bind(&try_allocate);
// Compute the sizes of backing store, parameter map, and arguments object.
// 1. Parameter map, has 2 extra words containing context and backing store.
const int kParameterMapHeaderSize =
FixedArray::kHeaderSize + 2 * kPointerSize;
// If there are no mapped parameters, we do not need the parameter_map.
__ CmpSmiLiteral(r8, Smi::FromInt(0), r0);
Label skip2, skip3;
__ bne(&skip2);
__ LoadImmP(r1, Operand::Zero());
__ b(&skip3);
__ bind(&skip2);
__ SmiToPtrArrayOffset(r1, r8);
__ AddP(r1, r1, Operand(kParameterMapHeaderSize));
__ bind(&skip3);
// 2. Backing store.
__ SmiToPtrArrayOffset(r6, r7);
__ AddP(r1, r1, r6);
__ AddP(r1, r1, Operand(FixedArray::kHeaderSize));
// 3. Arguments object.
__ AddP(r1, r1, Operand(JSSloppyArgumentsObject::kSize));
// Do the allocation of all three objects in one go.
__ Allocate(r1, r2, r1, r6, &runtime, TAG_OBJECT);
// r2 = address of new object(s) (tagged)
// r4 = argument count (smi-tagged)
// Get the arguments boilerplate from the current native context into r3.
const int kNormalOffset =
Context::SlotOffset(Context::SLOPPY_ARGUMENTS_MAP_INDEX);
const int kAliasedOffset =
Context::SlotOffset(Context::FAST_ALIASED_ARGUMENTS_MAP_INDEX);
__ LoadP(r6, NativeContextMemOperand());
__ CmpP(r8, Operand::Zero());
Label skip4, skip5;
__ bne(&skip4);
__ LoadP(r6, MemOperand(r6, kNormalOffset));
__ b(&skip5);
__ bind(&skip4);
__ LoadP(r6, MemOperand(r6, kAliasedOffset));
__ bind(&skip5);
// r2 = address of new object (tagged)
// r4 = argument count (smi-tagged)
// r6 = address of arguments map (tagged)
// r8 = mapped parameter count (tagged)
__ StoreP(r6, FieldMemOperand(r2, JSObject::kMapOffset), r0);
__ LoadRoot(r1, Heap::kEmptyFixedArrayRootIndex);
__ StoreP(r1, FieldMemOperand(r2, JSObject::kPropertiesOffset), r0);
__ StoreP(r1, FieldMemOperand(r2, JSObject::kElementsOffset), r0);
// Set up the callee in-object property.
__ AssertNotSmi(r3);
__ StoreP(r3, FieldMemOperand(r2, JSSloppyArgumentsObject::kCalleeOffset),
r0);
// Use the length (smi tagged) and set that as an in-object property too.
__ AssertSmi(r7);
__ StoreP(r7, FieldMemOperand(r2, JSSloppyArgumentsObject::kLengthOffset),
r0);
// Set up the elements pointer in the allocated arguments object.
// If we allocated a parameter map, r6 will point there, otherwise
// it will point to the backing store.
__ AddP(r6, r2, Operand(JSSloppyArgumentsObject::kSize));
__ StoreP(r6, FieldMemOperand(r2, JSObject::kElementsOffset), r0);
// r2 = address of new object (tagged)
// r4 = argument count (tagged)
// r6 = address of parameter map or backing store (tagged)
// r8 = mapped parameter count (tagged)
// Initialize parameter map. If there are no mapped arguments, we're done.
Label skip_parameter_map;
__ CmpSmiLiteral(r8, Smi::FromInt(0), r0);
Label skip6;
__ bne(&skip6);
// Move backing store address to r3, because it is
// expected there when filling in the unmapped arguments.
__ LoadRR(r3, r6);
__ b(&skip_parameter_map);
__ bind(&skip6);
__ LoadRoot(r7, Heap::kSloppyArgumentsElementsMapRootIndex);
__ StoreP(r7, FieldMemOperand(r6, FixedArray::kMapOffset), r0);
__ AddSmiLiteral(r7, r8, Smi::FromInt(2), r0);
__ StoreP(r7, FieldMemOperand(r6, FixedArray::kLengthOffset), r0);
__ StoreP(cp, FieldMemOperand(r6, FixedArray::kHeaderSize + 0 * kPointerSize),
r0);
__ SmiToPtrArrayOffset(r7, r8);
__ AddP(r7, r7, r6);
__ AddP(r7, r7, Operand(kParameterMapHeaderSize));
__ StoreP(r7, FieldMemOperand(r6, FixedArray::kHeaderSize + 1 * kPointerSize),
r0);
// Copy the parameter slots and the holes in the arguments.
// We need to fill in mapped_parameter_count slots. They index the context,
// where parameters are stored in reverse order, at
// MIN_CONTEXT_SLOTS .. MIN_CONTEXT_SLOTS+parameter_count-1
// The mapped parameter thus need to get indices
// MIN_CONTEXT_SLOTS+parameter_count-1 ..
// MIN_CONTEXT_SLOTS+parameter_count-mapped_parameter_count
// We loop from right to left.
Label parameters_loop;
__ LoadRR(r7, r8);
__ AddSmiLiteral(r1, r4, Smi::FromInt(Context::MIN_CONTEXT_SLOTS), r0);
__ SubP(r1, r1, r8);
__ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
__ SmiToPtrArrayOffset(r3, r7);
__ AddP(r3, r3, r6);
__ AddP(r3, r3, Operand(kParameterMapHeaderSize));
// r3 = address of backing store (tagged)
// r6 = address of parameter map (tagged)
// r7 = temporary scratch (a.o., for address calculation)
// r9 = temporary scratch (a.o., for address calculation)
// ip = the hole value
__ SmiUntag(r7);
__ push(r4);
__ LoadRR(r4, r7);
__ ShiftLeftP(r7, r7, Operand(kPointerSizeLog2));
__ AddP(r9, r3, r7);
__ AddP(r7, r6, r7);
__ AddP(r9, r9, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
__ AddP(r7, r7, Operand(kParameterMapHeaderSize - kHeapObjectTag));
__ bind(¶meters_loop);
__ StoreP(r1, MemOperand(r7, -kPointerSize));
__ lay(r7, MemOperand(r7, -kPointerSize));
__ StoreP(ip, MemOperand(r9, -kPointerSize));
__ lay(r9, MemOperand(r9, -kPointerSize));
__ AddSmiLiteral(r1, r1, Smi::FromInt(1), r0);
__ BranchOnCount(r4, ¶meters_loop);
__ pop(r4);
// Restore r7 = argument count (tagged).
__ LoadP(r7, FieldMemOperand(r2, JSSloppyArgumentsObject::kLengthOffset));
__ bind(&skip_parameter_map);
// r2 = address of new object (tagged)
// r3 = address of backing store (tagged)
// r7 = argument count (tagged)
// r8 = mapped parameter count (tagged)
// r1 = scratch
// Copy arguments header and remaining slots (if there are any).
__ LoadRoot(r1, Heap::kFixedArrayMapRootIndex);
__ StoreP(r1, FieldMemOperand(r3, FixedArray::kMapOffset), r0);
__ StoreP(r7, FieldMemOperand(r3, FixedArray::kLengthOffset), r0);
__ SubP(r1, r7, r8);
__ Ret(eq);
Label arguments_loop;
__ SmiUntag(r1);
__ LoadRR(r4, r1);
__ SmiToPtrArrayOffset(r0, r8);
__ SubP(r5, r5, r0);
__ AddP(r1, r3, r0);
__ AddP(r1, r1,
Operand(FixedArray::kHeaderSize - kHeapObjectTag - kPointerSize));
__ bind(&arguments_loop);
__ LoadP(r6, MemOperand(r5, -kPointerSize));
__ lay(r5, MemOperand(r5, -kPointerSize));
__ StoreP(r6, MemOperand(r1, kPointerSize));
__ la(r1, MemOperand(r1, kPointerSize));
__ BranchOnCount(r4, &arguments_loop);
// Return.
__ Ret();
// Do the runtime call to allocate the arguments object.
// r7 = argument count (tagged)
__ bind(&runtime);
__ Push(r3, r5, r7);
__ TailCallRuntime(Runtime::kNewSloppyArguments);
}
void FastNewStrictArgumentsStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r3 : function
// -- cp : context
// -- fp : frame pointer
// -- lr : return address
// -----------------------------------
__ AssertFunction(r3);
// For Ignition we need to skip all possible handler/stub frames until
// we reach the JavaScript frame for the function (similar to what the
// runtime fallback implementation does). So make r4 point to that
// JavaScript frame.
{
Label loop, loop_entry;
__ LoadRR(r4, fp);
__ b(&loop_entry);
__ bind(&loop);
__ LoadP(r4, MemOperand(r4, StandardFrameConstants::kCallerFPOffset));
__ bind(&loop_entry);
__ LoadP(ip, MemOperand(r4, StandardFrameConstants::kFunctionOffset));
__ CmpP(ip, r3);
__ bne(&loop);
}
// Check if we have an arguments adaptor frame below the function frame.
Label arguments_adaptor, arguments_done;
__ LoadP(r5, MemOperand(r4, StandardFrameConstants::kCallerFPOffset));
__ LoadP(ip, MemOperand(r5, CommonFrameConstants::kContextOrFrameTypeOffset));
__ CmpSmiLiteral(ip, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR), r0);
__ beq(&arguments_adaptor);
{
__ LoadP(r3, FieldMemOperand(r3, JSFunction::kSharedFunctionInfoOffset));
__ LoadW(r2, FieldMemOperand(
r3, SharedFunctionInfo::kFormalParameterCountOffset));
#if V8_TARGET_ARCH_S390X
__ SmiTag(r2);
#endif
__ SmiToPtrArrayOffset(r8, r2);
__ AddP(r4, r4, r8);
}
__ b(&arguments_done);
__ bind(&arguments_adaptor);
{
__ LoadP(r2, MemOperand(r5, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ SmiToPtrArrayOffset(r8, r2);
__ AddP(r4, r5, r8);
}
__ bind(&arguments_done);
__ AddP(r4, r4, Operand(StandardFrameConstants::kCallerSPOffset));
// ----------- S t a t e -------------
// -- cp : context
// -- r2 : number of rest parameters (tagged)
// -- r4 : pointer just past first rest parameters
// -- r8 : size of rest parameters
// -- lr : return address
// -----------------------------------
// Allocate space for the strict arguments object plus the backing store.
Label allocate, done_allocate;
__ mov(r3, Operand(JSStrictArgumentsObject::kSize + FixedArray::kHeaderSize));
__ AddP(r3, r3, r8);
__ Allocate(r3, r5, r6, r7, &allocate, TAG_OBJECT);
__ bind(&done_allocate);
// Setup the elements array in r5.
__ LoadRoot(r3, Heap::kFixedArrayMapRootIndex);
__ StoreP(r3, FieldMemOperand(r5, FixedArray::kMapOffset), r0);
__ StoreP(r2, FieldMemOperand(r5, FixedArray::kLengthOffset), r0);
__ AddP(r6, r5,
Operand(FixedArray::kHeaderSize - kHeapObjectTag - kPointerSize));
{
Label loop, done_loop;
__ SmiUntag(r1, r2);
__ LoadAndTestP(r1, r1);
__ beq(&done_loop);
__ bind(&loop);
__ lay(r4, MemOperand(r4, -kPointerSize));
__ LoadP(ip, MemOperand(r4));
__ la(r6, MemOperand(r6, kPointerSize));
__ StoreP(ip, MemOperand(r6));
__ BranchOnCount(r1, &loop);
__ bind(&done_loop);
__ AddP(r6, r6, Operand(kPointerSize));
}
// Setup the rest parameter array in r6.
__ LoadNativeContextSlot(Context::STRICT_ARGUMENTS_MAP_INDEX, r3);
__ StoreP(r3, MemOperand(r6, JSStrictArgumentsObject::kMapOffset));
__ LoadRoot(r3, Heap::kEmptyFixedArrayRootIndex);
__ StoreP(r3, MemOperand(r6, JSStrictArgumentsObject::kPropertiesOffset));
__ StoreP(r5, MemOperand(r6, JSStrictArgumentsObject::kElementsOffset));
__ StoreP(r2, MemOperand(r6, JSStrictArgumentsObject::kLengthOffset));
STATIC_ASSERT(JSStrictArgumentsObject::kSize == 4 * kPointerSize);
__ AddP(r2, r6, Operand(kHeapObjectTag));
__ Ret();
// Fall back to %AllocateInNewSpace.
__ bind(&allocate);
{
FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
__ SmiTag(r3);
__ Push(r2, r4, r3);
__ CallRuntime(Runtime::kAllocateInNewSpace);
__ LoadRR(r5, r2);
__ Pop(r2, r4);
}
__ b(&done_allocate);
}
void LoadGlobalViaContextStub::Generate(MacroAssembler* masm) {
Register context = cp;
Register result = r2;
Register slot = r4;
// Go up the context chain to the script context.
for (int i = 0; i < depth(); ++i) {
__ LoadP(result, ContextMemOperand(context, Context::PREVIOUS_INDEX));
context = result;
}
// Load the PropertyCell value at the specified slot.
__ ShiftLeftP(r0, slot, Operand(kPointerSizeLog2));
__ AddP(result, context, r0);
__ LoadP(result, ContextMemOperand(result));
__ LoadP(result, FieldMemOperand(result, PropertyCell::kValueOffset));
// If the result is not the_hole, return. Otherwise, handle in the runtime.
__ CompareRoot(result, Heap::kTheHoleValueRootIndex);
Label runtime;
__ beq(&runtime);
__ Ret();
__ bind(&runtime);
// Fallback to runtime.
__ SmiTag(slot);
__ Push(slot);
__ TailCallRuntime(Runtime::kLoadGlobalViaContext);
}
void StoreGlobalViaContextStub::Generate(MacroAssembler* masm) {
Register value = r2;
Register slot = r4;
Register cell = r3;
Register cell_details = r5;
Register cell_value = r6;
Register cell_value_map = r7;
Register scratch = r8;
Register context = cp;
Register context_temp = cell;
Label fast_heapobject_case, fast_smi_case, slow_case;
if (FLAG_debug_code) {
__ CompareRoot(value, Heap::kTheHoleValueRootIndex);
__ Check(ne, kUnexpectedValue);
}
// Go up the context chain to the script context.
for (int i = 0; i < depth(); i++) {
__ LoadP(context_temp, ContextMemOperand(context, Context::PREVIOUS_INDEX));
context = context_temp;
}
// Load the PropertyCell at the specified slot.
__ ShiftLeftP(r0, slot, Operand(kPointerSizeLog2));
__ AddP(cell, context, r0);
__ LoadP(cell, ContextMemOperand(cell));
// Load PropertyDetails for the cell (actually only the cell_type and kind).
__ LoadP(cell_details, FieldMemOperand(cell, PropertyCell::kDetailsOffset));
__ SmiUntag(cell_details);
__ AndP(cell_details, cell_details,
Operand(PropertyDetails::PropertyCellTypeField::kMask |
PropertyDetails::KindField::kMask |
PropertyDetails::kAttributesReadOnlyMask));
// Check if PropertyCell holds mutable data.
Label not_mutable_data;
__ CmpP(cell_details, Operand(PropertyDetails::PropertyCellTypeField::encode(
PropertyCellType::kMutable) |
PropertyDetails::KindField::encode(kData)));
__ bne(¬_mutable_data);
__ JumpIfSmi(value, &fast_smi_case);
__ bind(&fast_heapobject_case);
__ StoreP(value, FieldMemOperand(cell, PropertyCell::kValueOffset), r0);
// RecordWriteField clobbers the value register, so we copy it before the
// call.
__ LoadRR(r5, value);
__ RecordWriteField(cell, PropertyCell::kValueOffset, r5, scratch,
kLRHasNotBeenSaved, kDontSaveFPRegs, EMIT_REMEMBERED_SET,
OMIT_SMI_CHECK);
__ Ret();
__ bind(¬_mutable_data);
// Check if PropertyCell value matches the new value (relevant for Constant,
// ConstantType and Undefined cells).
Label not_same_value;
__ LoadP(cell_value, FieldMemOperand(cell, PropertyCell::kValueOffset));
__ CmpP(cell_value, value);
__ bne(¬_same_value);
// Make sure the PropertyCell is not marked READ_ONLY.
__ AndP(r0, cell_details, Operand(PropertyDetails::kAttributesReadOnlyMask));
__ bne(&slow_case);
if (FLAG_debug_code) {
Label done;
// This can only be true for Constant, ConstantType and Undefined cells,
// because we never store the_hole via this stub.
__ CmpP(cell_details,
Operand(PropertyDetails::PropertyCellTypeField::encode(
PropertyCellType::kConstant) |
PropertyDetails::KindField::encode(kData)));
__ beq(&done);
__ CmpP(cell_details,
Operand(PropertyDetails::PropertyCellTypeField::encode(
PropertyCellType::kConstantType) |
PropertyDetails::KindField::encode(kData)));
__ beq(&done);
__ CmpP(cell_details,
Operand(PropertyDetails::PropertyCellTypeField::encode(
PropertyCellType::kUndefined) |
PropertyDetails::KindField::encode(kData)));
__ Check(eq, kUnexpectedValue);
__ bind(&done);
}
__ Ret();
__ bind(¬_same_value);
// Check if PropertyCell contains data with constant type (and is not
// READ_ONLY).
__ CmpP(cell_details, Operand(PropertyDetails::PropertyCellTypeField::encode(
PropertyCellType::kConstantType) |
PropertyDetails::KindField::encode(kData)));
__ bne(&slow_case);
// Now either both old and new values must be smis or both must be heap
// objects with same map.
Label value_is_heap_object;
__ JumpIfNotSmi(value, &value_is_heap_object);
__ JumpIfNotSmi(cell_value, &slow_case);
// Old and new values are smis, no need for a write barrier here.
__ bind(&fast_smi_case);
__ StoreP(value, FieldMemOperand(cell, PropertyCell::kValueOffset), r0);
__ Ret();
__ bind(&value_is_heap_object);
__ JumpIfSmi(cell_value, &slow_case);
__ LoadP(cell_value_map, FieldMemOperand(cell_value, HeapObject::kMapOffset));
__ LoadP(scratch, FieldMemOperand(value, HeapObject::kMapOffset));
__ CmpP(cell_value_map, scratch);
__ beq(&fast_heapobject_case);
// Fallback to runtime.
__ bind(&slow_case);
__ SmiTag(slot);
__ Push(slot, value);
__ TailCallRuntime(is_strict(language_mode())
? Runtime::kStoreGlobalViaContext_Strict
: Runtime::kStoreGlobalViaContext_Sloppy);
}
static int AddressOffset(ExternalReference ref0, ExternalReference ref1) {
return ref0.address() - ref1.address();
}
// Calls an API function. Allocates HandleScope, extracts returned value
// from handle and propagates exceptions. Restores context. stack_space
// - space to be unwound on exit (includes the call JS arguments space and
// the additional space allocated for the fast call).
static void CallApiFunctionAndReturn(MacroAssembler* masm,
Register function_address,
ExternalReference thunk_ref,
int stack_space,
MemOperand* stack_space_operand,
MemOperand return_value_operand,
MemOperand* context_restore_operand) {
Isolate* isolate = masm->isolate();
ExternalReference next_address =
ExternalReference::handle_scope_next_address(isolate);
const int kNextOffset = 0;
const int kLimitOffset = AddressOffset(
ExternalReference::handle_scope_limit_address(isolate), next_address);
const int kLevelOffset = AddressOffset(
ExternalReference::handle_scope_level_address(isolate), next_address);
// Additional parameter is the address of the actual callback.
DCHECK(function_address.is(r3) || function_address.is(r4));
Register scratch = r5;
__ mov(scratch, Operand(ExternalReference::is_profiling_address(isolate)));
__ LoadlB(scratch, MemOperand(scratch, 0));
__ CmpP(scratch, Operand::Zero());
Label profiler_disabled;
Label end_profiler_check;
__ beq(&profiler_disabled, Label::kNear);
__ mov(scratch, Operand(thunk_ref));
__ b(&end_profiler_check, Label::kNear);
__ bind(&profiler_disabled);
__ LoadRR(scratch, function_address);
__ bind(&end_profiler_check);
// Allocate HandleScope in callee-save registers.
// r9 - next_address
// r6 - next_address->kNextOffset
// r7 - next_address->kLimitOffset
// r8 - next_address->kLevelOffset
__ mov(r9, Operand(next_address));
__ LoadP(r6, MemOperand(r9, kNextOffset));
__ LoadP(r7, MemOperand(r9, kLimitOffset));
__ LoadlW(r8, MemOperand(r9, kLevelOffset));
__ AddP(r8, Operand(1));
__ StoreW(r8, MemOperand(r9, kLevelOffset));
if (FLAG_log_timer_events) {
FrameScope frame(masm, StackFrame::MANUAL);
__ PushSafepointRegisters();
__ PrepareCallCFunction(1, r2);
__ mov(r2, Operand(ExternalReference::isolate_address(isolate)));
__ CallCFunction(ExternalReference::log_enter_external_function(isolate),
1);
__ PopSafepointRegisters();
}
// Native call returns to the DirectCEntry stub which redirects to the
// return address pushed on stack (could have moved after GC).
// DirectCEntry stub itself is generated early and never moves.
DirectCEntryStub stub(isolate);
stub.GenerateCall(masm, scratch);
if (FLAG_log_timer_events) {
FrameScope frame(masm, StackFrame::MANUAL);
__ PushSafepointRegisters();
__ PrepareCallCFunction(1, r2);
__ mov(r2, Operand(ExternalReference::isolate_address(isolate)));
__ CallCFunction(ExternalReference::log_leave_external_function(isolate),
1);
__ PopSafepointRegisters();
}
Label promote_scheduled_exception;
Label delete_allocated_handles;
Label leave_exit_frame;
Label return_value_loaded;
// load value from ReturnValue
__ LoadP(r2, return_value_operand);
__ bind(&return_value_loaded);
// No more valid handles (the result handle was the last one). Restore
// previous handle scope.
__ StoreP(r6, MemOperand(r9, kNextOffset));
if (__ emit_debug_code()) {
__ LoadlW(r3, MemOperand(r9, kLevelOffset));
__ CmpP(r3, r8);
__ Check(eq, kUnexpectedLevelAfterReturnFromApiCall);
}
__ SubP(r8, Operand(1));
__ StoreW(r8, MemOperand(r9, kLevelOffset));
__ CmpP(r7, MemOperand(r9, kLimitOffset));
__ bne(&delete_allocated_handles, Label::kNear);
// Leave the API exit frame.
__ bind(&leave_exit_frame);
bool restore_context = context_restore_operand != NULL;
if (restore_context) {
__ LoadP(cp, *context_restore_operand);
}
// LeaveExitFrame expects unwind space to be in a register.
if (stack_space_operand != NULL) {
__ l(r6, *stack_space_operand);
} else {
__ mov(r6, Operand(stack_space));
}
__ LeaveExitFrame(false, r6, !restore_context, stack_space_operand != NULL);
// Check if the function scheduled an exception.
__ mov(r7, Operand(ExternalReference::scheduled_exception_address(isolate)));
__ LoadP(r7, MemOperand(r7));
__ CompareRoot(r7, Heap::kTheHoleValueRootIndex);
__ bne(&promote_scheduled_exception, Label::kNear);
__ b(r14);
// Re-throw by promoting a scheduled exception.
__ bind(&promote_scheduled_exception);
__ TailCallRuntime(Runtime::kPromoteScheduledException);
// HandleScope limit has changed. Delete allocated extensions.
__ bind(&delete_allocated_handles);
__ StoreP(r7, MemOperand(r9, kLimitOffset));
__ LoadRR(r6, r2);
__ PrepareCallCFunction(1, r7);
__ mov(r2, Operand(ExternalReference::isolate_address(isolate)));
__ CallCFunction(ExternalReference::delete_handle_scope_extensions(isolate),
1);
__ LoadRR(r2, r6);
__ b(&leave_exit_frame, Label::kNear);
}
void CallApiCallbackStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r2 : callee
// -- r6 : call_data
// -- r4 : holder
// -- r3 : api_function_address
// -- cp : context
// --
// -- sp[0] : last argument
// -- ...
// -- sp[(argc - 1)* 4] : first argument
// -- sp[argc * 4] : receiver
// -----------------------------------
Register callee = r2;
Register call_data = r6;
Register holder = r4;
Register api_function_address = r3;
Register context = cp;
typedef FunctionCallbackArguments FCA;
STATIC_ASSERT(FCA::kContextSaveIndex == 6);
STATIC_ASSERT(FCA::kCalleeIndex == 5);
STATIC_ASSERT(FCA::kDataIndex == 4);
STATIC_ASSERT(FCA::kReturnValueOffset == 3);
STATIC_ASSERT(FCA::kReturnValueDefaultValueIndex == 2);
STATIC_ASSERT(FCA::kIsolateIndex == 1);
STATIC_ASSERT(FCA::kHolderIndex == 0);
STATIC_ASSERT(FCA::kArgsLength == 7);
// context save
__ push(context);
if (!is_lazy()) {
// load context from callee
__ LoadP(context, FieldMemOperand(callee, JSFunction::kContextOffset));
}
// callee
__ push(callee);
// call data
__ push(call_data);
Register scratch = call_data;
if (!call_data_undefined()) {
__ LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
}
// return value
__ push(scratch);
// return value default
__ push(scratch);
// isolate
__ mov(scratch, Operand(ExternalReference::isolate_address(masm->isolate())));
__ push(scratch);
// holder
__ push(holder);
// Prepare arguments.
__ LoadRR(scratch, sp);
// Allocate the v8::Arguments structure in the arguments' space since
// it's not controlled by GC.
// S390 LINUX ABI:
//
// Create 5 extra slots on stack:
// [0] space for DirectCEntryStub's LR save
// [1-4] FunctionCallbackInfo
const int kApiStackSpace = 5;
const int kFunctionCallbackInfoOffset =
(kStackFrameExtraParamSlot + 1) * kPointerSize;
FrameScope frame_scope(masm, StackFrame::MANUAL);
__ EnterExitFrame(false, kApiStackSpace);
DCHECK(!api_function_address.is(r2) && !scratch.is(r2));
// r2 = FunctionCallbackInfo&
// Arguments is after the return address.
__ AddP(r2, sp, Operand(kFunctionCallbackInfoOffset));
// FunctionCallbackInfo::implicit_args_
__ StoreP(scratch, MemOperand(r2, 0 * kPointerSize));
// FunctionCallbackInfo::values_
__ AddP(ip, scratch, Operand((FCA::kArgsLength - 1 + argc()) * kPointerSize));
__ StoreP(ip, MemOperand(r2, 1 * kPointerSize));
// FunctionCallbackInfo::length_ = argc
__ LoadImmP(ip, Operand(argc()));
__ StoreW(ip, MemOperand(r2, 2 * kPointerSize));
// FunctionCallbackInfo::is_construct_call_ = 0
__ LoadImmP(ip, Operand::Zero());
__ StoreW(ip, MemOperand(r2, 2 * kPointerSize + kIntSize));
ExternalReference thunk_ref =
ExternalReference::invoke_function_callback(masm->isolate());
AllowExternalCallThatCantCauseGC scope(masm);
MemOperand context_restore_operand(
fp, (2 + FCA::kContextSaveIndex) * kPointerSize);
// Stores return the first js argument
int return_value_offset = 0;
if (is_store()) {
return_value_offset = 2 + FCA::kArgsLength;
} else {
return_value_offset = 2 + FCA::kReturnValueOffset;
}
MemOperand return_value_operand(fp, return_value_offset * kPointerSize);
int stack_space = 0;
MemOperand is_construct_call_operand =
MemOperand(sp, kFunctionCallbackInfoOffset + 2 * kPointerSize + kIntSize);
MemOperand* stack_space_operand = &is_construct_call_operand;
stack_space = argc() + FCA::kArgsLength + 1;
stack_space_operand = NULL;
CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, stack_space,
stack_space_operand, return_value_operand,
&context_restore_operand);
}
void CallApiGetterStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- sp[0] : name
// -- sp[4 .. (4 + kArgsLength*4)] : v8::PropertyCallbackInfo::args_
// -- ...
// -- r4 : api_function_address
// -----------------------------------
Register api_function_address = ApiGetterDescriptor::function_address();
int arg0Slot = 0;
int accessorInfoSlot = 0;
int apiStackSpace = 0;
DCHECK(api_function_address.is(r4));
// v8::PropertyCallbackInfo::args_ array and name handle.
const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1;
// Load address of v8::PropertyAccessorInfo::args_ array and name handle.
__ LoadRR(r2, sp); // r2 = Handle<Name>
__ AddP(r3, r2, Operand(1 * kPointerSize)); // r3 = v8::PCI::args_
// If ABI passes Handles (pointer-sized struct) in a register:
//
// Create 2 extra slots on stack:
// [0] space for DirectCEntryStub's LR save
// [1] AccessorInfo&
//
// Otherwise:
//
// Create 3 extra slots on stack:
// [0] space for DirectCEntryStub's LR save
// [1] copy of Handle (first arg)
// [2] AccessorInfo&
if (ABI_PASSES_HANDLES_IN_REGS) {
accessorInfoSlot = kStackFrameExtraParamSlot + 1;
apiStackSpace = 2;
} else {
arg0Slot = kStackFrameExtraParamSlot + 1;
accessorInfoSlot = arg0Slot + 1;
apiStackSpace = 3;
}
FrameScope frame_scope(masm, StackFrame::MANUAL);
__ EnterExitFrame(false, apiStackSpace);
if (!ABI_PASSES_HANDLES_IN_REGS) {
// pass 1st arg by reference
__ StoreP(r2, MemOperand(sp, arg0Slot * kPointerSize));
__ AddP(r2, sp, Operand(arg0Slot * kPointerSize));
}
// Create v8::PropertyCallbackInfo object on the stack and initialize
// it's args_ field.
__ StoreP(r3, MemOperand(sp, accessorInfoSlot * kPointerSize));
__ AddP(r3, sp, Operand(accessorInfoSlot * kPointerSize));
// r3 = v8::PropertyCallbackInfo&
ExternalReference thunk_ref =
ExternalReference::invoke_accessor_getter_callback(isolate());
// +3 is to skip prolog, return address and name handle.
MemOperand return_value_operand(
fp, (PropertyCallbackArguments::kReturnValueOffset + 3) * kPointerSize);
CallApiFunctionAndReturn(masm, api_function_address, thunk_ref,
kStackUnwindSpace, NULL, return_value_operand, NULL);
}
#undef __
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_S390
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b356ce5f3da2f0a159eb4604380693b44b1debf1 | 4ad2ec9e00f59c0e47d0de95110775a8a987cec2 | /_Codeforces/Intel Final Round/D/main.cpp | e0845649c759df8153c204562ee27d86728aae36 | [] | no_license | atatomir/work | 2f13cfd328e00275672e077bba1e84328fccf42f | e8444d2e48325476cfbf0d4cfe5a5aa1efbedce9 | refs/heads/master | 2021-01-23T10:03:44.821372 | 2021-01-17T18:07:15 | 2021-01-17T18:07:15 | 33,084,680 | 2 | 1 | null | 2015-08-02T20:16:02 | 2015-03-29T18:54:24 | C++ | UTF-8 | C++ | false | false | 1,474 | cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
#define mp make_pair
#define pb push_back
#define ll long long
#define maxN 100011
#define sigma 26
int n, m, i, step;
char s[maxN];
int cnt[sigma + 11];
vector<char> ans;
int sol;
bool fill_works(char chlim, int l, int r) {
int i, todo, last;
todo = l + m - 1;
last = 0;
for (i = l; i < r; i++) {
if (s[i] == chlim)
last = i;
if (i >= todo) {
if (last == 0) return false;
todo = last + m;
sol++;
last = 0;
}
}
if (todo < r) return false;
return true;
}
bool check(int limit) {
int i, j, l, r, last;
char chlim = 'a' + limit;
sol = 0;
for (i = 1; i <= n; i = r + 1) {
l = i;
for (r = i; s[r] >= chlim && r <= n; r++);
if (r - l < m) continue;
if (!fill_works(chlim, l, r))
return false;
}
return true;
}
int main()
{
//freopen("test.in","r",stdin);
scanf("%d\n%s", &m, s + 1);
n = strlen(s + 1);
for (i = 1; i <= n; i++) cnt[s[i] - 'a']++;
for (step = 0; step < sigma; step++) {
if (check(step)) {
for (i = 1; i <= sol; i++) ans.pb('a' + step);
break;
}
for (i = 1; i <= cnt[step]; i++) ans.pb('a' + step);
}
for (auto e : ans) printf("%c", e);
return 0;
}
| [
"atatomir5@gmail.com"
] | atatomir5@gmail.com |
102a6bd6f9fdb6462ef2f6b23d0c88f7b856f408 | 91e3d3494819be1f5f04239c8aaf93989e6b2f34 | /crypto/hmac_sha512.h | d0ee7d99fbffadf98dc98b6f2e57ac76a7b8c874 | [] | no_license | filecoinwallet/ebzz_public | 1c5e38d64b26da77cb4a50002c94ac65e63e5e4a | 708fbb8e498f58b03921517d0fa3489ff8b2d861 | refs/heads/main | 2023-06-21T22:18:04.861369 | 2021-07-22T20:08:19 | 2021-07-22T20:08:19 | 385,140,291 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | // Copyright (c) 2014 The _ebzz_ebzz developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef _ebzz_ebzz_CRYPTO_HMAC_SHA512_H
#define _ebzz_ebzz_CRYPTO_HMAC_SHA512_H
#include "crypto/sha512.h"
#include <stdint.h>
#include <stdlib.h>
/** A hasher class for HMAC-SHA-512. */
class CHMAC_SHA512
{
private:
CSHA512 outer;
CSHA512 inner;
public:
static const size_t OUTPUT_SIZE = 64;
CHMAC_SHA512(const unsigned char* key, size_t keylen);
CHMAC_SHA512& Write(const unsigned char* data, size_t len)
{
inner.Write(data, len);
return *this;
}
void Finalize(unsigned char hash[OUTPUT_SIZE]);
};
#endif // _ebzz_ebzz_CRYPTO_HMAC_SHA512_H
| [
"86972302+bzzio@users.noreply.github.com"
] | 86972302+bzzio@users.noreply.github.com |
fb46d6d423bb2335d2680434e3dd144db0d9293f | 7fb149b31b9321fc14396dad040fabf7e6e6eb52 | /build/tmp/expandedArchives/wpilibc-cpp-2019.2.1-sources.zip_d2c10ca9fef4a09e287ef5192d19cdb5/AnalogTrigger.cpp | aeb58dfbee2832de8b6f1cf296730e6e881b5fb2 | [
"BSD-3-Clause"
] | permissive | FRCTeam5458DigitalMinds/Axon | 4feb4e7cc1a50d93d77c204dbf6cca863850ba3f | af571142de3f9d6589252c89537210015a1a26a0 | refs/heads/master | 2020-04-18T20:14:50.004225 | 2019-10-30T03:05:29 | 2019-10-30T03:05:29 | 167,732,922 | 3 | 0 | BSD-3-Clause | 2019-03-11T01:25:14 | 2019-01-26T20:00:28 | C++ | UTF-8 | C++ | false | false | 4,076 | cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "frc/AnalogTrigger.h"
#include <utility>
#include <hal/HAL.h>
#include "frc/AnalogInput.h"
#include "frc/WPIErrors.h"
using namespace frc;
AnalogTrigger::AnalogTrigger(int channel)
: AnalogTrigger(new AnalogInput(channel)) {
m_ownsAnalog = true;
AddChild(m_analogInput);
}
AnalogTrigger::AnalogTrigger(AnalogInput* input) {
m_analogInput = input;
int32_t status = 0;
int index = 0;
m_trigger = HAL_InitializeAnalogTrigger(input->m_port, &index, &status);
if (status != 0) {
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
m_index = std::numeric_limits<int>::max();
m_trigger = HAL_kInvalidHandle;
return;
}
m_index = index;
HAL_Report(HALUsageReporting::kResourceType_AnalogTrigger, input->m_channel);
SetName("AnalogTrigger", input->GetChannel());
}
AnalogTrigger::~AnalogTrigger() {
int32_t status = 0;
HAL_CleanAnalogTrigger(m_trigger, &status);
if (m_ownsAnalog) {
delete m_analogInput;
}
}
AnalogTrigger::AnalogTrigger(AnalogTrigger&& rhs)
: ErrorBase(std::move(rhs)),
SendableBase(std::move(rhs)),
m_index(std::move(rhs.m_index)) {
std::swap(m_trigger, rhs.m_trigger);
std::swap(m_analogInput, rhs.m_analogInput);
std::swap(m_ownsAnalog, rhs.m_ownsAnalog);
}
AnalogTrigger& AnalogTrigger::operator=(AnalogTrigger&& rhs) {
ErrorBase::operator=(std::move(rhs));
SendableBase::operator=(std::move(rhs));
m_index = std::move(rhs.m_index);
std::swap(m_trigger, rhs.m_trigger);
std::swap(m_analogInput, rhs.m_analogInput);
std::swap(m_ownsAnalog, rhs.m_ownsAnalog);
return *this;
}
void AnalogTrigger::SetLimitsVoltage(double lower, double upper) {
if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogTriggerLimitsVoltage(m_trigger, lower, upper, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
}
void AnalogTrigger::SetLimitsRaw(int lower, int upper) {
if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogTriggerLimitsRaw(m_trigger, lower, upper, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
}
void AnalogTrigger::SetAveraged(bool useAveragedValue) {
if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogTriggerAveraged(m_trigger, useAveragedValue, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
}
void AnalogTrigger::SetFiltered(bool useFilteredValue) {
if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogTriggerFiltered(m_trigger, useFilteredValue, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
}
int AnalogTrigger::GetIndex() const {
if (StatusIsFatal()) return -1;
return m_index;
}
bool AnalogTrigger::GetInWindow() {
if (StatusIsFatal()) return false;
int32_t status = 0;
bool result = HAL_GetAnalogTriggerInWindow(m_trigger, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
return result;
}
bool AnalogTrigger::GetTriggerState() {
if (StatusIsFatal()) return false;
int32_t status = 0;
bool result = HAL_GetAnalogTriggerTriggerState(m_trigger, &status);
wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
return result;
}
std::shared_ptr<AnalogTriggerOutput> AnalogTrigger::CreateOutput(
AnalogTriggerType type) const {
if (StatusIsFatal()) return nullptr;
return std::shared_ptr<AnalogTriggerOutput>(
new AnalogTriggerOutput(*this, type), NullDeleter<AnalogTriggerOutput>());
}
void AnalogTrigger::InitSendable(SendableBuilder& builder) {
if (m_ownsAnalog) m_analogInput->InitSendable(builder);
}
| [
"maximo43873@gmail.com"
] | maximo43873@gmail.com |
81585da4d5cb9d37fe20155bcd545cdbedc627fa | 5595c911796d316d6a1da3c28f257a8cb433b524 | /(1.2) Tumbuhan/mTumbuhan.cpp | 88a653b41a1c224bebe07f478d71bad815f62396 | [] | no_license | cmrudi/Tubes-OOP | be3121a80a034e9af0adb176c77ee34bb836eb86 | 62fde0eb89a9f038f67f7be4b3072cec8cd05b88 | refs/heads/master | 2016-08-11T16:17:37.540764 | 2016-03-11T08:16:11 | 2016-03-11T08:16:11 | 53,005,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | #include <iostream>
#include "mahkluk.h"
#include "tumbuhan.h"
using namespace std;
int main () {
tumbuhan plant;
plant.muncul();
plant.makan();
plant.regenerasi_shield();
return 0;
}
| [
"cutmeurahrudi@gmail.com"
] | cutmeurahrudi@gmail.com |
c1ec035b6c04973847bba01aedc8f3e50a3d0086 | 40f608d1961960345da32c52a143269fe615ee01 | /StepMotor_17HS3430_accel/StepMotor_17HS3430_accel.ino | 3dc7ef9f53313281fbc73fb410c7b33e56fc8bf0 | [] | no_license | awk6873/arduino-elevator-model | c608d27fd2ba2db28baadc4d058d39da1a093398 | 280cea5cc4090e9a10d879e1d3a6df6087f55109 | refs/heads/main | 2023-04-20T16:10:08.529325 | 2021-05-05T16:42:12 | 2021-05-05T16:42:12 | 363,899,771 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,355 | ino | //#define DEBUG
const int motorEnablePin = 2;
const int motorDirPin = 3;
const int motorStepPin = 4;
const int motorDirUp = 0; // сигнал DIR драйвера ШД для подъема/спуска кабины
const int motorDirDown = 1;
const int motorEnable = 0; // сигнал Enable ШД
const int motorDisable = 1;
const long motorVmin = 30; // скорость начальная, имп./сек.
// скорость макс. для N мм/сек, шкив Ф 42 мм, 200 * 2 шагов (режим полушаг), имп./сек.
const long motorVmax = (100 / (PI * 42)) * 200 * 16; // ~ 394
const int motorAccSteps = 200 * 16; // максимальное число шагов для разгона/торможения
const long motorAcc = (motorVmax * motorVmax - motorVmin * motorVmin) / (2 * motorAccSteps); // ускорение
int dir = 0;
void setup() {
pinMode(motorEnablePin, OUTPUT);
pinMode(motorStepPin, OUTPUT);
pinMode(motorDirPin, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(motorEnablePin, motorEnable);
digitalWrite(motorDirPin, dir);
Serial.begin(115200);
// отладка !
pinMode(10, OUTPUT);
}
void loop() {
int steps;
float V;
long accFactor;
// число шагов
steps = 6400;
// определяем границы областей разгона и торможения - не больше 1/3 от всего перемещения
int accLastStep = steps / 3;
if (accLastStep > motorAccSteps) accLastStep = motorAccSteps;
int decFirstStep = steps - accLastStep;
// разгон от начальной скорости
V = motorVmin;
#ifdef DEBUG
Serial.print("Move motor with steps: ");
Serial.print(steps);
Serial.print(", direction: ");
Serial.print(dir);
Serial.print(", acceleration: ");
Serial.print(motorAcc);
Serial.print(", accel.steps: ");
Serial.println(accLastStep);
#endif
// цикл по шагам перемещения
for (int i = 1; i <= steps; i++) {
// засекаем время
unsigned long t = micros();
// формируем импульс
digitalWrite(motorStepPin, HIGH);
delayMicroseconds(100);
digitalWrite(motorStepPin, LOW);
// вычисляем период импульса
unsigned long T = 1000000 / V;
#ifdef DEBUG
Serial.print(i);
Serial.print(';');
Serial.print(V);
Serial.print(';');
Serial.println(T);
#endif
// вычисляем скорость для следующего шага
if (i <= accLastStep) {
// находимся в зоне разгона
V = sqrt(V * V + 2 * motorAcc);
if (V > motorVmax) V = motorVmax;
}
else if (i >= decFirstStep) {
// находимся в зоне торможения
V = sqrt(V * V - 2 * motorAcc);
if (V < motorVmin) V = motorVmin;
}
if (i > accLastStep && i < decFirstStep)
digitalWrite(13, HIGH);
else
digitalWrite(13, LOW);
// задержка для формирования периода импульса
delayMicroseconds(T - (micros() - t));
}
digitalWrite(10, HIGH);
delay(2000);
digitalWrite(10, LOW);
dir = (dir == motorDirUp)?motorDirDown:motorDirUp;
digitalWrite(motorDirPin, dir);
}
| [
"akabaev@beeline.ru"
] | akabaev@beeline.ru |
8761657cd93481796e42872c68435a7b952b8b3b | 0a4a6e6aa13c1e08983725bac007b9daf5ffe18c | /Transformaçoes 2d/transform3..cpp | 2c69e15a2a6a496297c7d0f83a717c9899bf195b | [] | no_license | Mateevee/ImplementacoesCG | f3289fa53d902d490497c1a5a415bf2a3d9ff234 | f2967c5fbd10ae9c458bdbf7eb5ad822b0ae2d97 | refs/heads/master | 2020-04-10T13:18:27.402209 | 2018-12-10T18:10:04 | 2018-12-10T18:10:04 | 161,046,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,507 | cpp |
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
float angle = 0, scale = 1.0;
float xtrans = 0, ytrans = 0, ztrans = 0;
int enableMenu = 0;
void fillVector();
void display(void);
void init(void);
void desenhaEixos();
void mouse(int button, int state, int x, int y);
int v1=0, v2=0;
vector<std::pair<float,float>> cords;
int main(int argc, char** argv)
{
glutInit(&argc, argv);
fillVector();
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGB);
glutInitWindowSize(300, 300);
glutInitWindowPosition(100, 100);
glutCreateWindow("hello");
glutMouseFunc(mouse);
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
void fillVector()
{
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
cords.push_back(make_pair(-2.5 + (j), -2.5 + (i)));
}
}
}
// Mouse callback
void mouse(int button, int state, int x, int y)
{
v1 = (x/50);
v2 = (6 - (y / 50))-1;
cout << get<0>(cords.at(v1)) << endl;
}
void desenhaEixos()
{
int x, y, color = 0;
glClear(GL_COLOR_BUFFER_BIT);
for (x = 0; x < 8; x++) {
if (color == 0) {
glColor3f(0.0, 0.0, 0.0);
color++;
}
else {
glColor3f(1.0, 1.0, 1.0);
color = 0;
}
for (y = 0; y < 8; y++) {
if (color == 0) {
glColor3f(0.0, 0.0, 0.0);
color++;
}
else {
glColor3f(1.0, 1.0, 1.0);
color = 0;
}
glBegin(GL_QUADS);
glVertex2f(-3 + x, -3 + y);
glVertex2f(x, -3 + y);
glVertex2f(x, y);
glVertex2f(-3 + x, y);
glEnd();
}
}
glColor3f(1.0, 0.0, 0.0);
glPushMatrix();
glTranslatef(get<0>(cords.at(v1)), get<0>(cords.at(v2)), 0.0);
glutSolidSphere(.5, 50, 50);
glPopMatrix();
glFlush();
}
void display(void)
{
// Limpar todos os pixels
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity(); // Inicializa com matriz identidade
desenhaEixos();
glColor3f(1.0, 0.0, 0.0);
glPushMatrix();
glTranslatef(xtrans, ytrans, 0.0);
glRotatef(angle, 0.0, 0.0, 1.0);
glScalef(scale, scale, scale);
glutWireCube(10);
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
void init(void)
{
// selecionar cor de fundo (preto)
glClearColor(0.0, 0.0, 0.0, 0.0);
// inicializar sistema de viz.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-3, 3, -3, 3, -3, 3);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
| [
"noreply@github.com"
] | noreply@github.com |
5ad5d42cf704a8c879cd3d31af24bac6ccb6f75f | 89ff92342a0bf80f6853cfad8d9f42142bee99a5 | /station.cpp | ccd89ba34065de6cb523eae5d8ca991c0dc7310f | [] | no_license | khademul/homework-7 | e6aeeb9e0088d0d94fe54b0d49068f87be09174b | 70cd16a95ed5afcf322754330dae83d7e123249f | refs/heads/master | 2020-03-28T01:03:29.810289 | 2015-03-28T00:38:34 | 2015-03-28T00:38:34 | 32,766,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | cpp | /*
* station.cpp
*
*
* Khademul Haque
*/
#include "station.h"
NetworkCode Station::getNetworkCode() const {
return networkCode;
}
const char *Station::getNetworkCodeString() const {
switch(networkCode) {
case CE:
return "CE";
case CI:
return "CI";
case FA:
return "FA";
case NP:
return "NP";
case WR:
return "WR";
}
return NULL;
}
void Station::setNetworkCode(NetworkCode networkCode) {
this->networkCode = networkCode;
}
char Station::getOrientation() const {
return orientation;
}
void Station::setOrientation(char orientation) {
this->orientation = orientation;
}
std::string Station::getStationCode() const {
return stationCode;
}
void Station::setStationCode(std::string stationCode) {
this->stationCode = stationCode;
}
TypeOfBand Station::getTypeOfBand() const {
return typeOfBand;
}
void Station::setTypeOfBand(TypeOfBand typeOfBand) {
this->typeOfBand = typeOfBand;
}
TypeOfInstrument Station::getTypeOfInstrument() const {
return typeOfInstrument;
}
void Station::setTypeOfInstrument(TypeOfInstrument typeOfInstrument) {
this->typeOfInstrument = typeOfInstrument;
} | [
"khademul144@gmail.com"
] | khademul144@gmail.com |
69740f9661dcf1fd172ca0d09300769202afb59a | a2151e6936b591f1c6c3c1a8f3bea00577d4c9ad | /一顆星/UVA11005_Cheapest_Base.cpp | 4eed462239b8196fef9aaa2963cb1fadcbc205d3 | [] | no_license | 410621229/dsccpp | 6f74349248b1b4032c688344f6812971a4759d60 | 5f70aed6939cf647c9bc1353838da509869da6c7 | refs/heads/master | 2020-06-08T10:22:12.313116 | 2019-12-04T15:33:19 | 2019-12-04T15:33:19 | 193,212,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,195 | cpp | #include <cstdio>
#include <cstdlib>
#define oo 2147483647
void CalCost(int num, int bas, int a[], int base[]){
int k = num;
while(k){
base[bas - 1] += a[k % bas];
k /= bas;
}
}
int main(){
int a[36]; //存輸入的36個數字
int base[36]; // 存計算完的所有花費
int T, Case = 1;
scanf("%d", &T);
while(T--){
printf("Case %d:\n", Case);
if(Case > 1)
puts("");
Case++;
for(int i = 0; i < 36; i++)
scanf("%d", &a[i]);
int n;
scanf("%d", &n);
int num, min = oo;
while(n--){
min = oo;
scanf("%d", &num);
printf("Cheapest base(s) for number %d: ", num);
for(int i = 1; i < 36; i++){
base[i] = 0;
}
for(int i = 1; i < 36; i++)
CalCost(num , i+1, a, base);
for(int i = 1; i < 36; i++){
if(base[i] < min) min = base[i];
}
for(int i = 1; i < 36; i++){
if(base[i] == min)
printf("%d ", i+1);
}
printf("\n");
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
1e19f641388382f32447c64fdfc7366c96d02e74 | 03ea882f1f247db8a73f99d4c8ef0ac41cfcffda | /src/CImageGC.h | 6e81842ef2652cbf02b767d364ec6ed69573b1ff | [
"MIT"
] | permissive | colinw7/Cwm | b44a02ef3cdc4884c19b84732f4a54fbde1d7fef | dc68c207b5b15f24d81fce0e3c04e9c0c580212a | refs/heads/master | 2023-01-24T12:20:05.703709 | 2023-01-16T14:45:34 | 2023-01-16T14:45:34 | 10,445,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 621 | h | #ifndef CIMAGE_GC_H
#define CIMAGE_GC_H
#include <CRGBA.h>
class CImageGC {
private:
CRGBA fg_rgba_;
int fg_ind_;
CRGBA bg_rgba_;
int bg_ind_;
public:
CImageGC();
~CImageGC() { }
void getForeground(CRGBA &rgba) const { rgba = fg_rgba_; }
void getForeground(int &ind ) const { ind = fg_ind_ ; }
void setForeground(const CRGBA &rgba);
void setForeground(int ind);
void getBackground(CRGBA &rgba) const { rgba = bg_rgba_; }
void getBackground(int &ind ) const { ind = bg_ind_ ; }
void setBackground(const CRGBA &rgba);
void setBackground(int ind );
};
#endif
| [
"colinw7@gmail.com"
] | colinw7@gmail.com |
08a53a41ffa7c8c4bd72cd9f85d4fbfc4a006750 | 4b02aa96b41c7852678e7c9b3361830b2d1a1a09 | /LeetCode-solution/problems/next_permutation/solution.cpp | aa29cb40a8ca09c84b70f0d8e425dd1435e88557 | [] | no_license | arifkhan1990/LeetCode-solution | 4a4124d6b41dc516b673d1b1adc693054a00509f | 85e1a3a285ee059dce091621b79312ba96024eed | refs/heads/master | 2023-01-13T17:26:13.720649 | 2023-01-12T17:35:39 | 2023-01-12T17:35:39 | 243,922,740 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | class Solution {
public:
void nextPermutation(vector<int>& nums) {
// sort(nums.begin(),nums.end());
while(next_permutation(nums.begin(),nums.end())){
cout << "[";
for(int i = 0; i < nums.size() ; i++){
cout << nums[i];
if(i != nums.size() -1)
cout << ",";
}
cout << "]" << endl;
break;
}
}
}; | [
"arifkhanshubro@gmail.com"
] | arifkhanshubro@gmail.com |
3ca5742de5f22db7ba37cd6f3936805f3c41f026 | db079ec2b7a66ecb7f7bc7908e5d417f61cc15d4 | /apg4b/086a.cpp | eabaacb498b04328c04526614729616e86720110 | [] | no_license | Hayabusa1601/Atcoder-codes | 045cc92648311d3b2d6cb88f1295bc4a3149aca3 | 1911bd84ba2baeede3ca973ff2a642562f89768c | refs/heads/master | 2023-09-01T20:57:29.824441 | 2021-09-26T13:56:07 | 2021-09-26T13:56:07 | 272,010,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | #include<iostream>
using namespace std;
int main(){
int a, b;
cin >> a >> b;
if(a*b){
cout << "Odd" << endl;
}else{
cout << "Even" << endl;
}
return 0;
} | [
"1601hayabusa@gmail.com"
] | 1601hayabusa@gmail.com |
99384234424ff51e32036469556182e103a2817c | 9eb6451bc703c9bf1d7c5867a6214afe7f8bcb82 | /Cellar/blast/2.8.1/include/ncbi-tools++/objtools/edit/text_object_description.hpp | 737c18fcc5b25f91ba62137999b1818f9ee3ea7f | [] | no_license | SteveZhangSZ/CSE180_script | 6d057c0f37593b48c001d17c75ec8ba4a81f0fc7 | f81b3b88249ec458fa194b3f1af178e69ce4a1ef | refs/heads/master | 2022-11-30T04:54:36.124252 | 2020-08-18T15:29:14 | 2020-08-18T15:29:14 | 288,036,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,045 | hpp | /* $Id: text_object_description.hpp 575170 2018-11-26 13:17:25Z ivanov $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Sema Kachalo
*/
#ifndef _EDIT_RNA_EDIT__HPP_
#define _EDIT_RNA_EDIT__HPP_
#include <corelib/ncbistd.hpp>
#include <corelib/ncbiobj.hpp>
#include <objmgr/scope.hpp>
#include <objects/seqfeat/Seq_feat.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
BEGIN_SCOPE(edit)
NCBI_DLL_IMPORT string GetTextObjectDescription(const CSeq_feat& sf, CScope& scope);
NCBI_DLL_IMPORT string GetTextObjectDescription(const CSeqdesc& sd, CScope& scope);
NCBI_DLL_IMPORT string GetTextObjectDescription(const CBioseq& bs, CScope& scope);
NCBI_DLL_IMPORT string GetTextObjectDescription(const CBioseq_set& bs, CScope& scope);
END_SCOPE(edit)
END_SCOPE(objects)
END_NCBI_SCOPE
#endif
// _EDIT_RNA_EDIT__HPP_
| [
"sz.stevezhang.sz@gmail.com"
] | sz.stevezhang.sz@gmail.com |
bd3d27033fb398f16aa35ff65c919f401f555bad | 32008c385f0f676714133fcddc8904b180b379ae | /code_book/Thinking C++/master/C07/PriorityQueue6.cpp | c4681bf90c044bfcce073880da13f309ce002df5 | [] | no_license | dracohan/code | d92dca0a4ee6e0b3c10ea3c4f381cb1068a10a6e | 378b6fe945ec2e859cc84bf50375ec44463f23bb | refs/heads/master | 2023-08-18T23:32:30.565886 | 2023-08-17T17:16:29 | 2023-08-17T17:16:29 | 48,644,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,520 | cpp | //: C07:PriorityQueue6.cpp
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iterator>
#include <queue>
using namespace std;
template<class T, class Compare>
class PQV : public vector<T> {
Compare comp;
bool sorted;
void assureHeap() {
if(sorted) {
// Turn it back into a heap:
make_heap(begin(), end(), comp);
sorted = false;
}
}
public:
PQV(Compare cmp = Compare()) : comp(cmp) {
make_heap(begin(), end(), comp);
sorted = false;
}
const T& top() {
assureHeap();
return front();
}
void push(const T& x) {
assureHeap();
// Put it at the end:
push_back(x);
// Re-adjust the heap:
push_heap(begin(), end(), comp);
}
void pop() {
assureHeap();
// Move the top element to the last position:
pop_heap(begin(), end(), comp);
// Remove that element:
pop_back();
}
void sort() {
if(!sorted) {
sort_heap(begin(), end(), comp);
reverse(begin(), end());
sorted = true;
}
}
};
int main() {
PQV<int, less<int> > pqi;
srand(time(0));
for(int i = 0; i < 100; i++) {
pqi.push(rand() % 25);
copy(pqi.begin(), pqi.end(),
ostream_iterator<int>(cout, " "));
cout << "\n-----\n";
}
pqi.sort();
copy(pqi.begin(), pqi.end(),
ostream_iterator<int>(cout, " "));
cout << "\n-----\n";
while(!pqi.empty()) {
cout << pqi.top() << ' ';
pqi.pop();
}
} ///:~
| [
"13240943@qq.com"
] | 13240943@qq.com |
a558a007ee9c96e069986f9c82a4def8eec3e623 | 1e58ee167a1d2b03931a908ff18a11bd4b4005b4 | /groups/btl/btlso/btlso_defaulteventmanager_epoll.t.cpp | 311665c0b2e3515b7973eb3d9f203e382d1033ca | [
"Apache-2.0"
] | permissive | dhbaird/bde | 23a2592b753bc8f7139d7c94bc56a2d6c9a8a360 | a84bc84258ccdd77b45c41a277632394ebc032d7 | refs/heads/master | 2021-01-19T16:34:04.040918 | 2017-06-06T14:35:05 | 2017-06-08T11:27:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66,430 | cpp | // btlso_defaulteventmanager_epoll.t.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <btlso_defaulteventmanager_epoll.h>
#include <btlso_socketimputil.h>
#include <btlso_socketoptutil.h>
#include <btlso_timemetrics.h>
#include <btlso_eventmanagertester.h>
#include <btlso_platform.h>
#include <btlso_flag.h>
#include <bdlf_bind.h>
#include <bdlf_memfn.h>
#include <bslma_default.h>
#include <bslma_defaultallocatorguard.h>
#include <bslma_testallocator.h>
#include <bdlt_currenttime.h>
#include <bsls_timeinterval.h>
#include <bsls_platform.h>
#include <bsl_fstream.h>
#include <bsl_iostream.h>
#include <bsl_c_stdio.h>
#include <bsl_c_stdlib.h>
#include <bsl_functional.h>
#include <bsls_assert.h>
#include <bsl_set.h>
#include <bsl_string.h>
using namespace BloombergLP;
#if defined(BSLS_PLATFORM_OS_LINUX)
#define BTESO_EVENTMANAGER_ENABLETEST
typedef btlso::DefaultEventManager<btlso::Platform::EPOLL> Obj;
#endif
#ifdef BTESO_EVENTMANAGER_ENABLETEST
#include <bsl_c_errno.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <linux/version.h>
using namespace bsl; // automatically added by script
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// OVERVIEW
// Test the corresponding event manager component by using
// 'btlso::EventManagerTester' to exercise the "standard" test which applies to
// any event manager's test. Since the difference exists in implementation
// between different event manager components, the "customized" test is also
// given for this event manager. The "customized" test is implemented by
// utilizing the same script grammar and the same script interpreting defined
// in 'btlso::EventManagerTester' function but a new set of data to test this
// specific event manager component.
//-----------------------------------------------------------------------------
// CREATORS
// [ 2] btlso::DefaultEventManager
// [ 2] ~btlso::DefaultEventManager
//
// MANIPULATORS
// [ 4] registerSocketEvent
// [ 5] deregisterSocketEvent
// [ 6] deregisterSocket
// [ 9] deregisterSocket
// [ 7] deregisterAll
// [ 8] dispatch
//
// ACCESSORS
// [13] hasLimitedSocketCapacity
// [ 3] numSocketEvents
// [ 3] numEvents
// [ 3] isRegistered
//-----------------------------------------------------------------------------
// [14] USAGE EXAMPLE
// [13] Testing TRAITS
// [10] SYSTEM INTERFACES ASSUMPTIONS
// [ 1] Breathing test
// [-1] 'dispatch' PERFORMANCE DATA
// [-2] 'registerSocketEvent' PERFORMANCE DATA
//=============================================================================
// STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
static int testStatus = 0;
void aSsErT(int c, const char *s, int i)
{
if (c) {
cout << "Error " << __FILE__ << "(" << i << "): " << s
<< " (failed)" << endl;
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
#define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }
//=============================================================================
// SEMI-STANDARD TEST OUTPUT MACROS
//-----------------------------------------------------------------------------
#define P(X) cout << #X " = " << (X) << endl; // Print identifier and value.
#define Q(X) cout << "<| " #X " |>" << endl; // Quote identifier literally.
#define P_(X) cout << #X " = " << (X) << ", "<< flush; // P(X) without '\n'
#define L_ __LINE__ // current Line number
//=============================================================================
// STANDARD BDE LOOP-ASSERT TEST MACROS
//-----------------------------------------------------------------------------
#define LOOP_ASSERT(I,X) { \
if (!(X)) { cout << #I << ": " << I << "\n"; aSsErT(1, #X, __LINE__); }}
#define LOOP2_ASSERT(I,J,X) { \
if (!(X)) { cout << #I << ": " << I << "\t" << #J << ": " \
<< J << "\n"; aSsErT(1, #X, __LINE__); } }
#define LOOP3_ASSERT(I,J,K,X) { \
if (!(X)) { cout << #I << ": " << I << "\t" << #J << ": " << J << "\t" \
<< #K << ": " << K << "\n"; aSsErT(1, #X, __LINE__); } }
//=============================================================================
// The level of verbosity.
//-----------------------------------------------------------------------------
static int globalVerbose, globalVeryVerbose, globalVeryVeryVerbose;
//=============================================================================
// Control byte used to verify reads and writes.
//-----------------------------------------------------------------------------
const char control_byte(0x53);
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
typedef btlso::EventManagerTester EventManagerTester;
// Test success and failure codes.
enum {
FAIL = -1,
SUCCESS = 0
};
enum {
MAX_SCRIPT = 50,
MAX_PORT = 50,
BUF_LEN = 8192
};
#if defined(BSLS_PLATFORM_OS_WINDOWS)
enum {
READ_SIZE = 8192,
WRITE_SIZE = 30000
};
#else
enum {
READ_SIZE = 8192,
WRITE_SIZE = 73728
};
#endif
//=============================================================================
// HELPER CLASSES
//-----------------------------------------------------------------------------
static void genericCb(btlso::EventType::Type event,
btlso::SocketHandle::Handle socket,
int bytes,
btlso::EventManager *)
{
// User specified callback function that will be called after an event
// is dispatched to do the "real" things.
// This callback is only used in the 'usage example' test case, and will
// be copied to the head file as a part of the usage example.
enum {
k_MAX_READ_SIZE = 8192,
k_MAX_WRITE_SIZE = WRITE_SIZE
};
switch (event) {
case btlso::EventType::e_READ: {
ASSERT(0 < bytes);
char buffer[k_MAX_READ_SIZE];
int rc = btlso::SocketImpUtil::read(buffer, socket, bytes, 0);
ASSERT(0 < rc);
} break;
case btlso::EventType::e_WRITE: {
char wBuffer[k_MAX_WRITE_SIZE];
ASSERT(0 < bytes);
ASSERT(k_MAX_WRITE_SIZE >= bytes);
memset(wBuffer,'4', bytes);
int rc = btlso::SocketImpUtil::write(socket, &wBuffer, bytes, 0);
ASSERT(0 < rc);
} break;
case btlso::EventType::e_ACCEPT: {
int errCode;
int rc = btlso::SocketImpUtil::close(socket, &errCode);
ASSERT(0 == rc);
} break;
case btlso::EventType::e_CONNECT: {
int errCode = 0;
btlso::SocketImpUtil::close(socket, &errCode);
ASSERT(0 == errCode);
} break;
default: {
ASSERT("Invalid event code" && 0);
} break;
}
}
void assertCb()
{
BSLS_ASSERT_OPT(0);
}
static void emptyCb()
{
}
static void allocatedArgument(const bsl::string& argument) {
(void)argument;
}
static void multiRegisterDeregisterCb(Obj *mX)
{
btlso::SocketHandle::Handle socket[2];
int rc = btlso::SocketImpUtil::socketPair<btlso::IPv4Address>(
socket,
btlso::SocketImpUtil::k_SOCKET_STREAM);
ASSERT(0 == rc);
bsl::function<void()> emptyCallBack(&emptyCb);
// Register and deregister the socket handle six times. All registrations
// are done by invoking 'registerSocketEvent'. The deregistrations are
// done by invoking 'deregisterSocketEvent' twice, 'deregisterSocket'
// twice, and 'deregisterAll' twice.
ASSERT(0 == mX->registerSocketEvent(socket[0],
btlso::EventType::e_READ,
emptyCallBack));
mX->deregisterSocketEvent(socket[0], btlso::EventType::e_READ);
ASSERT(0 == mX->registerSocketEvent(socket[0],
btlso::EventType::e_READ,
emptyCallBack));
mX->deregisterSocket(socket[0]);
ASSERT(0 == mX->registerSocketEvent(socket[0],
btlso::EventType::e_READ,
emptyCallBack));
mX->deregisterAll();
ASSERT(0 == mX->registerSocketEvent(socket[0],
btlso::EventType::e_READ,
emptyCallBack));
mX->deregisterSocketEvent(socket[0], btlso::EventType::e_READ);
ASSERT(0 == mX->registerSocketEvent(socket[0],
btlso::EventType::e_READ,
emptyCallBack));
mX->deregisterSocket(socket[0]);
ASSERT(0 == mX->registerSocketEvent(socket[0],
btlso::EventType::e_READ,
emptyCallBack));
mX->deregisterAll();
}
#endif // BTESO_EVENTMANAGER_ENABLETEST
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
#ifdef BTESO_EVENTMANAGER_ENABLETEST
int test = argc > 1 ? atoi(argv[1]) : 0;
int verbose = argc > 2; globalVerbose = verbose;
int veryVerbose = argc > 3; globalVeryVerbose = veryVerbose;
int veryVeryVerbose = argc > 4; globalVeryVeryVerbose = veryVeryVerbose;
int controlFlag = 0;
if (veryVeryVerbose) {
controlFlag |= btlso::EventManagerTester::k_VERY_VERY_VERBOSE;
}
if (veryVerbose) {
controlFlag |= btlso::EventManagerTester::k_VERY_VERBOSE;
}
if (verbose) {
controlFlag |= btlso::EventManagerTester::k_VERBOSE;
}
cout << "TEST " << __FILE__ << " CASE " << test << endl;
btlso::SocketImpUtil::startup();
bslma::TestAllocator testAllocator("test", veryVeryVerbose);
testAllocator.setNoAbort(1); // tbd -- really? why?
btlso::TimeMetrics timeMetric(btlso::TimeMetrics::e_MIN_NUM_CATEGORIES,
btlso::TimeMetrics::e_CPU_BOUND,
&testAllocator);
bslma::TestAllocator defaultAllocator("default", veryVeryVerbose);
bslma::DefaultAllocatorGuard defaultAllocatorGuard(&defaultAllocator);
switch (test) { case 0:
case 15: {
// --------------------------------------------------------------------
// TESTING USAGE EXAMPLE
// The usage example provided in the component header file must
// compile, link, and run on all platforms as shown.
//
// Plan:
// Incorporate usage example from header into driver, remove
// leading comment characters, and replace 'assert' with
// 'ASSERT'.
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Usage Example"
<< "\n=====================" << endl;
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Using an event manager
///- - - - - - - - - - - - - - - - -
btlso::TimeMetrics timeMetric(btlso::TimeMetrics::e_MIN_NUM_CATEGORIES,
btlso::TimeMetrics::e_CPU_BOUND);
btlso::DefaultEventManager<btlso::Platform::EPOLL> mX(&timeMetric);
btlso::SocketHandle::Handle socket[2];
int rc = btlso::SocketImpUtil::socketPair<btlso::IPv4Address>(
socket,
btlso::SocketImpUtil::k_SOCKET_STREAM);
ASSERT(0 == rc);
int numBytes = 5;
btlso::EventManager::Callback readCb(
bdlf::BindUtil::bind(&genericCb,
btlso::EventType::e_READ,
socket[0],
numBytes,
&mX));
mX.registerSocketEvent(socket[0], btlso::EventType::e_READ, readCb);
numBytes = 25;
btlso::EventManager::Callback writeCb1(
bdlf::BindUtil::bind(&genericCb,
btlso::EventType::e_WRITE,
socket[0],
numBytes,
&mX));
mX.registerSocketEvent(socket[0], btlso::EventType::e_WRITE, writeCb1);
numBytes = 15;
btlso::EventManager::Callback writeCb2(
bdlf::BindUtil::bind(&genericCb,
btlso::EventType::e_WRITE,
socket[1],
numBytes,
&mX));
mX.registerSocketEvent(socket[1], btlso::EventType::e_WRITE, writeCb2);
ASSERT(3 == mX.numEvents());
ASSERT(2 == mX.numSocketEvents(socket[0]));
ASSERT(1 == mX.numSocketEvents(socket[1]));
ASSERT(1 == mX.isRegistered(socket[0], btlso::EventType::e_READ));
ASSERT(0 == mX.isRegistered(socket[1], btlso::EventType::e_READ));
ASSERT(1 == mX.isRegistered(socket[0], btlso::EventType::e_WRITE));
ASSERT(1 == mX.isRegistered(socket[1], btlso::EventType::e_WRITE));
int flags = 0;
bsls::TimeInterval deadline(bdlt::CurrentTime::now());
deadline += 5; // timeout 5 seconds from now.
rc = mX.dispatch(deadline, flags); ASSERT(2 == rc);
mX.deregisterSocketEvent(socket[0], btlso::EventType::e_WRITE);
ASSERT(2 == mX.numEvents());
ASSERT(1 == mX.numSocketEvents(socket[0]));
ASSERT(1 == mX.numSocketEvents(socket[1]));
ASSERT(1 == mX.isRegistered(socket[0], btlso::EventType::e_READ));
ASSERT(0 == mX.isRegistered(socket[1], btlso::EventType::e_READ));
ASSERT(0 == mX.isRegistered(socket[0], btlso::EventType::e_WRITE));
ASSERT(1 == mX.isRegistered(socket[1], btlso::EventType::e_WRITE));
ASSERT(1 == mX.deregisterSocket(socket[1]));
ASSERT(1 == mX.numEvents());
ASSERT(1 == mX.numSocketEvents(socket[0]));
ASSERT(0 == mX.numSocketEvents(socket[1]));
ASSERT(1 == mX.isRegistered(socket[0], btlso::EventType::e_READ));
ASSERT(0 == mX.isRegistered(socket[1], btlso::EventType::e_READ));
ASSERT(0 == mX.isRegistered(socket[0], btlso::EventType::e_WRITE));
ASSERT(0 == mX.isRegistered(socket[1], btlso::EventType::e_WRITE));
mX.deregisterAll();
ASSERT(0 == mX.numEvents());
ASSERT(0 == mX.numSocketEvents(socket[0]));
ASSERT(0 == mX.numSocketEvents(socket[1]));
ASSERT(0 == mX.isRegistered(socket[0], btlso::EventType::e_READ));
ASSERT(0 == mX.isRegistered(socket[0], btlso::EventType::e_READ));
ASSERT(0 == mX.isRegistered(socket[0], btlso::EventType::e_WRITE));
ASSERT(0 == mX.isRegistered(socket[1], btlso::EventType::e_WRITE));
} break;
case 14: {
// --------------------------------------------------------------------
// Test allocator usage
//
// Concern:
//: 1 Registered events hold memory from the specified allocator
//
// Plan:
//: 1 Register an event having a callback functor requiring dynamic
// memory allocation
//: 2 Check that no memory is outstanding from the default allocator,
// and that memory is outstanding from the test allocator
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING allocator usage" << endl
<< "=======================" << endl;
Obj mX(0, &testAllocator);
btlso::SocketHandle::Handle socket[2];
int rc = btlso::SocketImpUtil::socketPair<btlso::IPv4Address>(
socket, btlso::SocketImpUtil::k_SOCKET_STREAM);
ASSERT(0 == rc);
{
bsl::string argument =
"a long string that must be heap-allocated";
btlso::EventManager::Callback cb =
bdlf::BindUtil::bind(&allocatedArgument, argument);
if (veryVerbose) cout << "...registering event..." << endl;
ASSERT(0 == mX.registerSocketEvent(socket[0],
btlso::EventType::e_READ,
cb));
}
ASSERT(0 != testAllocator.numBlocksInUse());
ASSERT(0 == defaultAllocator.numBlocksInUse());
} break;
case 13: {
// --------------------------------------------------------------------
// TESTING 'hasLimitedSocketCapacity'
//
// Concern:
//: 1 'hasLimitedSocketCapacity' returns 'false'.
//
// Plan:
//: 1 Assert that 'hasLimitedSocketCapacity' returns 'false'.
//
// Testing:
// bool hasLimitedSocketCapacity() const;
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'hasLimitedSocketCapacity'" << endl
<< "==================================" << endl;
if (verbose) cout << "Testing 'hasLimitedSocketCapacity'" << endl;
{
Obj mX; const Obj& X = mX;
bool hlsc = X.hasLimitedSocketCapacity();
LOOP_ASSERT(hlsc, false == hlsc);
}
} break;
case 12: {
// --------------------------------------------------------------------
// TESTING TRAITS
//
// Concerns:
// That all of the classes defined in the component under test have
// the expected traits declared.
//
// Plan:
// Using the C++11-style traits, verify that the 'struct epoll_event'
// defines the expected trait, namely 'bsl::is_trivially_copyable'.
//
// Testing:
// bsl::is_trivially_copyable trait on epoll_event
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Traits"
<< "\n==============" << endl;
if (verbose) cout << "\nTesting struct ::epoll_event." << endl;
{
ASSERT(true ==
bsl::is_trivially_copyable<struct ::epoll_event>::value);
}
} break;
case 11: {
// --------------------------------------------------------------------
// MULTIPLE REGISTERING AND DEREGISTERING IN CALLBACK
//
// Concerns:
// Registering and deregistering functions can be called in pairs
// multiple times in a callback function without problem.
//
// Methodology:
// We register a socket handle to a event manager with a special
// callback function that does extra multiple registering and
// deregistering to the same event manager by invoking the methods
// inteded for testing. Verify there is no printed error or crash
// ater the callback is executed.
//
// Testing:
// 'registerSocketEvent' in a callback function
// 'deregisterSocketEvent' in a callback function
// 'deregisterSocket' in a callback function
// 'deregisterAll' in a callback function
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "MULTIPLE REGISTERING AND DEREGISTERING IN CALLBACK" << endl
<< "==================================================" << endl;
enum { NUM_BYTES = 16 };
Obj mX;
btlso::SocketHandle::Handle socket[2];
int rc = btlso::SocketImpUtil::socketPair<btlso::IPv4Address>(
socket, btlso::SocketImpUtil::k_SOCKET_STREAM);
ASSERT(0 == rc);
btlso::EventManager::Callback multiRegisterDeregisterCallback(
bdlf::BindUtil::bind(&multiRegisterDeregisterCb, &mX));
ASSERT(0 == mX.registerSocketEvent(socket[0],
btlso::EventType::e_READ,
multiRegisterDeregisterCallback));
ASSERT(0 == mX.registerSocketEvent(socket[0],
btlso::EventType::e_WRITE,
multiRegisterDeregisterCallback));
ASSERT(0 == mX.registerSocketEvent(socket[1],
btlso::EventType::e_READ,
multiRegisterDeregisterCallback));
ASSERT(0 == mX.registerSocketEvent(socket[1],
btlso::EventType::e_WRITE,
multiRegisterDeregisterCallback));
char wBuffer[NUM_BYTES];
memset(wBuffer,'4', NUM_BYTES);
rc = btlso::SocketImpUtil::write(socket[0], &wBuffer, NUM_BYTES, 0);
ASSERT(0 < rc);
ASSERT(1 == mX.dispatch(bsls::TimeInterval(1.0), 0));
} break;
case 10: {
// --------------------------------------------------------------------
// VERIFYING ASSUMPTIONS REGARDING 'epoll' MECHANISM
// Concerns:
// o epoll fd can be created
// o can register multiple socket handles incrementally
// o can deregister multiple socket handles in incrementally
// o 'epoll_wait' signals properly when appropriate socket event
// occurs
// o 'epoll_wait' signals properly when appropriate socket events
// occur
// Methodology:
// Create a set of (connected) socket pairs, register certain
// endpoints with the 'select' call and use the peer endpoints
// control.
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "VERIFYING 'epoll' MECHANISM" << endl
<< "===========================" << endl;
if (veryVerbose) cout << "\tInitializing socket pairs." << endl;
enum { NUM_PAIRS = 10 };
btlso::EventManagerTestPair testPairs[NUM_PAIRS];
for (int i = 0; i < NUM_PAIRS; i++) {
testPairs[i].setObservedBufferOptions(BUF_LEN, 1);
testPairs[i].setControlBufferOptions(BUF_LEN, 1);
}
if (veryVerbose)
cout << "\tAddressing concern #1: Calling epoll_create." << endl;
{
const int epollFd = epoll_create(1);
ASSERT(0 <= epollFd);
ASSERT(0 == close(epollFd));
}
if (veryVerbose)
cout << "\tAddressing concern #2: Incremental registration."
<< endl;
{
int epollFd = epoll_create(1);
ASSERT(0 <= epollFd);
if (veryVerbose) {
cout << "\t\tRegistering test pairs." << endl;
}
for (int i = 0; i < NUM_PAIRS; ++i) {
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = (void *) 0x12345678;
const int rc = epoll_ctl(epollFd, EPOLL_CTL_ADD,
testPairs[i].observedFd(),
&ev);
LOOP_ASSERT(i, 0 == rc);
}
if (veryVerbose) {
cout << "\t\tVerifying correct registration." << endl;
}
for (int i = 0; i < NUM_PAIRS; ++i) {
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = (void *) 0x12345678;
int rc = epoll_ctl(epollFd, EPOLL_CTL_ADD,
testPairs[i].observedFd(),
&ev);
LOOP_ASSERT(i, 0 != rc && EEXIST == errno);
ev.events = EPOLLIN;
ev.data.ptr = (void *) 0x12345678;
rc = epoll_ctl(epollFd, EPOLL_CTL_MOD,
testPairs[i].observedFd(),
&ev);
LOOP_ASSERT(i, 0 == rc);
}
ASSERT(0 == close(epollFd));
}
if (veryVerbose)
cout << "\tAddressing concern #3: Incremental deregistration."
<< endl;
{
int epollFd = epoll_create(1);
ASSERT(0 <= epollFd);
if (veryVerbose) {
cout << "\t\tRegistering test pairs." << endl;
}
for (int i = 0; i < NUM_PAIRS; ++i) {
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = (void *) 0x12345678;
const int rc = epoll_ctl(epollFd, EPOLL_CTL_ADD,
testPairs[i].observedFd(),
&ev);
LOOP_ASSERT(i, 0 == rc);
}
if (veryVerbose) {
cout << "\t\tDeregistering and verifying correctness." << endl;
}
for (int i = 0; i < NUM_PAIRS; ++i) {
struct epoll_event ev = {0,{0}};
int rc = epoll_ctl(epollFd, EPOLL_CTL_DEL,
testPairs[i].observedFd(),
&ev);
LOOP_ASSERT(i, 0 == rc);
ev.events = EPOLLIN;
ev.data.ptr = (void *) 0x12345678;
rc = epoll_ctl(epollFd, EPOLL_CTL_MOD,
testPairs[i].observedFd(),
&ev);
LOOP_ASSERT(i, 0 != rc && errno == ENOENT);
}
ASSERT(0 == close(epollFd));
}
if (veryVerbose)
cout << "\tAddressing concern #4: 'epoll_wait' behavior."
<< endl;
{
int epollFd = epoll_create(1);
ASSERT(0 <= epollFd);
if (veryVerbose) {
cout << "\t\tRegistering test pairs." << endl;
}
for (int i = 0; i < NUM_PAIRS; ++i) {
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = (void *) testPairs[i].observedFd();
const int rc = epoll_ctl(epollFd, EPOLL_CTL_ADD,
testPairs[i].observedFd(),
&ev);
LOOP_ASSERT(i, 0 == rc);
}
if (veryVerbose) {
cout << "\t\tSignalling and verifying correctness." << endl;
}
for (int i = 0; i < NUM_PAIRS; ++i) {
const char controlByte = 0xAB;
LOOP_ASSERT(i, sizeof(char) ==
write(testPairs[i].controlFd(), &controlByte,
sizeof(char)));
struct epoll_event events[2];
int rc = epoll_wait(epollFd, events, 2, -1);
LOOP_ASSERT(i, 1 == rc);
LOOP_ASSERT(i, (void *) testPairs[i].observedFd() ==
events[0].data.ptr);
LOOP_ASSERT(i, EPOLLIN == events[0].events);
char byte;
rc = read(testPairs[i].observedFd(), &byte, sizeof(char));
LOOP_ASSERT(i, sizeof(char) == rc);
LOOP_ASSERT(i, controlByte == byte);
}
ASSERT(0 == close(epollFd));
}
if (veryVerbose)
cout << "\tAddressing concern #5: 'epoll_wait' behavior."
<< endl;
{
int epollFd = epoll_create(1);
ASSERT(0 <= epollFd);
if (veryVerbose) {
cout << "\t\tRegistering test pairs." << endl;
}
for (int i = 0; i < NUM_PAIRS; ++i) {
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = (void *) testPairs[i].observedFd();
const int rc = epoll_ctl(epollFd, EPOLL_CTL_ADD,
testPairs[i].observedFd(),
&ev);
LOOP_ASSERT(i, 0 == rc);
}
if (veryVerbose) {
cout << "\t\tSignalling and verifying correctness." << endl;
}
for (int i = 0; i < NUM_PAIRS; ++i) {
const char controlByte = 0xAB;
LOOP_ASSERT(i, sizeof(char) ==
write(testPairs[i].controlFd(), &controlByte,
sizeof(char)));
struct epoll_event events[NUM_PAIRS + 1];
int rc = epoll_wait(epollFd, events, NUM_PAIRS + 1, -1);
LOOP_ASSERT(i, i + 1 == rc);
bsl::set<intptr_t> observedFds;
for (int j = 0; j < rc; ++j) {
intptr_t fd = (intptr_t) events[j].data.ptr;
ASSERT(observedFds.end() == observedFds.find(fd));
int k;
for (k = 0; k <= i; ++k) {
if (testPairs[k].observedFd() == fd) {
break;
}
}
LOOP2_ASSERT(k, i, k <= i);
observedFds.insert(fd);
LOOP2_ASSERT(i, j, POLLIN == events[j].events);
}
ASSERT(rc == static_cast<int>(observedFds.size()));
}
ASSERT(0 == close(epollFd));
}
} break;
case 9: {
// --------------------------------------------------------------------
// TESTING 'deregisterSocket' METHOD
//
// Concern:
// o Deregistration from a callback of the same socket is handled
// correctly
// o Deregistration from a callback of another socket is handled
// correctly
// o Deregistration from a callback of one of the _previous_
// sockets and subsequent registration is handled correctly -
//
// Plan:
// Create custom set of scripts for each concern and exercise them
// using 'btlso::EventManagerTester'.
//
// Testing:
// int deregisterSocket();
// --------------------------------------------------------------------
if (verbose) cout << endl << "TESTING 'deregisterSocket'" << endl
<< "==========================" << endl;
if (verbose)
cout << "\tAddressing concern# 1" << endl;
{
struct {
int d_line;
int d_fails; // number of failures in this script
const char *d_script;
} SCRIPTS[] =
{
//-------------->
{ L_, 0, "+0r64,{-0}; W0,64; T1; Dn,1; T0" },
{ L_, 0, "+0r64,{-0}; +1r64; W0,64; W1,64; T2; Dn,2; T1; E1r; E0" },
{ L_, 0, "+0r64,{-0}; +1r64; +2r64; W0,64; W1,64; W2,64; T3; Dn,3; T2;"
"E0; E1r; E2r" },
{ L_, 0, "+0r64; +1r64,{-1}; +2r64; W0,64; W1,64; W2,64; T3; Dn,3; T2"
"E0r; E1; E2r" },
{ L_, 0, "+0r64; +1r64; +2r64,{-2}; W0,64; W1,64; W2,64; T3; Dn,3; T2"
"E0r; E1r; E2" },
{ L_, 0, "+0r64,{-1; +1r64}; +1r64; W0,64; W1,64; T2; Dn,2; T2" },
//-------------->
};
const int NUM_SCRIPTS = sizeof SCRIPTS / sizeof *SCRIPTS;
for (int i = 0; i < NUM_SCRIPTS; ++i) {
Obj mX(&timeMetric, &testAllocator);
const int LINE = SCRIPTS[i].d_line;
enum { NUM_PAIRS = 4 };
btlso::EventManagerTestPair socketPairs[NUM_PAIRS];
for (int j = 0; j < NUM_PAIRS; j++) {
socketPairs[j].setObservedBufferOptions(BUF_LEN, 1);
socketPairs[j].setControlBufferOptions(BUF_LEN, 1);
}
int fails = btlso::EventManagerTester::gg(&mX,
socketPairs,
SCRIPTS[i].d_script,
controlFlag);
LOOP_ASSERT(LINE, SCRIPTS[i].d_fails == fails);
}
}
if (verbose)
cout << "\tAddressing concern# 2" << endl;
{
struct {
int d_line;
int d_fails; // number of failures in this script
const char *d_script;
} SCRIPTS[] =
{
//-------------->
/// On length 2
// Deregistering signaled socket handle
{ L_, 0, "+0r64,{-1}; +1r64,{-0}; W0,64; W1,64; T2; Dn,1; T1" },
{ L_, 0, "+0r64,{-1}; +1r64,{-0}; W1,64; W0,64; T2; Dn,1; T1" },
// Deregistering non-signaled socket handle
{ L_, 0, "+0r64, {-1}; +1r; W0,64; T2; Dn,1; T1; E0r; E1" },
{ L_, 0, "+0r; +1r64, {-0}; W1,64; T2; Dn,1; T1; E0; E1r" },
#if defined(LINUX_VERSION_CODE) && LINUX_VERSION_CODE > KERNEL_VERSION(2,6,9)
// Linux 2.6.9 does not seem to guarantee the order of fds, while
// later versions do. So we'll run this only if compiled on 2.6.10 and
// later.
#if 0
// Actually, it turns out 2.6.18 doesn't seem to guarantee the order either
// so these broke again.
/// On length 3
// Deregistering signaled socket handle. Registering 'r'/'w' without number of
// bytes registers number of bytes as '-1' which will fail when 'Dn' is called,
// unless the event is deregistered before it happens.
{ L_, 0, "+0r64,{-1}; +1r; +2r64; W0,64; W1,64; W2,64; T3; Dn,2; T2;"
"E0r; E1; E2r" },
{ L_, 0, "+0r64,{-2}; +1r64; +2r; W0,64; W1,64; W2,64; T3; Dn,2; T2;"
"E0r; E1r; E2" },
{ L_, 0, "+0r64; +1r64,{-0}; +2r64; W0,64; W1,64; W2,64; T3; Dn,3; T2;"
"E0; E1r; E2r" },
{ L_, 0, "+0r64; +1r64, {-2}; +2r; W0,64; W1,64; W2,64; T3; Dn,2; T2;"
"E0r; E1r; E2" },
#endif
#endif
// Deregistering non-signaled socket handle
//-------------->
};
const int NUM_SCRIPTS = sizeof SCRIPTS / sizeof *SCRIPTS;
for (int i = 0; i < NUM_SCRIPTS; ++i) {
Obj mX(&timeMetric, &testAllocator);
const int LINE = SCRIPTS[i].d_line;
enum { NUM_PAIRS = 4 };
btlso::EventManagerTestPair socketPairs[NUM_PAIRS];
for (int j = 0; j < NUM_PAIRS; j++) {
socketPairs[j].setObservedBufferOptions(BUF_LEN, 1);
socketPairs[j].setControlBufferOptions(BUF_LEN, 1);
}
int fails = btlso::EventManagerTester::gg(&mX,
socketPairs,
SCRIPTS[i].d_script,
controlFlag);
LOOP_ASSERT(LINE, SCRIPTS[i].d_fails == fails);
}
}
} break;
case 8: {
// ------i-------------------------------------------------------------
// TESTING 'dispatch' METHOD
// The goal is to ensure that 'dispatch' invokes the callback
// method for the write socket handle and event, for all possible
// events.
//
// Plan:
// Standard test:
// Create an object of the event manager under test, call the
// corresponding test function of 'btlso::EventManagerTester', where
// multiple socket pairs are created to test the dispatch() in
// this event manager.
// Customized test:
// Create an object of the event manager under test and a list
// of test scripts based on the script grammar defined in
// 'btlso::EventManagerTester', call the script interpreting function
// gg() of 'btlso::EventManagerTester' to execute the test data.
// Exhausting test:
// Test the "timeout" from the dispatch() with the loop-driven
// implementation where timeout value are generated during each
// iteration and invoke the dispatch() with it.
// Testing:
// int dispatch();
// int dispatch(const bsls::TimeInterval&, ...);
// --------------------------------------------------------------------
if (verbose) cout << endl << "TESTING 'dispatch'" << endl
<< "==================" << endl;
if (verbose)
cout << "\tStandard test for 'dispatch'" << endl;
{
Obj mX(&timeMetric, &testAllocator);
int notFailed = !btlso::EventManagerTester::testDispatch(
&mX,
controlFlag);
ASSERT("BLACK-BOX (standard) TEST FAILED" && notFailed);
}
if (verbose)
cout << "\tCustom test for 'dispatch'" << endl;
{
struct {
int d_line;
int d_fails; // number of failures in this script
const char *d_script;
} SCRIPTS[] =
{
{L_, 0, "Dn0,0" },
{L_, 0, "Dn100,0" },
{L_, 0, "+0w2; Dn,1" },
{L_, 0, "+0w40; +0r3; Dn0,1; W0,30; Dn0,2" },
{L_, 0, "+0w40; +0r3; Dn100,1; W0,30; Dn120,2" },
{L_, 0, "+0w20; +0r12; Dn,1; W0,30; +1w6; +2w8; Dn,4" },
{L_, 0, "+0w40; +1r6; +1w41; +2w42; +3w43; +0r12; W3,30;"
"Dn,4; W0,30; +1r6; W1,30; +2r8; W2,30; +3r10; Dn,8" },
{L_, 0, "+2r3; Dn100,0; +2w40; Dn50,1; W2,30; Dn55,2" },
{L_, 0, "+0w20; +0r12; Dn0,1; W0,30; +1w6; +2w8; Dn100,4" },
{L_, 0, "+0w40; +1r6; +1w41; +2w42; +3w43; +0r12; Dn100,4;"
"W0,60; W1,70; +1r6; W2,60; W3,60; +2r8; +3r10;"
"Dn120,8" },
};
const int NUM_SCRIPTS = sizeof SCRIPTS / sizeof *SCRIPTS;
for (int i = 0; i < NUM_SCRIPTS; ++i) {
Obj mX(&timeMetric, &testAllocator);
const int LINE = SCRIPTS[i].d_line;
btlso::EventManagerTestPair socketPairs[4];
const int NUM_PAIR = sizeof socketPairs /sizeof socketPairs[0];
for (int j = 0; j < NUM_PAIR; j++) {
socketPairs[j].setObservedBufferOptions(BUF_LEN, 1);
socketPairs[j].setControlBufferOptions(BUF_LEN, 1);
}
int fails = btlso::EventManagerTester::gg(&mX,
socketPairs,
SCRIPTS[i].d_script,
controlFlag);
LOOP_ASSERT(LINE, SCRIPTS[i].d_fails == fails);
if (veryVerbose) {
P_(LINE); P(fails);
}
}
}
if (verbose)
cout << "\tVerifying behavior on timeout (no sockets)." << endl;
{
const int NUM_ATTEMPTS = 50;
for (int i = 0; i < NUM_ATTEMPTS; ++i) {
Obj mX(&timeMetric, &testAllocator);
bsls::TimeInterval deadline = bdlt::CurrentTime::now();
deadline.addMilliseconds(i % 10);
deadline.addNanoseconds(i % 1000);
LOOP_ASSERT(i, 0 == mX.dispatch(
deadline,
btlso::Flag::k_ASYNC_INTERRUPT));
bsls::TimeInterval now = bdlt::CurrentTime::now();
LOOP_ASSERT(i, deadline <= now);
if (veryVeryVerbose) {
P_(deadline); P(now);
}
}
}
if (verbose)
cout << "\tVerifying behavior on timeout (at least one socket)."
<< endl;
{
btlso::EventManagerTestPair socketPair;
bsl::function<void()> nullFunctor;
const int NUM_ATTEMPTS = 50;
for (int i = 0; i < NUM_ATTEMPTS; ++i) {
Obj mX(&timeMetric, &testAllocator);
mX.registerSocketEvent(socketPair.observedFd(),
btlso::EventType::e_READ,
nullFunctor);
bsls::TimeInterval deadline = bdlt::CurrentTime::now();
deadline.addMilliseconds(i % 10);
deadline.addNanoseconds(i % 1000);
LOOP_ASSERT(i, 0 ==
mX.dispatch(deadline, btlso::Flag::k_ASYNC_INTERRUPT));
bsls::TimeInterval now = bdlt::CurrentTime::now();
LOOP3_ASSERT(deadline, now, i, deadline <= now);
if (veryVeryVerbose) {
P_(deadline); P(now);
}
}
}
} break;
case 7: {
// --------------------------------------------------------------------
// TESTING 'deregisterAll' METHODS
// It must be verified that the application of 'deregisterAll'
// from any state returns the event manager.
//
// Plan:
// Standard test:
// Create an object of the event manager under test, call the
// corresponding test function of 'btlso::EventManagerTester', where
// multiple socket pairs are created to test the deregisterAll() in
// this event manager.
// Customized test:
// No customized test since no difference in implementation
// between all event managers.
// Testing:
// void deregisterAll();
// --------------------------------------------------------------------
if (verbose) cout << endl << "TESTING 'deregisterAll'" << endl
<< "=======================" << endl;
if (verbose)
cout << "Standard test for 'deregisterAll'" << endl
<< "=================================" << endl;
{
Obj mX(&timeMetric, &testAllocator);
int fails = EventManagerTester::testDeregisterAll(&mX,
controlFlag);
ASSERT(0 == fails);
}
} break;
case 6: {
// --------------------------------------------------------------------
// TESTING 'deregisterSocket' METHOD
// All possible transitions from other state to 0 must be
// exhaustively tested.
//
// Plan:
// Standard test:
// Create an object of the event manager under test, call the
// corresponding test function of 'btlso::EventManagerTester', where
// multiple socket pairs are created to test the deregisterSocket()
// in this event manager.
// Customized test:
// Create a socket, register and then unregister more than the system
// limit for open files and then try to dispatch. This will make
// sure that the internal epoll buffer is consistent with the
// number of open files.
// Testing:
// int deregisterSocket();
// --------------------------------------------------------------------
if (verbose) cout << endl << "TESTING 'deregisterSocket'" << endl
<< "==========================" << endl;
{
Obj mX(&timeMetric, &testAllocator);
int fails = EventManagerTester::testDeregisterSocket(&mX,
controlFlag);
ASSERT(0 == fails);
}
{
enum { NUM_DEREGISTERS = 70000 };
Obj mX;
bsl::function<void()> cb(&assertCb);
for (int i = 0; i < NUM_DEREGISTERS; ++i) {
int fd = socket(PF_INET, SOCK_STREAM, 0);
BSLS_ASSERT_OPT(fd != -1);
mX.registerSocketEvent(fd, btlso::EventType::e_READ, cb);
mX.deregisterSocket(fd);
close(fd);
}
btlso::EventManagerTestPair socketPair;
mX.registerSocketEvent(socketPair.controlFd(),
btlso::EventType::e_READ, cb);
bsls::TimeInterval timeout = bdlt::CurrentTime::now();
timeout.addMilliseconds(200);
ASSERT(0 == mX.dispatch(timeout, 0));
}
} break;
case 5: {
// --------------------------------------------------------------------
// TESTING 'deregisterSocketEvent' METHOD
// All possible deregistration transitions must be exhaustively
// tested.
//
// Plan:
// Standard test:
// Create an object of the event manager under test, call the
// corresponding test function of 'btlso::EventManagerTester', where
// multiple socket pairs are created to test the
// deregisterSocketEvent() in this event manager.
// Customized test:
// Create a socket, register and then unregister more than the system
// limit for open files and then try to dispatch. This will make
// sure that the internal epoll buffer is consistent with the
// number of open files.
// Testing:
// void deregisterSocketEvent();
// --------------------------------------------------------------------
if (verbose) cout << endl << "TESTING 'deregisterSocketEvent'" << endl
<< "===============================" << endl;
if (verbose)
cout << "Standard test for 'deregisterSocketEvent'" << endl
<< "=========================================" << endl;
{
Obj mX(&timeMetric, &testAllocator);
int fails = EventManagerTester::testDeregisterSocketEvent(
&mX,
controlFlag);
ASSERT(0 == fails);
}
if (verbose)
cout << "Customized test for 'deregisterSocketEvent'" << endl
<< "===========================================" << endl;
{
struct {
int d_line;
int d_fails; // number of failures in this script
const char *d_script;
} SCRIPTS[] =
{
{L_, 0, "+0w; -0w; T0" },
{L_, 0, "+0w; +0r; -0w; E0r; T1"},
{L_, 0, "+0w; +1r; -0w; E1r; T1"},
{L_, 0, "+0w; +1r; -1r; E0w; T1"},
};
const int NUM_SCRIPTS = sizeof SCRIPTS / sizeof *SCRIPTS;
for (int i = 0; i < NUM_SCRIPTS; ++i) {
Obj mX(&timeMetric, &testAllocator);
const int LINE = SCRIPTS[i].d_line;
btlso::EventManagerTestPair socketPairs[4];
const int NUM_PAIR = sizeof socketPairs /sizeof socketPairs[0];
for (int j = 0; j < NUM_PAIR; j++) {
socketPairs[j].setObservedBufferOptions(BUF_LEN, 1);
socketPairs[j].setControlBufferOptions(BUF_LEN, 1);
}
int fails = btlso::EventManagerTester::gg(&mX,
socketPairs,
SCRIPTS[i].d_script,
controlFlag);
LOOP_ASSERT(LINE, SCRIPTS[i].d_fails == fails);
if (veryVerbose) {
P_(LINE); P(fails);
}
}
}
{
enum { NUM_DEREGISTERS = 70000 };
Obj mX;
bsl::function<void()> cb(&assertCb);
for (int i = 0; i < NUM_DEREGISTERS; ++i) {
int fd = socket(PF_INET, SOCK_STREAM, 0);
BSLS_ASSERT_OPT(fd != -1);
mX.registerSocketEvent(fd, btlso::EventType::e_READ, cb);
mX.deregisterSocketEvent(fd, btlso::EventType::e_READ);
close(fd);
}
btlso::EventManagerTestPair socketPair;
mX.registerSocketEvent(socketPair.observedFd(),
btlso::EventType::e_READ, cb);
bsls::TimeInterval timeout = bdlt::CurrentTime::now();
timeout.addMilliseconds(200);
ASSERT(0 == mX.dispatch(timeout, 0));
}
} break;
case 4: {
// --------------------------------------------------------------------
// TESTING 'registerSocketEvent' METHOD
// The main concern about this function is to ensure full coverage
// of the every legal event combination that can be registered for
// one and two sockets.
//
// Plan:
// Standard test:
// Create an object of the event manager under test, call the
// corresponding function of 'btlso::EventManagerTester', where a
// number of socket pairs are created to test the
// registerSocketEvent() in this event manager.
// Customized test:
// Create an object of the event manager under test and a list
// of test scripts based on the script grammar defined in
// 'btlso::EventManagerTester', call the script interpreting function
// gg() of 'btlso::EventManagerTester' to execute the test data.
// Testing:
// void registerSocketEvent();
// --------------------------------------------------------------------
if (verbose) cout << endl << "TESTING 'registerSocketEvent'" << endl
<< "=============================" << endl;
if (verbose)
cout << "Standard test for 'registerSocketEvent'" << endl
<< "=======================================" << endl;
{
Obj mX(&timeMetric, &testAllocator);
int fails = EventManagerTester::testRegisterSocketEvent(
&mX,
controlFlag);
ASSERT(0 == fails);
if (verbose) {
P(timeMetric.percentage(btlso::TimeMetrics::e_CPU_BOUND));
}
ASSERT(100 == timeMetric.percentage(
btlso::TimeMetrics::e_CPU_BOUND));
}
if (verbose)
cout << "Customized test for 'registerSocketEvent'" << endl
<< "=========================================" << endl;
{
struct {
int d_line;
int d_fails; // number of failures in this script
const char *d_script;
} SCRIPTS[] =
{
{L_, 0, "+0w; E0w; T1" },
{L_, 0, "+0r; E0r; T1" },
{L_, 0, "+0w; +0w; E0w; T1" },
{L_, 0, "+0r; +0r; E0r; T1" },
{L_, 0, "+0w; +0w; +0r; +0r; E0rw; T2" },
{L_, 0, "+0w; +1r; E0w; E1r; T2" },
{L_, 0, "+0w; +1r; +1w; +0r; E0rw; E1rw; T4"},
};
const int NUM_SCRIPTS = sizeof SCRIPTS / sizeof *SCRIPTS;
for (int i = 0; i < NUM_SCRIPTS; ++i) {
Obj mX(&timeMetric, &testAllocator);
const int LINE = SCRIPTS[i].d_line;
btlso::EventManagerTestPair socketPairs[4];
const int NUM_PAIR =
sizeof socketPairs / sizeof socketPairs[0];
for (int j = 0; j < NUM_PAIR; j++) {
socketPairs[j].setObservedBufferOptions(BUF_LEN, 1);
socketPairs[j].setControlBufferOptions(BUF_LEN, 1);
}
int fails = btlso::EventManagerTester::gg(&mX,
socketPairs,
SCRIPTS[i].d_script,
controlFlag);
LOOP_ASSERT(LINE, SCRIPTS[i].d_fails == fails);
if (veryVerbose) {
P_(LINE); P(fails);
}
}
if (verbose) {
P(timeMetric.percentage(btlso::TimeMetrics::e_CPU_BOUND));
}
ASSERT(100 == timeMetric.percentage(
btlso::TimeMetrics::e_CPU_BOUND));
}
} break;
case 3: {
// --------------------------------------------------------------------
// TESTING ACCESSORS
// The main concern about this function is to ensure full coverage
// of the every legal event combination that can be registered for
// one and two sockets.
//
// Plan:
// Standard test:
// Create an object of the event manager under test, call the
// corresponding function of 'btlso::EventManagerTester', where a
// number of socket pairs are created to test the accessors in
// this event manager.
// Customized test:
// No customized test since no difference in implementation
// between all event managers.
// Testing:
// int isRegistered();
// int numEvents() const;
// int numSocketEvents();
// --------------------------------------------------------------------
if (verbose) cout << endl << "TESTING ACCESSORS" << endl
<< "=================" << endl;
if (verbose) cout << "\tOn a non-metered object" << endl;
{
Obj mX((btlso::TimeMetrics*)0, &testAllocator);
int fails = EventManagerTester::testAccessors(&mX, controlFlag);
ASSERT(0 == fails);
}
if (verbose) cout << "\tOn a metered object" << endl;
{
Obj mX(&timeMetric, &testAllocator);
int fails = EventManagerTester::testAccessors(&mX, controlFlag);
ASSERT(0 == fails);
if (verbose) {
P(timeMetric.percentage(btlso::TimeMetrics::e_CPU_BOUND));
}
ASSERT(100 == timeMetric.percentage(
btlso::TimeMetrics::e_CPU_BOUND));
}
} break;
case 2: {
// --------------------------------------------------------------------
// TESTING PRIMARY MANIPULATORS
//
// Plan:
// Standard test:
// Create objects of the event manager under test and a list
// of test scripts based on the script grammar defined in
// 'btlso::EventManagerTester', call the script interpreting function
// gg() of 'btlso::EventManagerTester' to execute the test data.
// Testing:
// btlso::DefaultEventManager();
// ~btlso::DefaultEventManager();
// --------------------------------------------------------------------
if (verbose) cout << endl << "TESTING PRIMARY MANIPULATORS" << endl
<< "============================" << endl;
{
Obj mX[2];
const int NUM_OBJ = sizeof mX / sizeof mX[0];
for (int k = 0; k < NUM_OBJ; k++) {
struct {
int d_line;
int d_fails; // failures in this script
const char *d_script;
} SCRIPTS[] =
{
//------------------>
{ L_, 0, "+0r; E0r; T1; -0r; E0; T0" },
{ L_, 0, "+0w; E0w; T1; -0w; E0; T0" },
{ L_, 0, "+0w; +0w; E0w; T1; -0w; E0; T0" },
{ L_, 0, "+0r; +0r; E0r; T1; -0r; E0; T0" },
{ L_, 0, "+0r; +0w; E0rw; T2; -0r; -0w; E0; T0" },
{ L_, 0, "+0r; +1r; E0r; E1r; T2; -0r; -1r; E0; E1; T0" },
{ L_, 0, "+0r; +1r; +1w; E0r; E1wr; T3; -0r; -1r; -1w; E0; E1; T0" },
{ L_, 0, "+0r; +1r; +1w; +0w E0rw; E1wr; T4" },
//------------------>
};
const int NUM_SCRIPTS = sizeof SCRIPTS / sizeof *SCRIPTS;
for (int i = 0; i < NUM_SCRIPTS; ++i) {
const int LINE = SCRIPTS[i].d_line;
enum { NUM_PAIRS = 4 };
btlso::EventManagerTestPair socketPairs[NUM_PAIRS];
for (int j = 0; j < NUM_PAIRS; j++) {
socketPairs[i].setObservedBufferOptions(BUF_LEN, 1);
socketPairs[i].setControlBufferOptions(BUF_LEN, 1);
}
int fails = EventManagerTester::gg(&mX[k],
socketPairs,
SCRIPTS[i].d_script,
controlFlag);
LOOP_ASSERT(LINE, SCRIPTS[i].d_fails == fails);
if (veryVerbose) {
P_(LINE); P(fails);
}
}
}
}
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST
// Ensure the basic liveness of an event manager instance.
//
// Testing:
// Create an object of this event manager under test. Perform
// some basic operations on it.
// --------------------------------------------------------------------
if (verbose) cout << endl << "BREATHING TEST" << endl
<< "==============" << endl;
{
ASSERT(Obj::isSupported());
struct {
int d_line;
int d_fails; // number of failures in this script
const char *d_script;
} SCRIPTS[] =
{
{L_, 0, "Dn0,0" },
{L_, 0, "Dn100,0" },
{L_, 0, "+0w2; Dn,1" },
{L_, 0, "+0w40; +0r3; Dn0,1; W0,40; Dn0,2" },
{L_, 0, "+0w40; +0r3; Dn100,1; W0,40; Dn120,2" },
{L_, 0, "+0w20; +0r12; Dn,1; W0,30; +1w6; +2w8; Dn,4" },
{L_, 0, "+0w40; +1r6; +1w41; +2w42; +3w43; +0r12;"
"Dn,4; W0,40; +1r6; W1,40; W2,40; W3,40; +2r8;"
"+3r10; Dn,8" },
{L_, 0, "+2r3; Dn100,0; +2w40; Dn50,1; W2,40; Dn55,2" },
{L_, 0, "+0w20; +0r12; Dn0,1; +1w6; +2w8; W0,40; Dn100,4" },
{L_, 0, "+0w40; +1r6; +1w41; +2w42; +3w43; +0r12;"
"Dn100,4; W0,40; W1,40; W2,40; W3,40; +1r6; +2r8;"
"+3r10; Dn120,8" },
};
const int NUM_SCRIPTS = sizeof SCRIPTS / sizeof *SCRIPTS;
for (int i = 0; i < NUM_SCRIPTS; ++i) {
Obj mX((btlso::TimeMetrics*)0, &testAllocator);
const int LINE = SCRIPTS[i].d_line;
enum { NUM_PAIRS = 4 };
btlso::EventManagerTestPair socketPairs[NUM_PAIRS];
for (int j = 0; j < NUM_PAIRS; j++) {
socketPairs[j].setObservedBufferOptions(BUF_LEN, 1);
socketPairs[j].setControlBufferOptions(BUF_LEN, 1);
}
int fails = EventManagerTester::gg(&mX,
socketPairs,
SCRIPTS[i].d_script,
controlFlag);
LOOP_ASSERT(LINE, SCRIPTS[i].d_fails == fails);
if (veryVerbose) {
P_(LINE); P(fails);
}
}
}
} break;
case -1: {
// --------------------------------------------------------------------
// PERFORMANCE TESTING 'dispatch'
// Get the performance data.
//
// Plan:
// Set up a collection of socketPairs and register one end of all the
// pairs with the event manager. Write 1 byte to
// 'fracBusy * numSocketPairs' of the connections, and measure the
// average time taken to dispatch a read event for a given number of
// registered read event. If 'timeOut > 0' register a timeout
// interval with the 'dispatch' call. If 'R|N' is 'R', actually read
// the bytes in the dispatch, if it's 'N', just call a null function
// within the dispatch.
//
// Testing:
// 'dispatch' capacity
//
// See the compilation of results for all event managers & platforms
// at the beginning of 'btlso_eventmanagertester.t.cpp'.
// --------------------------------------------------------------------
if (verbose) cout << "PERFORMANCE TESTING 'dispatch'\n"
"==============================\n";
{
Obj mX(&timeMetric, &testAllocator);
btlso::EventManagerTester::testDispatchPerformance(&mX,
"epoll",
controlFlag);
}
} break;
case -2: {
// --------------------------------------------------------------------
// TESTING PERFORMANCE 'registerSocketEvent' METHOD
// Get performance data.
//
// Plan:
// Open multiple sockets and register a read event for each
// socket, calculate the average time taken to register a read
// event for a given number of registered read event.
//
// Testing:
// Obj::registerSocketEvent
//
// See the compilation of results for all event managers & platforms
// at the beginning of 'btlso_eventmanagertester.t.cpp'.
// --------------------------------------------------------------------
if (verbose) cout << "PERFORMANCE TESTING 'registerSocketEvent'\n"
"=========================================\n";
Obj mX(&timeMetric, &testAllocator);
btlso::EventManagerTester::testRegisterPerformance(&mX, controlFlag);
} break;
default: {
cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
testStatus = -1;
} break;
}
btlso::SocketImpUtil::cleanup();
if (testStatus > 0) {
cerr << "Error, non-zero test status = " << testStatus << "." << endl;
}
return testStatus;
#else
return -1;
#endif // BTESO_EVENTMANAGERIMP_ENABLETEST
}
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| [
"abeels@bloomberg.net"
] | abeels@bloomberg.net |
94ee8ca033175ab009b83f66d6900569a880e8fa | b885748c915658d167317b37928c5fef3d27441d | /framework/volume_loader_raw.cpp | fe312da5c210c67d5e19c7e3e7d4d1c968339ac9 | [] | no_license | xaf-cv/AnSciVis | 9eaf7bfc86ba5d8f0df4e3c671f6bb39e6dff59c | 24bd1b2899d8083407c9f4336a8909b54c953949 | refs/heads/master | 2021-06-25T05:36:53.015626 | 2017-09-08T14:53:31 | 2017-09-08T14:53:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,675 | cpp | #include "volume_loader_raw.hpp"
#include <fstream>
#include <iostream>
volume_data_type Volume_loader_raw::load_volume(std::string filepath)
{
std::ifstream volume_file;
volume_file.open(filepath, std::ios::in | std::ios::binary);
volume_data_type data;
if(volume_file.is_open())
{
glm::ivec3 vol_dim = get_dimensions(filepath);
unsigned channels = get_channel_count(filepath);
unsigned byte_per_channel = get_bit_per_channel(filepath) / 8;
size_t data_size = vol_dim.x * vol_dim.y * vol_dim.z * channels * byte_per_channel;
data.resize(data_size);
volume_file.seekg(0, std::ios::beg);
volume_file.read((char *)&data.front(), data_size);
volume_file.close();
// std::cout << "File " << filepath << " successfully loaded" << std::endl;
return data;
}
else
{
std::cerr << "File " << filepath << " doesnt exist! Check Filepath!" << std::endl;
assert(0);
return data;
}
// never reached
assert(0);
return data;
}
glm::ivec3 Volume_loader_raw::get_dimensions(const std::string filepath) const
{
unsigned width = 0;
unsigned height = 0;
unsigned depth = 0;
//"name_wxx_hxx_dxx_cx_bx"
size_t p0 = 0, p1 = std::string::npos;
p0 = filepath.find("_w", 0) + 2;
p1 = filepath.find("_h", 0);
if(p1 != p0)
{
std::string token = filepath.substr(p0, p1 - p0);
width = std::atoi(token.c_str());
}
p0 = filepath.find("_h", p0) + 2;
p1 = filepath.find("_d", p0);
if(p1 != p0)
{
std::string token = filepath.substr(p0, p1 - p0);
height = std::atoi(token.c_str());
}
p0 = filepath.find("_d", p0) + 2;
p1 = filepath.find("_c", p0);
if(p1 != p0)
{
std::string token = filepath.substr(p0, p1 - p0);
depth = std::atoi(token.c_str());
}
return glm::ivec3(width, height, depth);
}
unsigned Volume_loader_raw::get_channel_count(const std::string filepath) const
{
unsigned channels = 0;
size_t p0 = 0, p1 = std::string::npos;
p0 = filepath.find("_c", 0) + 2;
p1 = filepath.find("_b", p0);
std::string token = filepath.substr(p0, p1 - p0);
channels = std::atoi(token.c_str());
return channels;
}
unsigned Volume_loader_raw::get_bit_per_channel(const std::string filepath) const
{
unsigned byte_per_channel = 0;
size_t p0 = 0, p1 = std::string::npos;
p0 = filepath.find("_b", 0) + 2;
p1 = filepath.find(".", p0);
std::string token = filepath.substr(p0, p1 - p0);
byte_per_channel = std::atoi(token.c_str());
return byte_per_channel;
}
| [
"antonf.vit@gmail.com"
] | antonf.vit@gmail.com |
c4495d62f7c042f05cd2c861b26d52ea95e108f1 | a3effde3c27c072090f0021bdae3306961eb2d92 | /Codeforces/1285/B.cpp | 50eb8a951970102a9ab9a56c96099be9cd2acd8d | [] | no_license | anmolgup/Competitive-programming-code | f4837522bf648c90847d971481f830a47722da29 | 329101c4e45be68192715c9a0718f148e541b58b | refs/heads/master | 2022-12-03T19:00:40.261727 | 2020-08-08T09:21:58 | 2020-08-08T09:21:58 | 286,011,774 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,746 | cpp | #include<bits/stdc++.h>
using namespace std;
//Optimisations
#pragma GCC target ("avx2")
#pragma GCC optimization ("unroll-loops")
#pragma GCC optimize("O2")
//shortcuts for functions
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define endl "\n"
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define th(n) cout<<n<<endl
#define gc getchar_unlocked
#define ms(s, n) memset(s, n, sizeof(s))
#define prec(n) fixed<<setprecision(n)
#define n_l '\n'
// make it python
#define gcd __gcd
#define append push_back
#define str to_string
#define stringtoll stoll
#define upper(s) transform(s.begin(),s.end(),s.begin(),::toupper)
#define lower(s) transform(s.begin(),s.end(),s.begin(),::tolower)
#define print(arr) for(auto el: arr) cout<<el<<" ";cout<<endl
// utility functions shortcuts
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define sswap(a,b) {a=a^b;b=a^b;a=a^b;}
#define swap(a,b) {auto temp=a; a=b; b=temp;}
#define set0(dp) memset(dp,0,sizeof(dp));
#define bits(x) __builtin_popcount(x)
#define SORT(v) sort(all(v))
#define endl "\n"
#define forr(i,n) for(ll i=0;i<n;i++)
#define formatrix(i,n) for(ll i=0;i<n;i++, cout<<"\n")
#define eof (scanf("%d" ,&n))!=EOF
// declaration shortcuts
#define vll vector<ll>
#define vvl vector<vector<ll>>
#define vpll vector<pair<ll,ll> >
#define pll pair<ll,ll>
#define ppl pair<ll,pll>
#define ull unsigned long long
#define ll long long
#define mll map< ll, ll >
#define sll set< ll >
#define uni(v) v.erase(unique(v.begin(),v.end()),v.end());
#define ini(a, v) memset(a, v, sizeof(a))
// Constants
constexpr int dx[] = {-1, 0, 1, 0, 1, 1, -1, -1};
constexpr int dy[] = {0, -1, 0, 1, 1, -1, 1, -1};
constexpr ll INF = 1999999999999999997;
constexpr int inf= INT_MAX;
constexpr int MAXSIZE = int(1e6)+5;
constexpr auto PI = 3.14159265358979323846L;
constexpr auto oo = numeric_limits<int>::max() / 2 - 2;
constexpr auto eps = 1e-6;
constexpr auto mod = 1000000007;
constexpr auto MOD = 1000000007;
constexpr auto MOD9 = 1000000009;
constexpr auto maxn = 200006;
// Debugging
// For reference: https://codeforces.com/blog/entry/65311
#define dbg(...) cout << "[" << #__VA_ARGS__ << "]: "; cout << to_string(__VA_ARGS__) << endl
template <typename T, size_t N> int SIZE(const T (&t)[N]){ return N; } template<typename T> int SIZE(const T &t){ return t.size(); } string to_string(string s, int x1=0, int x2=1e9){ return '"' + ((x1 < s.size()) ? s.substr(x1, x2-x1+1) : "") + '"'; } string to_string(const char* s) { return to_string((string) s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(char c){ return string({c}); } template<size_t N> string to_string(bitset<N> &b, int x1=0, int x2=1e9){ string t = ""; for(int __iii__ = min(x1,SIZE(b)), __jjj__ = min(x2, SIZE(b)-1); __iii__ <= __jjj__; ++__iii__){ t += b[__iii__] + '0'; } return '"' + t + '"'; } template <typename A, typename... C> string to_string(A (&v), int x1=0, int x2=1e9, C... coords); int l_v_l_v_l = 0, t_a_b_s = 0; template <typename A, typename B> string to_string(pair<A, B> &p) { l_v_l_v_l++; string res = "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; l_v_l_v_l--; return res; } template <typename A, typename... C> string to_string(A (&v), int x1, int x2, C... coords) { int rnk = rank<A>::value; string tab(t_a_b_s, ' '); string res = ""; bool first = true; if(l_v_l_v_l == 0) res += n_l; res += tab + "["; x1 = min(x1, SIZE(v)), x2 = min(x2, SIZE(v)); auto l = begin(v); advance(l, x1); auto r = l; advance(r, (x2-x1) + (x2 < SIZE(v))); for (auto e = l; e != r; e = next(e)) { if (!first) { res += ", "; } first = false; l_v_l_v_l++; if(e != l){ if(rnk > 1) { res += n_l; t_a_b_s = l_v_l_v_l; }; } else{ t_a_b_s = 0; } res += to_string(*e, coords...); l_v_l_v_l--; } res += "]"; if(l_v_l_v_l == 0) res += n_l; return res; } void dbgs(){;} template<typename Heads, typename... Tails> void dbgs(Heads H, Tails... T){ cout << to_string(H) << " | "; dbgs(T...); }
#define dbgm(...) cout << "[" << #__VA_ARGS__ << "]: "; dbgs(__VA_ARGS__); cout << endl;
#define n_l '\n'
ll maxSubArraySum(ll a[], ll size)
{
ll max_so_far = a[0];
ll curr_max = a[0];
// debug(a[0]);
for (ll i = 1; i < size; i++)
{
curr_max = max(a[i], curr_max+a[i]);
max_so_far = max(max_so_far, curr_max);
}
return max_so_far;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll t;
cin >> t;
while(t--)
{
ll n;
cin >> n;
ll tot = 0;
ll v[n + 1];
forr(i,n){
cin >> v[i];
tot += v[i];
}
ll max_sum = max(maxSubArraySum(v,n - 1),maxSubArraySum(v + 1,n - 1));
if(max_sum < tot)
cout<<"YES\n";
else
cout<<"NO\n";
}
} | [
"anmolgupta9557@gmail.com"
] | anmolgupta9557@gmail.com |
0a4322c40e046b94356fde9e836bb40a459f833d | b8a473d5dd86d4839b17f5ec67430f8e1c2f7ac0 | /StdAfx.h | 4728f18eadb841c6c75be27c5a875c7f7bd5329d | [] | no_license | huyixi95/PowerfulClient | 60fa5f29d352ac5c3486942cb3dd107839d5d781 | 57ab8fb628a12e44e131b80f93456a3897b121ba | refs/heads/master | 2023-07-06T19:31:01.984981 | 2021-08-11T15:49:43 | 2021-08-11T15:49:43 | 394,892,286 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | h |
#if !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_)
#define AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_
#pragma once
//#define WIN32_LEAN_AND_MEAN
#define _CRT_SECURE_NO_DEPRECATE
#include <windows.h>
#include <objbase.h>
#include <zmouse.h>
#include "DuiLibHeaders\UIlib.h"
using namespace DuiLib;
#ifdef _DEBUG
# ifdef _UNICODE
# pragma comment(lib, "DuiLib_d.lib")
# else
# pragma comment(lib, "DuiLibLibs\\DuiLibA_d.lib")
# endif
#else
# ifdef _UNICODE
# pragma comment(lib, "DuiLibLibs\\DuiLib.lib")
# else
# pragma comment(lib, "DuiLibLibs\\DuiLibA.lib")
# endif
#endif
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_)
| [
"wb-hyx706096@alibaba-inc.c"
] | wb-hyx706096@alibaba-inc.c |
3ee3aa34de782cd94412eb49c0d2ed3770f8cbd8 | 2057737709101c527e6b76991b71e0e70b8b5582 | /basics/references.cpp | be494610a6b944c99254669dc5c2556ce2883152 | [] | no_license | Prkizir/c-dev | 76851ba7e0c47bddee88858f9b9556617e8d3840 | 9795b41eeb554e33fc0eaffcf94fdad1bb22b3a4 | refs/heads/master | 2023-06-05T16:23:13.101297 | 2021-06-22T05:00:11 | 2021-06-22T05:00:11 | 369,870,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | cpp | #include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
/*
* Section 1
*/
//
// int a = 10;
// int &r = a; // Reference must be initialised when declared
// // "r" becomes an alias of "a"
//
// cout << a << endl; // 10
// r++;
// cout << r << endl; // 11
// cout << a << endl; // 11
// Reference used in Parameter Passing (used instead of pointers)
/*
* References Practice
*/
int a = 10;
int &r = a; // Immutable
// int b = 20;
// r = b; // Not initialisation (cannot change reference),
// instead, "a" becomes 20
// cout << a << endl;
a = 25;
cout << a << endl << r << endl;
return 0;
}
| [
"mercado.sergio.382@gmail.com"
] | mercado.sergio.382@gmail.com |
b655f0db7ae3d2a5dbd8eca2983be012caf0e8b8 | 5a32832b598a2506e042b7d8635b2657654c7e98 | /src/qt/guiutil.cpp | 01e37c3dc1b8180a74458b3d6fc816e97770c4c8 | [
"MIT"
] | permissive | sdcoin/consumption | 0798a5dfbe5dce61d587acd2184e0199e02be091 | 81afd4e49b2a9730f74f13cf64352e9e0b9fb926 | refs/heads/master | 2021-01-20T13:13:20.522351 | 2017-08-29T08:44:04 | 2017-08-29T08:44:04 | 101,739,443 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,250 | cpp | #include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#if BOOST_FILESYSTEM_VERSION >= 3
#include <boost/filesystem/detail/utf8_codecvt_facet.hpp>
#endif
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
#if BOOST_FILESYSTEM_VERSION >= 3
static boost::filesystem::detail::utf8_codecvt_facet utf8;
#endif
namespace GUIUtil {
#if BOOST_FILESYSTEM_VERSION >= 3
boost::filesystem::path qstringToBoostPath(const QString &path)
{
return boost::filesystem::path(path.toStdString(), utf8);
}
QString boostPathToQString(const boost::filesystem::path &path)
{
return QString::fromStdString(path.string(utf8));
}
#else
#warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older
boost::filesystem::path qstringToBoostPath(const QString &path)
{
return boost::filesystem::path(path.toStdString());
}
QString boostPathToQString(const boost::filesystem::path &path)
{
return QString::fromStdString(path.string());
}
#endif
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "ConsumptionBlockChain.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "ConsumptionBlockChain.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=ConsumptionBlockChain\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("ConsumptionBlockChain-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" ConsumptionBlockChain-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("ConsumptionBlockChain-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
| [
"sdcion@163.com"
] | sdcion@163.com |
7ae1a6cf76548884373f5cfd143b520eab625b4d | 4dbaea97b6b6ba4f94f8996b60734888b163f69a | /LeetCode/81.cpp | 2c291725a2a751d7b249f0fc499fda512cbccbd5 | [] | no_license | Ph0en1xGSeek/ACM | 099954dedfccd6e87767acb5d39780d04932fc63 | b6730843ab0455ac72b857c0dff1094df0ae40f5 | refs/heads/master | 2022-10-25T09:15:41.614817 | 2022-10-04T12:17:11 | 2022-10-04T12:17:11 | 63,936,497 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | cpp | class Solution {
public:
bool search(vector<int>& nums, int target) {
if(nums.size() == 0){
return false;
}
int left = 0, right = nums.size() - 1;
while(left <= right){
int mid = (left + right) >> 1;
if(nums[mid] == target) {
return true;
}else if(nums[mid] == nums[left]){
left++;
continue;
}else if(nums[mid] > nums[left]){
if(nums[left] <= target && target < nums[mid]){
right = mid - 1;
}else{
left = mid + 1;
}
}else{
if(nums[right] >= target && nums[mid] < target){
left = mid + 1;
}else{
right = mid - 1;
}
}
}
return false;
}
}; | [
"54panguosheng@gmail.com"
] | 54panguosheng@gmail.com |
875782d535ed5caf254077f0986ae164e676dae8 | 1dc9449da8c131431c168998119141ca4c5b0c4b | /config.h | cc5fba1e12bd7be8500199bc8da720873277fc7c | [] | no_license | k7jto/kismet | f06dc21ed5138ded9c6c8098d0e4943330e580c9 | 751b09291e7ddc42e60f137c513e079b75d186cf | refs/heads/master | 2020-05-18T12:53:54.595681 | 2014-12-29T15:55:44 | 2014-12-29T15:55:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,780 | h | /* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.in by autoheader. */
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* system binary directory */
#define BIN_LOC "/usr/local/bin"
/* system data directory */
#define DATA_LOC "/usr/local/share"
/* libairpcap header */
/* #undef HAVE_AIRPCAP_H */
/* BSD radiotap packet headers */
/* #undef HAVE_BSD_SYS_RADIOTAP */
/* kernel capability support */
/* #undef HAVE_CAPABILITY */
/* Define to 1 if you have the <errno.h> header file. */
#define HAVE_ERRNO_H 1
/* Define to 1 if you have the <getopt.h> header file. */
#define HAVE_GETOPT_H 1
/* system defines getopt_long */
#define HAVE_GETOPT_LONG 1
/* Define to 1 if you have the `gettimeofday' function. */
#define HAVE_GETTIMEOFDAY 1
/* GPS support will be built. */
#define HAVE_GPS 1
/* inttypes.h is present */
#define HAVE_INTTYPES_H 1
/* libairpcap win32 control lib */
/* #undef HAVE_LIBAIRPCAP */
/* Define to 1 if you have the `cap' library (-lcap). */
/* #undef HAVE_LIBCAP */
/* Curses terminal lib */
/* #undef HAVE_LIBCURSES */
/* NCurses terminal lib */
#define HAVE_LIBNCURSES 1
/* libnl netlink library */
#define HAVE_LIBNL 1
/* libnl-2.0 netlink library */
/* #undef HAVE_LIBNL20 */
/* libnl-3.0 netlink library */
/* #undef HAVE_LIBNL30 */
/* Panel terminal lib */
#define HAVE_LIBPANEL 1
/* libpcap packet capture lib */
#define HAVE_LIBPCAP 1
/* libpcre regex support */
/* #undef HAVE_LIBPCRE */
/* Define to 1 if you have the <libutil.h> header file. */
/* #undef HAVE_LIBUTIL_H */
/* Linux wireless iwfreq.flag */
#define HAVE_LINUX_IWFREQFLAG 1
/* Netlink works */
#define HAVE_LINUX_NETLINK 1
/* Linux wireless extentions present */
#define HAVE_LINUX_WIRELESS 1
/* local radiotap packet headers */
#define HAVE_LOCAL_RADIOTAP 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the <netdb.h> header file. */
#define HAVE_NETDB_H 1
/* pcap/pcap.h */
/* #undef HAVE_PCAPPCAP_H */
/* pcapfileno-capable libwpcap */
/* #undef HAVE_PCAP_FILENO */
/* Selectablefd-capable libpcap */
#define HAVE_PCAP_GETSELFD 1
/* libpcap header */
#define HAVE_PCAP_H 1
/* Nonblocking-capable libpcap */
#define HAVE_PCAP_NONBLOCK 1
/* libpcap supports PPI */
#define HAVE_PPI 1
/* Define to 1 if you have the `pstat' function. */
/* #undef HAVE_PSTAT */
/* Define to 1 if you have the `select' function. */
#define HAVE_SELECT 1
/* Define to 1 if you have the `setproctitle' function. */
/* #undef HAVE_SETPROCTITLE */
/* Define to 1 if you have the `socket' function. */
#define HAVE_SOCKET 1
/* accept() takes type socklen_t for addrlen */
#define HAVE_SOCKLEN_T 1
/* Define to 1 if `stat' has the bug that it succeeds when given the
zero-length file name argument. */
/* #undef HAVE_STAT_EMPTY_STRING_BUG */
/* stdint.h is present */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the `strcasecmp' function. */
#define HAVE_STRCASECMP 1
/* Define to 1 if you have the `strftime' function. */
#define HAVE_STRFTIME 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strstr' function. */
#define HAVE_STRSTR 1
/* System headers are there */
#define HAVE_SYSHEADERS 1
/* Define to 1 if you have the <sys/pstat.h> header file. */
/* #undef HAVE_SYS_PSTAT_H */
/* Define to 1 if you have the <sys/socket.h> header file. */
#define HAVE_SYS_SOCKET_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <sys/wait.h> header file. */
#define HAVE_SYS_WAIT_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if you have the <Win32-Extensions.h> header file. */
/* #undef HAVE_WIN32_EXTENSIONS_H */
/* Define to 1 if you have the <windows.h> header file. */
/* #undef HAVE_WINDOWS_H */
/* __PROGNAME glibc macro available */
#define HAVE___PROGNAME 1
/* system library directory */
#define LIB_LOC "/usr/local/lib"
/* system state directory */
#define LOCALSTATE_DIR "/usr/local/var"
/* Define to 1 if `lstat' dereferences a symlink specified with a trailing
slash. */
#define LSTAT_FOLLOWS_SLASHED_SYMLINK 1
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT ""
/* Define to the full name of this package. */
#define PACKAGE_NAME ""
/* Define to the full name and version of this package. */
#define PACKAGE_STRING ""
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME ""
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION ""
/* writeable argv type */
#define PF_ARGV_TYPE PF_ARGV_WRITEABLE
/* Define as the return type of signal handlers (`int' or `void'). */
#define RETSIGTYPE void
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* system config directory */
#define SYSCONF_LOC "/usr/local/etc"
/* Compiling for Cygwin */
/* #undef SYS_CYGWIN */
/* Compiling for OSX/Darwin */
/* #undef SYS_DARWIN */
/* Compiling for FreeBSD */
/* #undef SYS_FREEBSD */
/* Compiling for Linux OS */
#define SYS_LINUX 1
/* Compiling for NetBSD */
/* #undef SYS_NETBSD */
/* Compiling for OpenBSD */
/* #undef SYS_OPENBSD */
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#define TIME_WITH_SYS_TIME 1
/* Define to 1 if your <sys/time.h> declares `struct tm'. */
/* #undef TM_IN_SYS_TIME */
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Enable large inode numbers on Mac OS X 10.5. */
#ifndef _DARWIN_USE_64_BIT_INODE
# define _DARWIN_USE_64_BIT_INODE 1
#endif
/* Number of bits in a file offset, on hosts where this is settable. */
/* #undef _FILE_OFFSET_BITS */
/* Define for large files, on AIX-style hosts. */
/* #undef _LARGE_FILES */
/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */
/* proftpd argv stuff */
#define PF_ARGV_NONE 0
#define PF_ARGV_NEW 1
#define PF_ARGV_WRITEABLE 2
#define PF_ARGV_PSTAT 3
#define PF_ARGV_PSSTRINGS 4
/* Maximum number of characters in the status line */
#define STATUS_MAX 1024
/* Maximum number of channels - I've only ever heard of 14 being used. */
#define CHANNEL_MAX 14
/* Stupid ncurses */
#define NCURSES_NOMACROS
/* Number of hex pairs in a key */
#define WEPKEY_MAX 32
/* String length of a key */
#define WEPKEYSTR_MAX ((WEPKEY_MAX * 2) + WEPKEY_MAX)
/* Number of past alerts to queue for new clients */
#define ALERT_BACKLOG 50
/* system min isn't reliable */
#define kismin(x,y) ((x) < (y) ? (x) : (y))
#define kismax(x,y) ((x) > (y) ? (x) : (y))
// Timer slices per second
#define SERVER_TIMESLICES_SEC 10
// Max chars in SSID
#define MAX_SSID_LEN 255
/* Namespace (on non-obj-c files) */
#ifndef __IN_OBJC_FILE__
using namespace std;
#define __STL_USE_NAMESPACES
#endif
#ifndef _
#define _(x) x
#endif
| [
"k7jto_john@gmail.com"
] | k7jto_john@gmail.com |
c17bd507504cf617f1c42974ed993267472067b7 | 0c6bec29bbeea5c6a8d88514dd271fd1a5dc1745 | /MS5/Date.h | df6ca118b88541d869b52305218a1963993166d6 | [] | no_license | chevashiIP/OOP244 | 8f9b1be2f049451d19b829b3bd7828c3addd4daf | e8edfbf32691aefbcf7c125cd0d9dffd5e55fbcf | refs/heads/main | 2023-03-13T18:50:11.350329 | 2021-03-05T20:37:26 | 2021-03-05T20:37:26 | 344,265,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,325 | h | // Final Project Milestone 1
//
// Version 1.0
// Date
// Author
// Description
//
//
//
//
// Revision History
// -----------------------------------------------------------
// Name Date Reason
/////////////////////////////////////////////////////////////////
#ifndef AMA_DATE_H
#define AMA_DATE_H
#include <iostream>
namespace AMA {
const int NO_ERROR = 0;
const int CIN_FAILED = 1;
const int YEAR_ERROR = 2;
const int MON_ERROR = 3;
const int DAY_ERROR = 4;
const int max_year = 2030;
const int min_year = 2000;
class Date {
int year;
int month;
int day;
int compValue() const;
int nowErrorCode;
int mdays(int mon, int year)const;
void errCode(int errorCode);
public:
Date();
Date(int, int, int);
void MakeEmpty();
bool operator==(const Date& rhs) const;
bool operator!=(const Date& rhs) const;
bool operator<(const Date& rhs) const;
bool operator>(const Date& rhs) const;
bool operator<=(const Date& rhs) const;
bool operator>=(const Date& rhs) const;
int errCode() const;
bool bad() const;
std::istream& read(std::istream& istr);
std::ostream& write(std::ostream& ostr) const;
};
std::ostream& operator << (std::ostream& ostr, const Date& d);
std::istream& operator >> (std::istream& istr, Date& d);
}
#endif | [
"32250543+SomeRandomDude456@users.noreply.github.com"
] | 32250543+SomeRandomDude456@users.noreply.github.com |
bb01241ed6b3eb97e52caf3e1a438b3b70b5971e | 9b8591c5f2a54cc74c73a30472f97909e35f2ecf | /source/QtDataVisualization/QCustom3DItemSlots.h | b4ce2a271eef51b8e7eb96a16a1dae92f6a1bb54 | [
"MIT"
] | permissive | tnsr1/Qt5xHb | d3a9396a6ad5047010acd5d8459688e6e07e49c2 | 04b6bd5d8fb08903621003fa5e9b61b831c36fb3 | refs/heads/master | 2021-05-17T11:15:52.567808 | 2020-03-26T06:52:17 | 2020-03-26T06:52:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,266 | h | /*
Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#ifndef QCUSTOM3DITEMSLOTS_H
#define QCUSTOM3DITEMSLOTS_H
#include <QtCore/QObject>
#include <QtCore/QCoreApplication>
#include <QtCore/QString>
#include <QtDataVisualization/QCustom3DItem>
#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_signals.h"
using namespace QtDataVisualization;
class QCustom3DItemSlots: public QObject
{
Q_OBJECT
public:
QCustom3DItemSlots(QObject *parent = 0);
~QCustom3DItemSlots();
public slots:
void meshFileChanged( const QString & meshFile );
void positionAbsoluteChanged( bool positionAbsolute );
void positionChanged( const QVector3D & position );
void rotationChanged( const QQuaternion & rotation );
void scalingAbsoluteChanged( bool scalingAbsolute );
void scalingChanged( const QVector3D & scaling );
void shadowCastingChanged( bool shadowCasting );
void textureFileChanged( const QString & textureFile );
void visibleChanged( bool visible );
};
#endif /* QCUSTOM3DITEMSLOTS_H */
| [
"5998677+marcosgambeta@users.noreply.github.com"
] | 5998677+marcosgambeta@users.noreply.github.com |
14930d92e456b0ec1b2b6ab1dee5b7f9f7ac0c18 | 697551aa9d680478d19faa52df1aaf42a51e3201 | /sdk/protobuf/include/google/protobuf/util/internal/testdata/books.pb.h | eff1a64b841ed79428137ec9705e2f2c6db370da | [] | no_license | siddhugit/dev_app | bf7505759b79c3a0d6b7132b424dbcb5d1434da3 | 7cb7d492c32b39783180c9d7257833043803ed52 | refs/heads/main | 2023-02-06T01:13:59.360675 | 2020-12-25T15:35:40 | 2020-12-25T15:35:40 | 308,992,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 361,659 | h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/util/internal/testdata/books.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3013000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3013000 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
#include "google/protobuf/util/internal/testdata/anys.pb.h"
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[16]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
namespace proto_util_converter {
namespace testing {
class Author;
class AuthorDefaultTypeInternal;
extern AuthorDefaultTypeInternal _Author_default_instance_;
class BadAuthor;
class BadAuthorDefaultTypeInternal;
extern BadAuthorDefaultTypeInternal _BadAuthor_default_instance_;
class BadNestedBook;
class BadNestedBookDefaultTypeInternal;
extern BadNestedBookDefaultTypeInternal _BadNestedBook_default_instance_;
class Book;
class BookDefaultTypeInternal;
extern BookDefaultTypeInternal _Book_default_instance_;
class Book_Data;
class Book_DataDefaultTypeInternal;
extern Book_DataDefaultTypeInternal _Book_Data_default_instance_;
class Book_Label;
class Book_LabelDefaultTypeInternal;
extern Book_LabelDefaultTypeInternal _Book_Label_default_instance_;
class Cyclic;
class CyclicDefaultTypeInternal;
extern CyclicDefaultTypeInternal _Cyclic_default_instance_;
class NestedBook;
class NestedBookDefaultTypeInternal;
extern NestedBookDefaultTypeInternal _NestedBook_default_instance_;
class PackedPrimitive;
class PackedPrimitiveDefaultTypeInternal;
extern PackedPrimitiveDefaultTypeInternal _PackedPrimitive_default_instance_;
class Primitive;
class PrimitiveDefaultTypeInternal;
extern PrimitiveDefaultTypeInternal _Primitive_default_instance_;
class Publisher;
class PublisherDefaultTypeInternal;
extern PublisherDefaultTypeInternal _Publisher_default_instance_;
class TestJsonName1;
class TestJsonName1DefaultTypeInternal;
extern TestJsonName1DefaultTypeInternal _TestJsonName1_default_instance_;
class TestJsonName2;
class TestJsonName2DefaultTypeInternal;
extern TestJsonName2DefaultTypeInternal _TestJsonName2_default_instance_;
class TestMessageFieldsWithSameJsonName;
class TestMessageFieldsWithSameJsonNameDefaultTypeInternal;
extern TestMessageFieldsWithSameJsonNameDefaultTypeInternal _TestMessageFieldsWithSameJsonName_default_instance_;
class TestPrimitiveFieldsWithSameJsonName;
class TestPrimitiveFieldsWithSameJsonNameDefaultTypeInternal;
extern TestPrimitiveFieldsWithSameJsonNameDefaultTypeInternal _TestPrimitiveFieldsWithSameJsonName_default_instance_;
class TestRepeatedFieldsWithSameJsonName;
class TestRepeatedFieldsWithSameJsonNameDefaultTypeInternal;
extern TestRepeatedFieldsWithSameJsonNameDefaultTypeInternal _TestRepeatedFieldsWithSameJsonName_default_instance_;
} // namespace testing
} // namespace proto_util_converter
PROTOBUF_NAMESPACE_OPEN
template<> ::proto_util_converter::testing::Author* Arena::CreateMaybeMessage<::proto_util_converter::testing::Author>(Arena*);
template<> ::proto_util_converter::testing::BadAuthor* Arena::CreateMaybeMessage<::proto_util_converter::testing::BadAuthor>(Arena*);
template<> ::proto_util_converter::testing::BadNestedBook* Arena::CreateMaybeMessage<::proto_util_converter::testing::BadNestedBook>(Arena*);
template<> ::proto_util_converter::testing::Book* Arena::CreateMaybeMessage<::proto_util_converter::testing::Book>(Arena*);
template<> ::proto_util_converter::testing::Book_Data* Arena::CreateMaybeMessage<::proto_util_converter::testing::Book_Data>(Arena*);
template<> ::proto_util_converter::testing::Book_Label* Arena::CreateMaybeMessage<::proto_util_converter::testing::Book_Label>(Arena*);
template<> ::proto_util_converter::testing::Cyclic* Arena::CreateMaybeMessage<::proto_util_converter::testing::Cyclic>(Arena*);
template<> ::proto_util_converter::testing::NestedBook* Arena::CreateMaybeMessage<::proto_util_converter::testing::NestedBook>(Arena*);
template<> ::proto_util_converter::testing::PackedPrimitive* Arena::CreateMaybeMessage<::proto_util_converter::testing::PackedPrimitive>(Arena*);
template<> ::proto_util_converter::testing::Primitive* Arena::CreateMaybeMessage<::proto_util_converter::testing::Primitive>(Arena*);
template<> ::proto_util_converter::testing::Publisher* Arena::CreateMaybeMessage<::proto_util_converter::testing::Publisher>(Arena*);
template<> ::proto_util_converter::testing::TestJsonName1* Arena::CreateMaybeMessage<::proto_util_converter::testing::TestJsonName1>(Arena*);
template<> ::proto_util_converter::testing::TestJsonName2* Arena::CreateMaybeMessage<::proto_util_converter::testing::TestJsonName2>(Arena*);
template<> ::proto_util_converter::testing::TestMessageFieldsWithSameJsonName* Arena::CreateMaybeMessage<::proto_util_converter::testing::TestMessageFieldsWithSameJsonName>(Arena*);
template<> ::proto_util_converter::testing::TestPrimitiveFieldsWithSameJsonName* Arena::CreateMaybeMessage<::proto_util_converter::testing::TestPrimitiveFieldsWithSameJsonName>(Arena*);
template<> ::proto_util_converter::testing::TestRepeatedFieldsWithSameJsonName* Arena::CreateMaybeMessage<::proto_util_converter::testing::TestRepeatedFieldsWithSameJsonName>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace proto_util_converter {
namespace testing {
enum Book_Type : int {
Book_Type_FICTION = 1,
Book_Type_KIDS = 2,
Book_Type_ACTION_AND_ADVENTURE = 3,
Book_Type_arts_and_photography = 4,
Book_Type_I18N_Tech = 5
};
bool Book_Type_IsValid(int value);
constexpr Book_Type Book_Type_Type_MIN = Book_Type_FICTION;
constexpr Book_Type Book_Type_Type_MAX = Book_Type_I18N_Tech;
constexpr int Book_Type_Type_ARRAYSIZE = Book_Type_Type_MAX + 1;
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Book_Type_descriptor();
template<typename T>
inline const std::string& Book_Type_Name(T enum_t_value) {
static_assert(::std::is_same<T, Book_Type>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function Book_Type_Name.");
return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum(
Book_Type_descriptor(), enum_t_value);
}
inline bool Book_Type_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Book_Type* value) {
return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<Book_Type>(
Book_Type_descriptor(), name, value);
}
// ===================================================================
class Book_Data PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.Book.Data) */ {
public:
inline Book_Data() : Book_Data(nullptr) {}
virtual ~Book_Data();
Book_Data(const Book_Data& from);
Book_Data(Book_Data&& from) noexcept
: Book_Data() {
*this = ::std::move(from);
}
inline Book_Data& operator=(const Book_Data& from) {
CopyFrom(from);
return *this;
}
inline Book_Data& operator=(Book_Data&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const Book_Data& default_instance();
static inline const Book_Data* internal_default_instance() {
return reinterpret_cast<const Book_Data*>(
&_Book_Data_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(Book_Data& a, Book_Data& b) {
a.Swap(&b);
}
inline void Swap(Book_Data* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(Book_Data* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline Book_Data* New() const final {
return CreateMaybeMessage<Book_Data>(nullptr);
}
Book_Data* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<Book_Data>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const Book_Data& from);
void MergeFrom(const Book_Data& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Book_Data* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.Book.Data";
}
protected:
explicit Book_Data(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kCopyrightFieldNumber = 8,
kYearFieldNumber = 7,
};
// optional string copyright = 8;
bool has_copyright() const;
private:
bool _internal_has_copyright() const;
public:
void clear_copyright();
const std::string& copyright() const;
void set_copyright(const std::string& value);
void set_copyright(std::string&& value);
void set_copyright(const char* value);
void set_copyright(const char* value, size_t size);
std::string* mutable_copyright();
std::string* release_copyright();
void set_allocated_copyright(std::string* copyright);
private:
const std::string& _internal_copyright() const;
void _internal_set_copyright(const std::string& value);
std::string* _internal_mutable_copyright();
public:
// optional uint32 year = 7;
bool has_year() const;
private:
bool _internal_has_year() const;
public:
void clear_year();
::PROTOBUF_NAMESPACE_ID::uint32 year() const;
void set_year(::PROTOBUF_NAMESPACE_ID::uint32 value);
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_year() const;
void _internal_set_year(::PROTOBUF_NAMESPACE_ID::uint32 value);
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.Book.Data)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr copyright_;
::PROTOBUF_NAMESPACE_ID::uint32 year_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class Book_Label PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.Book.Label) */ {
public:
inline Book_Label() : Book_Label(nullptr) {}
virtual ~Book_Label();
Book_Label(const Book_Label& from);
Book_Label(Book_Label&& from) noexcept
: Book_Label() {
*this = ::std::move(from);
}
inline Book_Label& operator=(const Book_Label& from) {
CopyFrom(from);
return *this;
}
inline Book_Label& operator=(Book_Label&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const Book_Label& default_instance();
static inline const Book_Label* internal_default_instance() {
return reinterpret_cast<const Book_Label*>(
&_Book_Label_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
friend void swap(Book_Label& a, Book_Label& b) {
a.Swap(&b);
}
inline void Swap(Book_Label* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(Book_Label* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline Book_Label* New() const final {
return CreateMaybeMessage<Book_Label>(nullptr);
}
Book_Label* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<Book_Label>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const Book_Label& from);
void MergeFrom(const Book_Label& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Book_Label* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.Book.Label";
}
protected:
explicit Book_Label(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kKeyFieldNumber = 1,
kValueFieldNumber = 2,
};
// optional string key = 1;
bool has_key() const;
private:
bool _internal_has_key() const;
public:
void clear_key();
const std::string& key() const;
void set_key(const std::string& value);
void set_key(std::string&& value);
void set_key(const char* value);
void set_key(const char* value, size_t size);
std::string* mutable_key();
std::string* release_key();
void set_allocated_key(std::string* key);
private:
const std::string& _internal_key() const;
void _internal_set_key(const std::string& value);
std::string* _internal_mutable_key();
public:
// optional string value = 2;
bool has_value() const;
private:
bool _internal_has_value() const;
public:
void clear_value();
const std::string& value() const;
void set_value(const std::string& value);
void set_value(std::string&& value);
void set_value(const char* value);
void set_value(const char* value, size_t size);
std::string* mutable_value();
std::string* release_value();
void set_allocated_value(std::string* value);
private:
const std::string& _internal_value() const;
void _internal_set_value(const std::string& value);
std::string* _internal_mutable_value();
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.Book.Label)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr key_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class Book PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.Book) */ {
public:
inline Book() : Book(nullptr) {}
virtual ~Book();
Book(const Book& from);
Book(Book&& from) noexcept
: Book() {
*this = ::std::move(from);
}
inline Book& operator=(const Book& from) {
CopyFrom(from);
return *this;
}
inline Book& operator=(Book&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const Book& default_instance();
static inline const Book* internal_default_instance() {
return reinterpret_cast<const Book*>(
&_Book_default_instance_);
}
static constexpr int kIndexInFileMessages =
2;
friend void swap(Book& a, Book& b) {
a.Swap(&b);
}
inline void Swap(Book* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(Book* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline Book* New() const final {
return CreateMaybeMessage<Book>(nullptr);
}
Book* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<Book>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const Book& from);
void MergeFrom(const Book& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Book* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.Book";
}
protected:
explicit Book(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
typedef Book_Data Data;
typedef Book_Label Label;
typedef Book_Type Type;
static constexpr Type FICTION =
Book_Type_FICTION;
static constexpr Type KIDS =
Book_Type_KIDS;
static constexpr Type ACTION_AND_ADVENTURE =
Book_Type_ACTION_AND_ADVENTURE;
static constexpr Type arts_and_photography =
Book_Type_arts_and_photography;
static constexpr Type I18N_Tech =
Book_Type_I18N_Tech;
static inline bool Type_IsValid(int value) {
return Book_Type_IsValid(value);
}
static constexpr Type Type_MIN =
Book_Type_Type_MIN;
static constexpr Type Type_MAX =
Book_Type_Type_MAX;
static constexpr int Type_ARRAYSIZE =
Book_Type_Type_ARRAYSIZE;
static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor*
Type_descriptor() {
return Book_Type_descriptor();
}
template<typename T>
static inline const std::string& Type_Name(T enum_t_value) {
static_assert(::std::is_same<T, Type>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function Type_Name.");
return Book_Type_Name(enum_t_value);
}
static inline bool Type_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name,
Type* value) {
return Book_Type_Parse(name, value);
}
// accessors -------------------------------------------------------
enum : int {
kLabelsFieldNumber = 10,
kPrimitiveRepeatedFieldNumber = 14,
kTitleFieldNumber = 1,
kContentFieldNumber = 5,
kSnakeFieldFieldNumber = 12,
kAuthorFieldNumber = 2,
kDataFieldNumber = 6,
kPublisherFieldNumber = 9,
kTypeNotFoundFieldNumber = 13,
kPublishedFieldNumber = 4,
kLengthFieldNumber = 3,
kTypeFieldNumber = 11,
};
// repeated .proto_util_converter.testing.Book.Label labels = 10;
int labels_size() const;
private:
int _internal_labels_size() const;
public:
void clear_labels();
::proto_util_converter::testing::Book_Label* mutable_labels(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Book_Label >*
mutable_labels();
private:
const ::proto_util_converter::testing::Book_Label& _internal_labels(int index) const;
::proto_util_converter::testing::Book_Label* _internal_add_labels();
public:
const ::proto_util_converter::testing::Book_Label& labels(int index) const;
::proto_util_converter::testing::Book_Label* add_labels();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Book_Label >&
labels() const;
// repeated int32 primitive_repeated = 14;
int primitive_repeated_size() const;
private:
int _internal_primitive_repeated_size() const;
public:
void clear_primitive_repeated();
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_primitive_repeated(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
_internal_primitive_repeated() const;
void _internal_add_primitive_repeated(::PROTOBUF_NAMESPACE_ID::int32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
_internal_mutable_primitive_repeated();
public:
::PROTOBUF_NAMESPACE_ID::int32 primitive_repeated(int index) const;
void set_primitive_repeated(int index, ::PROTOBUF_NAMESPACE_ID::int32 value);
void add_primitive_repeated(::PROTOBUF_NAMESPACE_ID::int32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
primitive_repeated() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
mutable_primitive_repeated();
// optional string title = 1;
bool has_title() const;
private:
bool _internal_has_title() const;
public:
void clear_title();
const std::string& title() const;
void set_title(const std::string& value);
void set_title(std::string&& value);
void set_title(const char* value);
void set_title(const char* value, size_t size);
std::string* mutable_title();
std::string* release_title();
void set_allocated_title(std::string* title);
private:
const std::string& _internal_title() const;
void _internal_set_title(const std::string& value);
std::string* _internal_mutable_title();
public:
// optional bytes content = 5;
bool has_content() const;
private:
bool _internal_has_content() const;
public:
void clear_content();
const std::string& content() const;
void set_content(const std::string& value);
void set_content(std::string&& value);
void set_content(const char* value);
void set_content(const void* value, size_t size);
std::string* mutable_content();
std::string* release_content();
void set_allocated_content(std::string* content);
private:
const std::string& _internal_content() const;
void _internal_set_content(const std::string& value);
std::string* _internal_mutable_content();
public:
// optional string snake_field = 12;
bool has_snake_field() const;
private:
bool _internal_has_snake_field() const;
public:
void clear_snake_field();
const std::string& snake_field() const;
void set_snake_field(const std::string& value);
void set_snake_field(std::string&& value);
void set_snake_field(const char* value);
void set_snake_field(const char* value, size_t size);
std::string* mutable_snake_field();
std::string* release_snake_field();
void set_allocated_snake_field(std::string* snake_field);
private:
const std::string& _internal_snake_field() const;
void _internal_set_snake_field(const std::string& value);
std::string* _internal_mutable_snake_field();
public:
// optional .proto_util_converter.testing.Author author = 2;
bool has_author() const;
private:
bool _internal_has_author() const;
public:
void clear_author();
const ::proto_util_converter::testing::Author& author() const;
::proto_util_converter::testing::Author* release_author();
::proto_util_converter::testing::Author* mutable_author();
void set_allocated_author(::proto_util_converter::testing::Author* author);
private:
const ::proto_util_converter::testing::Author& _internal_author() const;
::proto_util_converter::testing::Author* _internal_mutable_author();
public:
void unsafe_arena_set_allocated_author(
::proto_util_converter::testing::Author* author);
::proto_util_converter::testing::Author* unsafe_arena_release_author();
// optional group Data = 6 { ... };
bool has_data() const;
private:
bool _internal_has_data() const;
public:
void clear_data();
const ::proto_util_converter::testing::Book_Data& data() const;
::proto_util_converter::testing::Book_Data* release_data();
::proto_util_converter::testing::Book_Data* mutable_data();
void set_allocated_data(::proto_util_converter::testing::Book_Data* data);
private:
const ::proto_util_converter::testing::Book_Data& _internal_data() const;
::proto_util_converter::testing::Book_Data* _internal_mutable_data();
public:
void unsafe_arena_set_allocated_data(
::proto_util_converter::testing::Book_Data* data);
::proto_util_converter::testing::Book_Data* unsafe_arena_release_data();
// optional .proto_util_converter.testing.Publisher publisher = 9;
bool has_publisher() const;
private:
bool _internal_has_publisher() const;
public:
void clear_publisher();
const ::proto_util_converter::testing::Publisher& publisher() const;
::proto_util_converter::testing::Publisher* release_publisher();
::proto_util_converter::testing::Publisher* mutable_publisher();
void set_allocated_publisher(::proto_util_converter::testing::Publisher* publisher);
private:
const ::proto_util_converter::testing::Publisher& _internal_publisher() const;
::proto_util_converter::testing::Publisher* _internal_mutable_publisher();
public:
void unsafe_arena_set_allocated_publisher(
::proto_util_converter::testing::Publisher* publisher);
::proto_util_converter::testing::Publisher* unsafe_arena_release_publisher();
// optional .proto_util_converter.testing.AnyWrapper type_not_found = 13;
bool has_type_not_found() const;
private:
bool _internal_has_type_not_found() const;
public:
void clear_type_not_found();
const ::proto_util_converter::testing::AnyWrapper& type_not_found() const;
::proto_util_converter::testing::AnyWrapper* release_type_not_found();
::proto_util_converter::testing::AnyWrapper* mutable_type_not_found();
void set_allocated_type_not_found(::proto_util_converter::testing::AnyWrapper* type_not_found);
private:
const ::proto_util_converter::testing::AnyWrapper& _internal_type_not_found() const;
::proto_util_converter::testing::AnyWrapper* _internal_mutable_type_not_found();
public:
void unsafe_arena_set_allocated_type_not_found(
::proto_util_converter::testing::AnyWrapper* type_not_found);
::proto_util_converter::testing::AnyWrapper* unsafe_arena_release_type_not_found();
// optional int64 published = 4;
bool has_published() const;
private:
bool _internal_has_published() const;
public:
void clear_published();
::PROTOBUF_NAMESPACE_ID::int64 published() const;
void set_published(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_published() const;
void _internal_set_published(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional uint32 length = 3;
bool has_length() const;
private:
bool _internal_has_length() const;
public:
void clear_length();
::PROTOBUF_NAMESPACE_ID::uint32 length() const;
void set_length(::PROTOBUF_NAMESPACE_ID::uint32 value);
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_length() const;
void _internal_set_length(::PROTOBUF_NAMESPACE_ID::uint32 value);
public:
// optional .proto_util_converter.testing.Book.Type type = 11;
bool has_type() const;
private:
bool _internal_has_type() const;
public:
void clear_type();
::proto_util_converter::testing::Book_Type type() const;
void set_type(::proto_util_converter::testing::Book_Type value);
private:
::proto_util_converter::testing::Book_Type _internal_type() const;
void _internal_set_type(::proto_util_converter::testing::Book_Type value);
public:
GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(Book)
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.Book)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Book_Label > labels_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > primitive_repeated_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr title_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr content_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr snake_field_;
::proto_util_converter::testing::Author* author_;
::proto_util_converter::testing::Book_Data* data_;
::proto_util_converter::testing::Publisher* publisher_;
::proto_util_converter::testing::AnyWrapper* type_not_found_;
::PROTOBUF_NAMESPACE_ID::int64 published_;
::PROTOBUF_NAMESPACE_ID::uint32 length_;
int type_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class Publisher PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.Publisher) */ {
public:
inline Publisher() : Publisher(nullptr) {}
virtual ~Publisher();
Publisher(const Publisher& from);
Publisher(Publisher&& from) noexcept
: Publisher() {
*this = ::std::move(from);
}
inline Publisher& operator=(const Publisher& from) {
CopyFrom(from);
return *this;
}
inline Publisher& operator=(Publisher&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const Publisher& default_instance();
static inline const Publisher* internal_default_instance() {
return reinterpret_cast<const Publisher*>(
&_Publisher_default_instance_);
}
static constexpr int kIndexInFileMessages =
3;
friend void swap(Publisher& a, Publisher& b) {
a.Swap(&b);
}
inline void Swap(Publisher* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(Publisher* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline Publisher* New() const final {
return CreateMaybeMessage<Publisher>(nullptr);
}
Publisher* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<Publisher>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const Publisher& from);
void MergeFrom(const Publisher& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Publisher* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.Publisher";
}
protected:
explicit Publisher(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kNameFieldNumber = 1,
};
// required string name = 1;
bool has_name() const;
private:
bool _internal_has_name() const;
public:
void clear_name();
const std::string& name() const;
void set_name(const std::string& value);
void set_name(std::string&& value);
void set_name(const char* value);
void set_name(const char* value, size_t size);
std::string* mutable_name();
std::string* release_name();
void set_allocated_name(std::string* name);
private:
const std::string& _internal_name() const;
void _internal_set_name(const std::string& value);
std::string* _internal_mutable_name();
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.Publisher)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class Author PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.Author) */ {
public:
inline Author() : Author(nullptr) {}
virtual ~Author();
Author(const Author& from);
Author(Author&& from) noexcept
: Author() {
*this = ::std::move(from);
}
inline Author& operator=(const Author& from) {
CopyFrom(from);
return *this;
}
inline Author& operator=(Author&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const Author& default_instance();
static inline const Author* internal_default_instance() {
return reinterpret_cast<const Author*>(
&_Author_default_instance_);
}
static constexpr int kIndexInFileMessages =
4;
friend void swap(Author& a, Author& b) {
a.Swap(&b);
}
inline void Swap(Author* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(Author* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline Author* New() const final {
return CreateMaybeMessage<Author>(nullptr);
}
Author* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<Author>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const Author& from);
void MergeFrom(const Author& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Author* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.Author";
}
protected:
explicit Author(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kPseudonymFieldNumber = 3,
kFriendFieldNumber = 5,
kNameFieldNumber = 2,
kIdFieldNumber = 1,
kAliveFieldNumber = 4,
};
// repeated string pseudonym = 3;
int pseudonym_size() const;
private:
int _internal_pseudonym_size() const;
public:
void clear_pseudonym();
const std::string& pseudonym(int index) const;
std::string* mutable_pseudonym(int index);
void set_pseudonym(int index, const std::string& value);
void set_pseudonym(int index, std::string&& value);
void set_pseudonym(int index, const char* value);
void set_pseudonym(int index, const char* value, size_t size);
std::string* add_pseudonym();
void add_pseudonym(const std::string& value);
void add_pseudonym(std::string&& value);
void add_pseudonym(const char* value);
void add_pseudonym(const char* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& pseudonym() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_pseudonym();
private:
const std::string& _internal_pseudonym(int index) const;
std::string* _internal_add_pseudonym();
public:
// repeated .proto_util_converter.testing.Author friend = 5;
int friend__size() const;
private:
int _internal_friend__size() const;
public:
void clear_friend_();
::proto_util_converter::testing::Author* mutable_friend_(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author >*
mutable_friend_();
private:
const ::proto_util_converter::testing::Author& _internal_friend_(int index) const;
::proto_util_converter::testing::Author* _internal_add_friend_();
public:
const ::proto_util_converter::testing::Author& friend_(int index) const;
::proto_util_converter::testing::Author* add_friend_();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author >&
friend_() const;
// optional string name = 2;
bool has_name() const;
private:
bool _internal_has_name() const;
public:
void clear_name();
const std::string& name() const;
void set_name(const std::string& value);
void set_name(std::string&& value);
void set_name(const char* value);
void set_name(const char* value, size_t size);
std::string* mutable_name();
std::string* release_name();
void set_allocated_name(std::string* name);
private:
const std::string& _internal_name() const;
void _internal_set_name(const std::string& value);
std::string* _internal_mutable_name();
public:
// optional uint64 id = 1 [json_name = "@id"];
bool has_id() const;
private:
bool _internal_has_id() const;
public:
void clear_id();
::PROTOBUF_NAMESPACE_ID::uint64 id() const;
void set_id(::PROTOBUF_NAMESPACE_ID::uint64 value);
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_id() const;
void _internal_set_id(::PROTOBUF_NAMESPACE_ID::uint64 value);
public:
// optional bool alive = 4;
bool has_alive() const;
private:
bool _internal_has_alive() const;
public:
void clear_alive();
bool alive() const;
void set_alive(bool value);
private:
bool _internal_alive() const;
void _internal_set_alive(bool value);
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.Author)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> pseudonym_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author > friend__;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_;
::PROTOBUF_NAMESPACE_ID::uint64 id_;
bool alive_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class BadAuthor PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.BadAuthor) */ {
public:
inline BadAuthor() : BadAuthor(nullptr) {}
virtual ~BadAuthor();
BadAuthor(const BadAuthor& from);
BadAuthor(BadAuthor&& from) noexcept
: BadAuthor() {
*this = ::std::move(from);
}
inline BadAuthor& operator=(const BadAuthor& from) {
CopyFrom(from);
return *this;
}
inline BadAuthor& operator=(BadAuthor&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const BadAuthor& default_instance();
static inline const BadAuthor* internal_default_instance() {
return reinterpret_cast<const BadAuthor*>(
&_BadAuthor_default_instance_);
}
static constexpr int kIndexInFileMessages =
5;
friend void swap(BadAuthor& a, BadAuthor& b) {
a.Swap(&b);
}
inline void Swap(BadAuthor* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(BadAuthor* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline BadAuthor* New() const final {
return CreateMaybeMessage<BadAuthor>(nullptr);
}
BadAuthor* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<BadAuthor>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const BadAuthor& from);
void MergeFrom(const BadAuthor& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(BadAuthor* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.BadAuthor";
}
protected:
explicit BadAuthor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kNameFieldNumber = 2,
kAliveFieldNumber = 4,
kIdFieldNumber = 1,
kPseudonymFieldNumber = 3,
};
// repeated uint64 name = 2;
int name_size() const;
private:
int _internal_name_size() const;
public:
void clear_name();
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_name(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
_internal_name() const;
void _internal_add_name(::PROTOBUF_NAMESPACE_ID::uint64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
_internal_mutable_name();
public:
::PROTOBUF_NAMESPACE_ID::uint64 name(int index) const;
void set_name(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value);
void add_name(::PROTOBUF_NAMESPACE_ID::uint64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
name() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
mutable_name();
// repeated bool alive = 4 [packed = true];
int alive_size() const;
private:
int _internal_alive_size() const;
public:
void clear_alive();
private:
bool _internal_alive(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
_internal_alive() const;
void _internal_add_alive(bool value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
_internal_mutable_alive();
public:
bool alive(int index) const;
void set_alive(int index, bool value);
void add_alive(bool value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
alive() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
mutable_alive();
// optional string id = 1;
bool has_id() const;
private:
bool _internal_has_id() const;
public:
void clear_id();
const std::string& id() const;
void set_id(const std::string& value);
void set_id(std::string&& value);
void set_id(const char* value);
void set_id(const char* value, size_t size);
std::string* mutable_id();
std::string* release_id();
void set_allocated_id(std::string* id);
private:
const std::string& _internal_id() const;
void _internal_set_id(const std::string& value);
std::string* _internal_mutable_id();
public:
// optional string pseudonym = 3;
bool has_pseudonym() const;
private:
bool _internal_has_pseudonym() const;
public:
void clear_pseudonym();
const std::string& pseudonym() const;
void set_pseudonym(const std::string& value);
void set_pseudonym(std::string&& value);
void set_pseudonym(const char* value);
void set_pseudonym(const char* value, size_t size);
std::string* mutable_pseudonym();
std::string* release_pseudonym();
void set_allocated_pseudonym(std::string* pseudonym);
private:
const std::string& _internal_pseudonym() const;
void _internal_set_pseudonym(const std::string& value);
std::string* _internal_mutable_pseudonym();
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.BadAuthor)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 > name_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< bool > alive_;
mutable std::atomic<int> _alive_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr id_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr pseudonym_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class Primitive PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.Primitive) */ {
public:
inline Primitive() : Primitive(nullptr) {}
virtual ~Primitive();
Primitive(const Primitive& from);
Primitive(Primitive&& from) noexcept
: Primitive() {
*this = ::std::move(from);
}
inline Primitive& operator=(const Primitive& from) {
CopyFrom(from);
return *this;
}
inline Primitive& operator=(Primitive&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const Primitive& default_instance();
static inline const Primitive* internal_default_instance() {
return reinterpret_cast<const Primitive*>(
&_Primitive_default_instance_);
}
static constexpr int kIndexInFileMessages =
6;
friend void swap(Primitive& a, Primitive& b) {
a.Swap(&b);
}
inline void Swap(Primitive* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(Primitive* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline Primitive* New() const final {
return CreateMaybeMessage<Primitive>(nullptr);
}
Primitive* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<Primitive>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const Primitive& from);
void MergeFrom(const Primitive& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Primitive* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.Primitive";
}
protected:
explicit Primitive(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kRepFix32FieldNumber = 16,
kRepU32FieldNumber = 17,
kRepI32FieldNumber = 18,
kRepSf32FieldNumber = 19,
kRepS32FieldNumber = 20,
kRepFix64FieldNumber = 21,
kRepU64FieldNumber = 22,
kRepI64FieldNumber = 23,
kRepSf64FieldNumber = 24,
kRepS64FieldNumber = 25,
kRepStrFieldNumber = 26,
kRepBytesFieldNumber = 27,
kRepFloatFieldNumber = 28,
kRepDoubleFieldNumber = 29,
kRepBoolFieldNumber = 30,
kStrFieldNumber = 11,
kBytesFieldNumber = 12,
kFix32FieldNumber = 1,
kU32FieldNumber = 2,
kI32FieldNumber = 3,
kSf32FieldNumber = 4,
kFix64FieldNumber = 6,
kU64FieldNumber = 7,
kI64FieldNumber = 8,
kSf64FieldNumber = 9,
kS32FieldNumber = 5,
kFloatFieldNumber = 13,
kS64FieldNumber = 10,
kDoubleFieldNumber = 14,
kBoolFieldNumber = 15,
};
// repeated fixed32 rep_fix32 = 16;
int rep_fix32_size() const;
private:
int _internal_rep_fix32_size() const;
public:
void clear_rep_fix32();
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_rep_fix32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
_internal_rep_fix32() const;
void _internal_add_rep_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
_internal_mutable_rep_fix32();
public:
::PROTOBUF_NAMESPACE_ID::uint32 rep_fix32(int index) const;
void set_rep_fix32(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value);
void add_rep_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
rep_fix32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
mutable_rep_fix32();
// repeated uint32 rep_u32 = 17;
int rep_u32_size() const;
private:
int _internal_rep_u32_size() const;
public:
void clear_rep_u32();
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_rep_u32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
_internal_rep_u32() const;
void _internal_add_rep_u32(::PROTOBUF_NAMESPACE_ID::uint32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
_internal_mutable_rep_u32();
public:
::PROTOBUF_NAMESPACE_ID::uint32 rep_u32(int index) const;
void set_rep_u32(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value);
void add_rep_u32(::PROTOBUF_NAMESPACE_ID::uint32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
rep_u32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
mutable_rep_u32();
// repeated int32 rep_i32 = 18;
int rep_i32_size() const;
private:
int _internal_rep_i32_size() const;
public:
void clear_rep_i32();
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_rep_i32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
_internal_rep_i32() const;
void _internal_add_rep_i32(::PROTOBUF_NAMESPACE_ID::int32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
_internal_mutable_rep_i32();
public:
::PROTOBUF_NAMESPACE_ID::int32 rep_i32(int index) const;
void set_rep_i32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value);
void add_rep_i32(::PROTOBUF_NAMESPACE_ID::int32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
rep_i32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
mutable_rep_i32();
// repeated sfixed32 rep_sf32 = 19;
int rep_sf32_size() const;
private:
int _internal_rep_sf32_size() const;
public:
void clear_rep_sf32();
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_rep_sf32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
_internal_rep_sf32() const;
void _internal_add_rep_sf32(::PROTOBUF_NAMESPACE_ID::int32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
_internal_mutable_rep_sf32();
public:
::PROTOBUF_NAMESPACE_ID::int32 rep_sf32(int index) const;
void set_rep_sf32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value);
void add_rep_sf32(::PROTOBUF_NAMESPACE_ID::int32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
rep_sf32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
mutable_rep_sf32();
// repeated sint32 rep_s32 = 20;
int rep_s32_size() const;
private:
int _internal_rep_s32_size() const;
public:
void clear_rep_s32();
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_rep_s32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
_internal_rep_s32() const;
void _internal_add_rep_s32(::PROTOBUF_NAMESPACE_ID::int32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
_internal_mutable_rep_s32();
public:
::PROTOBUF_NAMESPACE_ID::int32 rep_s32(int index) const;
void set_rep_s32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value);
void add_rep_s32(::PROTOBUF_NAMESPACE_ID::int32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
rep_s32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
mutable_rep_s32();
// repeated fixed64 rep_fix64 = 21;
int rep_fix64_size() const;
private:
int _internal_rep_fix64_size() const;
public:
void clear_rep_fix64();
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_rep_fix64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
_internal_rep_fix64() const;
void _internal_add_rep_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
_internal_mutable_rep_fix64();
public:
::PROTOBUF_NAMESPACE_ID::uint64 rep_fix64(int index) const;
void set_rep_fix64(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value);
void add_rep_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
rep_fix64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
mutable_rep_fix64();
// repeated uint64 rep_u64 = 22;
int rep_u64_size() const;
private:
int _internal_rep_u64_size() const;
public:
void clear_rep_u64();
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_rep_u64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
_internal_rep_u64() const;
void _internal_add_rep_u64(::PROTOBUF_NAMESPACE_ID::uint64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
_internal_mutable_rep_u64();
public:
::PROTOBUF_NAMESPACE_ID::uint64 rep_u64(int index) const;
void set_rep_u64(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value);
void add_rep_u64(::PROTOBUF_NAMESPACE_ID::uint64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
rep_u64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
mutable_rep_u64();
// repeated int64 rep_i64 = 23;
int rep_i64_size() const;
private:
int _internal_rep_i64_size() const;
public:
void clear_rep_i64();
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_rep_i64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
_internal_rep_i64() const;
void _internal_add_rep_i64(::PROTOBUF_NAMESPACE_ID::int64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
_internal_mutable_rep_i64();
public:
::PROTOBUF_NAMESPACE_ID::int64 rep_i64(int index) const;
void set_rep_i64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value);
void add_rep_i64(::PROTOBUF_NAMESPACE_ID::int64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
rep_i64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
mutable_rep_i64();
// repeated sfixed64 rep_sf64 = 24;
int rep_sf64_size() const;
private:
int _internal_rep_sf64_size() const;
public:
void clear_rep_sf64();
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_rep_sf64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
_internal_rep_sf64() const;
void _internal_add_rep_sf64(::PROTOBUF_NAMESPACE_ID::int64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
_internal_mutable_rep_sf64();
public:
::PROTOBUF_NAMESPACE_ID::int64 rep_sf64(int index) const;
void set_rep_sf64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value);
void add_rep_sf64(::PROTOBUF_NAMESPACE_ID::int64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
rep_sf64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
mutable_rep_sf64();
// repeated sint64 rep_s64 = 25;
int rep_s64_size() const;
private:
int _internal_rep_s64_size() const;
public:
void clear_rep_s64();
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_rep_s64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
_internal_rep_s64() const;
void _internal_add_rep_s64(::PROTOBUF_NAMESPACE_ID::int64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
_internal_mutable_rep_s64();
public:
::PROTOBUF_NAMESPACE_ID::int64 rep_s64(int index) const;
void set_rep_s64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value);
void add_rep_s64(::PROTOBUF_NAMESPACE_ID::int64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
rep_s64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
mutable_rep_s64();
// repeated string rep_str = 26;
int rep_str_size() const;
private:
int _internal_rep_str_size() const;
public:
void clear_rep_str();
const std::string& rep_str(int index) const;
std::string* mutable_rep_str(int index);
void set_rep_str(int index, const std::string& value);
void set_rep_str(int index, std::string&& value);
void set_rep_str(int index, const char* value);
void set_rep_str(int index, const char* value, size_t size);
std::string* add_rep_str();
void add_rep_str(const std::string& value);
void add_rep_str(std::string&& value);
void add_rep_str(const char* value);
void add_rep_str(const char* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& rep_str() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_rep_str();
private:
const std::string& _internal_rep_str(int index) const;
std::string* _internal_add_rep_str();
public:
// repeated bytes rep_bytes = 27;
int rep_bytes_size() const;
private:
int _internal_rep_bytes_size() const;
public:
void clear_rep_bytes();
const std::string& rep_bytes(int index) const;
std::string* mutable_rep_bytes(int index);
void set_rep_bytes(int index, const std::string& value);
void set_rep_bytes(int index, std::string&& value);
void set_rep_bytes(int index, const char* value);
void set_rep_bytes(int index, const void* value, size_t size);
std::string* add_rep_bytes();
void add_rep_bytes(const std::string& value);
void add_rep_bytes(std::string&& value);
void add_rep_bytes(const char* value);
void add_rep_bytes(const void* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& rep_bytes() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_rep_bytes();
private:
const std::string& _internal_rep_bytes(int index) const;
std::string* _internal_add_rep_bytes();
public:
// repeated float rep_float = 28;
int rep_float_size() const;
private:
int _internal_rep_float_size() const;
public:
void clear_rep_float();
private:
float _internal_rep_float(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >&
_internal_rep_float() const;
void _internal_add_rep_float(float value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< float >*
_internal_mutable_rep_float();
public:
float rep_float(int index) const;
void set_rep_float(int index, float value);
void add_rep_float(float value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >&
rep_float() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< float >*
mutable_rep_float();
// repeated double rep_double = 29;
int rep_double_size() const;
private:
int _internal_rep_double_size() const;
public:
void clear_rep_double();
private:
double _internal_rep_double(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
_internal_rep_double() const;
void _internal_add_rep_double(double value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
_internal_mutable_rep_double();
public:
double rep_double(int index) const;
void set_rep_double(int index, double value);
void add_rep_double(double value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
rep_double() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
mutable_rep_double();
// repeated bool rep_bool = 30;
int rep_bool_size() const;
private:
int _internal_rep_bool_size() const;
public:
void clear_rep_bool();
private:
bool _internal_rep_bool(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
_internal_rep_bool() const;
void _internal_add_rep_bool(bool value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
_internal_mutable_rep_bool();
public:
bool rep_bool(int index) const;
void set_rep_bool(int index, bool value);
void add_rep_bool(bool value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
rep_bool() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
mutable_rep_bool();
// optional string str = 11;
bool has_str() const;
private:
bool _internal_has_str() const;
public:
void clear_str();
const std::string& str() const;
void set_str(const std::string& value);
void set_str(std::string&& value);
void set_str(const char* value);
void set_str(const char* value, size_t size);
std::string* mutable_str();
std::string* release_str();
void set_allocated_str(std::string* str);
private:
const std::string& _internal_str() const;
void _internal_set_str(const std::string& value);
std::string* _internal_mutable_str();
public:
// optional bytes bytes = 12;
bool has_bytes() const;
private:
bool _internal_has_bytes() const;
public:
void clear_bytes();
const std::string& bytes() const;
void set_bytes(const std::string& value);
void set_bytes(std::string&& value);
void set_bytes(const char* value);
void set_bytes(const void* value, size_t size);
std::string* mutable_bytes();
std::string* release_bytes();
void set_allocated_bytes(std::string* bytes);
private:
const std::string& _internal_bytes() const;
void _internal_set_bytes(const std::string& value);
std::string* _internal_mutable_bytes();
public:
// optional fixed32 fix32 = 1;
bool has_fix32() const;
private:
bool _internal_has_fix32() const;
public:
void clear_fix32();
::PROTOBUF_NAMESPACE_ID::uint32 fix32() const;
void set_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value);
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_fix32() const;
void _internal_set_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value);
public:
// optional uint32 u32 = 2;
bool has_u32() const;
private:
bool _internal_has_u32() const;
public:
void clear_u32();
::PROTOBUF_NAMESPACE_ID::uint32 u32() const;
void set_u32(::PROTOBUF_NAMESPACE_ID::uint32 value);
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_u32() const;
void _internal_set_u32(::PROTOBUF_NAMESPACE_ID::uint32 value);
public:
// optional int32 i32 = 3;
bool has_i32() const;
private:
bool _internal_has_i32() const;
public:
void clear_i32();
::PROTOBUF_NAMESPACE_ID::int32 i32() const;
void set_i32(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_i32() const;
void _internal_set_i32(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// optional sfixed32 sf32 = 4;
bool has_sf32() const;
private:
bool _internal_has_sf32() const;
public:
void clear_sf32();
::PROTOBUF_NAMESPACE_ID::int32 sf32() const;
void set_sf32(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_sf32() const;
void _internal_set_sf32(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// optional fixed64 fix64 = 6;
bool has_fix64() const;
private:
bool _internal_has_fix64() const;
public:
void clear_fix64();
::PROTOBUF_NAMESPACE_ID::uint64 fix64() const;
void set_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value);
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_fix64() const;
void _internal_set_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value);
public:
// optional uint64 u64 = 7;
bool has_u64() const;
private:
bool _internal_has_u64() const;
public:
void clear_u64();
::PROTOBUF_NAMESPACE_ID::uint64 u64() const;
void set_u64(::PROTOBUF_NAMESPACE_ID::uint64 value);
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_u64() const;
void _internal_set_u64(::PROTOBUF_NAMESPACE_ID::uint64 value);
public:
// optional int64 i64 = 8;
bool has_i64() const;
private:
bool _internal_has_i64() const;
public:
void clear_i64();
::PROTOBUF_NAMESPACE_ID::int64 i64() const;
void set_i64(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_i64() const;
void _internal_set_i64(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional sfixed64 sf64 = 9;
bool has_sf64() const;
private:
bool _internal_has_sf64() const;
public:
void clear_sf64();
::PROTOBUF_NAMESPACE_ID::int64 sf64() const;
void set_sf64(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_sf64() const;
void _internal_set_sf64(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional sint32 s32 = 5;
bool has_s32() const;
private:
bool _internal_has_s32() const;
public:
void clear_s32();
::PROTOBUF_NAMESPACE_ID::int32 s32() const;
void set_s32(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_s32() const;
void _internal_set_s32(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// optional float float = 13;
bool has_float_() const;
private:
bool _internal_has_float_() const;
public:
void clear_float_();
float float_() const;
void set_float_(float value);
private:
float _internal_float_() const;
void _internal_set_float_(float value);
public:
// optional sint64 s64 = 10;
bool has_s64() const;
private:
bool _internal_has_s64() const;
public:
void clear_s64();
::PROTOBUF_NAMESPACE_ID::int64 s64() const;
void set_s64(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_s64() const;
void _internal_set_s64(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional double double = 14;
bool has_double_() const;
private:
bool _internal_has_double_() const;
public:
void clear_double_();
double double_() const;
void set_double_(double value);
private:
double _internal_double_() const;
void _internal_set_double_(double value);
public:
// optional bool bool = 15;
bool has_bool_() const;
private:
bool _internal_has_bool_() const;
public:
void clear_bool_();
bool bool_() const;
void set_bool_(bool value);
private:
bool _internal_bool_() const;
void _internal_set_bool_(bool value);
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.Primitive)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 > rep_fix32_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 > rep_u32_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > rep_i32_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > rep_sf32_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > rep_s32_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 > rep_fix64_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 > rep_u64_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 > rep_i64_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 > rep_sf64_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 > rep_s64_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> rep_str_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> rep_bytes_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< float > rep_float_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< double > rep_double_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< bool > rep_bool_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr str_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr bytes_;
::PROTOBUF_NAMESPACE_ID::uint32 fix32_;
::PROTOBUF_NAMESPACE_ID::uint32 u32_;
::PROTOBUF_NAMESPACE_ID::int32 i32_;
::PROTOBUF_NAMESPACE_ID::int32 sf32_;
::PROTOBUF_NAMESPACE_ID::uint64 fix64_;
::PROTOBUF_NAMESPACE_ID::uint64 u64_;
::PROTOBUF_NAMESPACE_ID::int64 i64_;
::PROTOBUF_NAMESPACE_ID::int64 sf64_;
::PROTOBUF_NAMESPACE_ID::int32 s32_;
float float__;
::PROTOBUF_NAMESPACE_ID::int64 s64_;
double double__;
bool bool__;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class PackedPrimitive PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.PackedPrimitive) */ {
public:
inline PackedPrimitive() : PackedPrimitive(nullptr) {}
virtual ~PackedPrimitive();
PackedPrimitive(const PackedPrimitive& from);
PackedPrimitive(PackedPrimitive&& from) noexcept
: PackedPrimitive() {
*this = ::std::move(from);
}
inline PackedPrimitive& operator=(const PackedPrimitive& from) {
CopyFrom(from);
return *this;
}
inline PackedPrimitive& operator=(PackedPrimitive&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const PackedPrimitive& default_instance();
static inline const PackedPrimitive* internal_default_instance() {
return reinterpret_cast<const PackedPrimitive*>(
&_PackedPrimitive_default_instance_);
}
static constexpr int kIndexInFileMessages =
7;
friend void swap(PackedPrimitive& a, PackedPrimitive& b) {
a.Swap(&b);
}
inline void Swap(PackedPrimitive* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(PackedPrimitive* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline PackedPrimitive* New() const final {
return CreateMaybeMessage<PackedPrimitive>(nullptr);
}
PackedPrimitive* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<PackedPrimitive>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const PackedPrimitive& from);
void MergeFrom(const PackedPrimitive& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(PackedPrimitive* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.PackedPrimitive";
}
protected:
explicit PackedPrimitive(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kRepFix32FieldNumber = 16,
kRepU32FieldNumber = 17,
kRepI32FieldNumber = 18,
kRepSf32FieldNumber = 19,
kRepS32FieldNumber = 20,
kRepFix64FieldNumber = 21,
kRepU64FieldNumber = 22,
kRepI64FieldNumber = 23,
kRepSf64FieldNumber = 24,
kRepS64FieldNumber = 25,
kRepFloatFieldNumber = 28,
kRepDoubleFieldNumber = 29,
kRepBoolFieldNumber = 30,
};
// repeated fixed32 rep_fix32 = 16 [packed = true];
int rep_fix32_size() const;
private:
int _internal_rep_fix32_size() const;
public:
void clear_rep_fix32();
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_rep_fix32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
_internal_rep_fix32() const;
void _internal_add_rep_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
_internal_mutable_rep_fix32();
public:
::PROTOBUF_NAMESPACE_ID::uint32 rep_fix32(int index) const;
void set_rep_fix32(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value);
void add_rep_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
rep_fix32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
mutable_rep_fix32();
// repeated uint32 rep_u32 = 17 [packed = true];
int rep_u32_size() const;
private:
int _internal_rep_u32_size() const;
public:
void clear_rep_u32();
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_rep_u32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
_internal_rep_u32() const;
void _internal_add_rep_u32(::PROTOBUF_NAMESPACE_ID::uint32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
_internal_mutable_rep_u32();
public:
::PROTOBUF_NAMESPACE_ID::uint32 rep_u32(int index) const;
void set_rep_u32(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value);
void add_rep_u32(::PROTOBUF_NAMESPACE_ID::uint32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
rep_u32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
mutable_rep_u32();
// repeated int32 rep_i32 = 18 [packed = true];
int rep_i32_size() const;
private:
int _internal_rep_i32_size() const;
public:
void clear_rep_i32();
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_rep_i32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
_internal_rep_i32() const;
void _internal_add_rep_i32(::PROTOBUF_NAMESPACE_ID::int32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
_internal_mutable_rep_i32();
public:
::PROTOBUF_NAMESPACE_ID::int32 rep_i32(int index) const;
void set_rep_i32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value);
void add_rep_i32(::PROTOBUF_NAMESPACE_ID::int32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
rep_i32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
mutable_rep_i32();
// repeated sfixed32 rep_sf32 = 19 [packed = true];
int rep_sf32_size() const;
private:
int _internal_rep_sf32_size() const;
public:
void clear_rep_sf32();
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_rep_sf32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
_internal_rep_sf32() const;
void _internal_add_rep_sf32(::PROTOBUF_NAMESPACE_ID::int32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
_internal_mutable_rep_sf32();
public:
::PROTOBUF_NAMESPACE_ID::int32 rep_sf32(int index) const;
void set_rep_sf32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value);
void add_rep_sf32(::PROTOBUF_NAMESPACE_ID::int32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
rep_sf32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
mutable_rep_sf32();
// repeated sint32 rep_s32 = 20 [packed = true];
int rep_s32_size() const;
private:
int _internal_rep_s32_size() const;
public:
void clear_rep_s32();
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_rep_s32(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
_internal_rep_s32() const;
void _internal_add_rep_s32(::PROTOBUF_NAMESPACE_ID::int32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
_internal_mutable_rep_s32();
public:
::PROTOBUF_NAMESPACE_ID::int32 rep_s32(int index) const;
void set_rep_s32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value);
void add_rep_s32(::PROTOBUF_NAMESPACE_ID::int32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
rep_s32() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
mutable_rep_s32();
// repeated fixed64 rep_fix64 = 21 [packed = true];
int rep_fix64_size() const;
private:
int _internal_rep_fix64_size() const;
public:
void clear_rep_fix64();
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_rep_fix64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
_internal_rep_fix64() const;
void _internal_add_rep_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
_internal_mutable_rep_fix64();
public:
::PROTOBUF_NAMESPACE_ID::uint64 rep_fix64(int index) const;
void set_rep_fix64(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value);
void add_rep_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
rep_fix64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
mutable_rep_fix64();
// repeated uint64 rep_u64 = 22 [packed = true];
int rep_u64_size() const;
private:
int _internal_rep_u64_size() const;
public:
void clear_rep_u64();
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_rep_u64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
_internal_rep_u64() const;
void _internal_add_rep_u64(::PROTOBUF_NAMESPACE_ID::uint64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
_internal_mutable_rep_u64();
public:
::PROTOBUF_NAMESPACE_ID::uint64 rep_u64(int index) const;
void set_rep_u64(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value);
void add_rep_u64(::PROTOBUF_NAMESPACE_ID::uint64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
rep_u64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
mutable_rep_u64();
// repeated int64 rep_i64 = 23 [packed = true];
int rep_i64_size() const;
private:
int _internal_rep_i64_size() const;
public:
void clear_rep_i64();
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_rep_i64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
_internal_rep_i64() const;
void _internal_add_rep_i64(::PROTOBUF_NAMESPACE_ID::int64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
_internal_mutable_rep_i64();
public:
::PROTOBUF_NAMESPACE_ID::int64 rep_i64(int index) const;
void set_rep_i64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value);
void add_rep_i64(::PROTOBUF_NAMESPACE_ID::int64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
rep_i64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
mutable_rep_i64();
// repeated sfixed64 rep_sf64 = 24 [packed = true];
int rep_sf64_size() const;
private:
int _internal_rep_sf64_size() const;
public:
void clear_rep_sf64();
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_rep_sf64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
_internal_rep_sf64() const;
void _internal_add_rep_sf64(::PROTOBUF_NAMESPACE_ID::int64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
_internal_mutable_rep_sf64();
public:
::PROTOBUF_NAMESPACE_ID::int64 rep_sf64(int index) const;
void set_rep_sf64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value);
void add_rep_sf64(::PROTOBUF_NAMESPACE_ID::int64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
rep_sf64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
mutable_rep_sf64();
// repeated sint64 rep_s64 = 25 [packed = true];
int rep_s64_size() const;
private:
int _internal_rep_s64_size() const;
public:
void clear_rep_s64();
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_rep_s64(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
_internal_rep_s64() const;
void _internal_add_rep_s64(::PROTOBUF_NAMESPACE_ID::int64 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
_internal_mutable_rep_s64();
public:
::PROTOBUF_NAMESPACE_ID::int64 rep_s64(int index) const;
void set_rep_s64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value);
void add_rep_s64(::PROTOBUF_NAMESPACE_ID::int64 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
rep_s64() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
mutable_rep_s64();
// repeated float rep_float = 28 [packed = true];
int rep_float_size() const;
private:
int _internal_rep_float_size() const;
public:
void clear_rep_float();
private:
float _internal_rep_float(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >&
_internal_rep_float() const;
void _internal_add_rep_float(float value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< float >*
_internal_mutable_rep_float();
public:
float rep_float(int index) const;
void set_rep_float(int index, float value);
void add_rep_float(float value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >&
rep_float() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< float >*
mutable_rep_float();
// repeated double rep_double = 29 [packed = true];
int rep_double_size() const;
private:
int _internal_rep_double_size() const;
public:
void clear_rep_double();
private:
double _internal_rep_double(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
_internal_rep_double() const;
void _internal_add_rep_double(double value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
_internal_mutable_rep_double();
public:
double rep_double(int index) const;
void set_rep_double(int index, double value);
void add_rep_double(double value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
rep_double() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
mutable_rep_double();
// repeated bool rep_bool = 30 [packed = true];
int rep_bool_size() const;
private:
int _internal_rep_bool_size() const;
public:
void clear_rep_bool();
private:
bool _internal_rep_bool(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
_internal_rep_bool() const;
void _internal_add_rep_bool(bool value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
_internal_mutable_rep_bool();
public:
bool rep_bool(int index) const;
void set_rep_bool(int index, bool value);
void add_rep_bool(bool value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
rep_bool() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
mutable_rep_bool();
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.PackedPrimitive)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 > rep_fix32_;
mutable std::atomic<int> _rep_fix32_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 > rep_u32_;
mutable std::atomic<int> _rep_u32_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > rep_i32_;
mutable std::atomic<int> _rep_i32_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > rep_sf32_;
mutable std::atomic<int> _rep_sf32_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > rep_s32_;
mutable std::atomic<int> _rep_s32_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 > rep_fix64_;
mutable std::atomic<int> _rep_fix64_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 > rep_u64_;
mutable std::atomic<int> _rep_u64_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 > rep_i64_;
mutable std::atomic<int> _rep_i64_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 > rep_sf64_;
mutable std::atomic<int> _rep_sf64_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 > rep_s64_;
mutable std::atomic<int> _rep_s64_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< float > rep_float_;
mutable std::atomic<int> _rep_float_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< double > rep_double_;
mutable std::atomic<int> _rep_double_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< bool > rep_bool_;
mutable std::atomic<int> _rep_bool_cached_byte_size_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class NestedBook PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.NestedBook) */ {
public:
inline NestedBook() : NestedBook(nullptr) {}
virtual ~NestedBook();
NestedBook(const NestedBook& from);
NestedBook(NestedBook&& from) noexcept
: NestedBook() {
*this = ::std::move(from);
}
inline NestedBook& operator=(const NestedBook& from) {
CopyFrom(from);
return *this;
}
inline NestedBook& operator=(NestedBook&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const NestedBook& default_instance();
static inline const NestedBook* internal_default_instance() {
return reinterpret_cast<const NestedBook*>(
&_NestedBook_default_instance_);
}
static constexpr int kIndexInFileMessages =
8;
friend void swap(NestedBook& a, NestedBook& b) {
a.Swap(&b);
}
inline void Swap(NestedBook* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(NestedBook* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline NestedBook* New() const final {
return CreateMaybeMessage<NestedBook>(nullptr);
}
NestedBook* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<NestedBook>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const NestedBook& from);
void MergeFrom(const NestedBook& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(NestedBook* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.NestedBook";
}
protected:
explicit NestedBook(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kBookFieldNumber = 1,
};
// optional .proto_util_converter.testing.Book book = 1;
bool has_book() const;
private:
bool _internal_has_book() const;
public:
void clear_book();
const ::proto_util_converter::testing::Book& book() const;
::proto_util_converter::testing::Book* release_book();
::proto_util_converter::testing::Book* mutable_book();
void set_allocated_book(::proto_util_converter::testing::Book* book);
private:
const ::proto_util_converter::testing::Book& _internal_book() const;
::proto_util_converter::testing::Book* _internal_mutable_book();
public:
void unsafe_arena_set_allocated_book(
::proto_util_converter::testing::Book* book);
::proto_util_converter::testing::Book* unsafe_arena_release_book();
static const int kAnotherBookFieldNumber = 301;
static ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::proto_util_converter::testing::Book,
::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::proto_util_converter::testing::NestedBook >, 11, false >
another_book;
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.NestedBook)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::proto_util_converter::testing::Book* book_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class BadNestedBook PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.BadNestedBook) */ {
public:
inline BadNestedBook() : BadNestedBook(nullptr) {}
virtual ~BadNestedBook();
BadNestedBook(const BadNestedBook& from);
BadNestedBook(BadNestedBook&& from) noexcept
: BadNestedBook() {
*this = ::std::move(from);
}
inline BadNestedBook& operator=(const BadNestedBook& from) {
CopyFrom(from);
return *this;
}
inline BadNestedBook& operator=(BadNestedBook&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const BadNestedBook& default_instance();
static inline const BadNestedBook* internal_default_instance() {
return reinterpret_cast<const BadNestedBook*>(
&_BadNestedBook_default_instance_);
}
static constexpr int kIndexInFileMessages =
9;
friend void swap(BadNestedBook& a, BadNestedBook& b) {
a.Swap(&b);
}
inline void Swap(BadNestedBook* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(BadNestedBook* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline BadNestedBook* New() const final {
return CreateMaybeMessage<BadNestedBook>(nullptr);
}
BadNestedBook* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<BadNestedBook>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const BadNestedBook& from);
void MergeFrom(const BadNestedBook& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(BadNestedBook* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.BadNestedBook";
}
protected:
explicit BadNestedBook(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kBookFieldNumber = 1,
};
// repeated uint32 book = 1 [packed = true];
int book_size() const;
private:
int _internal_book_size() const;
public:
void clear_book();
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_book(int index) const;
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
_internal_book() const;
void _internal_add_book(::PROTOBUF_NAMESPACE_ID::uint32 value);
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
_internal_mutable_book();
public:
::PROTOBUF_NAMESPACE_ID::uint32 book(int index) const;
void set_book(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value);
void add_book(::PROTOBUF_NAMESPACE_ID::uint32 value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
book() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
mutable_book();
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.BadNestedBook)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 > book_;
mutable std::atomic<int> _book_cached_byte_size_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class Cyclic PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.Cyclic) */ {
public:
inline Cyclic() : Cyclic(nullptr) {}
virtual ~Cyclic();
Cyclic(const Cyclic& from);
Cyclic(Cyclic&& from) noexcept
: Cyclic() {
*this = ::std::move(from);
}
inline Cyclic& operator=(const Cyclic& from) {
CopyFrom(from);
return *this;
}
inline Cyclic& operator=(Cyclic&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const Cyclic& default_instance();
static inline const Cyclic* internal_default_instance() {
return reinterpret_cast<const Cyclic*>(
&_Cyclic_default_instance_);
}
static constexpr int kIndexInFileMessages =
10;
friend void swap(Cyclic& a, Cyclic& b) {
a.Swap(&b);
}
inline void Swap(Cyclic* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(Cyclic* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline Cyclic* New() const final {
return CreateMaybeMessage<Cyclic>(nullptr);
}
Cyclic* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<Cyclic>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const Cyclic& from);
void MergeFrom(const Cyclic& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Cyclic* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.Cyclic";
}
protected:
explicit Cyclic(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kMAuthorFieldNumber = 5,
kMStrFieldNumber = 2,
kMBookFieldNumber = 3,
kMCyclicFieldNumber = 4,
kMIntFieldNumber = 1,
};
// repeated .proto_util_converter.testing.Author m_author = 5;
int m_author_size() const;
private:
int _internal_m_author_size() const;
public:
void clear_m_author();
::proto_util_converter::testing::Author* mutable_m_author(int index);
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author >*
mutable_m_author();
private:
const ::proto_util_converter::testing::Author& _internal_m_author(int index) const;
::proto_util_converter::testing::Author* _internal_add_m_author();
public:
const ::proto_util_converter::testing::Author& m_author(int index) const;
::proto_util_converter::testing::Author* add_m_author();
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author >&
m_author() const;
// optional string m_str = 2;
bool has_m_str() const;
private:
bool _internal_has_m_str() const;
public:
void clear_m_str();
const std::string& m_str() const;
void set_m_str(const std::string& value);
void set_m_str(std::string&& value);
void set_m_str(const char* value);
void set_m_str(const char* value, size_t size);
std::string* mutable_m_str();
std::string* release_m_str();
void set_allocated_m_str(std::string* m_str);
private:
const std::string& _internal_m_str() const;
void _internal_set_m_str(const std::string& value);
std::string* _internal_mutable_m_str();
public:
// optional .proto_util_converter.testing.Book m_book = 3;
bool has_m_book() const;
private:
bool _internal_has_m_book() const;
public:
void clear_m_book();
const ::proto_util_converter::testing::Book& m_book() const;
::proto_util_converter::testing::Book* release_m_book();
::proto_util_converter::testing::Book* mutable_m_book();
void set_allocated_m_book(::proto_util_converter::testing::Book* m_book);
private:
const ::proto_util_converter::testing::Book& _internal_m_book() const;
::proto_util_converter::testing::Book* _internal_mutable_m_book();
public:
void unsafe_arena_set_allocated_m_book(
::proto_util_converter::testing::Book* m_book);
::proto_util_converter::testing::Book* unsafe_arena_release_m_book();
// optional .proto_util_converter.testing.Cyclic m_cyclic = 4;
bool has_m_cyclic() const;
private:
bool _internal_has_m_cyclic() const;
public:
void clear_m_cyclic();
const ::proto_util_converter::testing::Cyclic& m_cyclic() const;
::proto_util_converter::testing::Cyclic* release_m_cyclic();
::proto_util_converter::testing::Cyclic* mutable_m_cyclic();
void set_allocated_m_cyclic(::proto_util_converter::testing::Cyclic* m_cyclic);
private:
const ::proto_util_converter::testing::Cyclic& _internal_m_cyclic() const;
::proto_util_converter::testing::Cyclic* _internal_mutable_m_cyclic();
public:
void unsafe_arena_set_allocated_m_cyclic(
::proto_util_converter::testing::Cyclic* m_cyclic);
::proto_util_converter::testing::Cyclic* unsafe_arena_release_m_cyclic();
// optional int32 m_int = 1;
bool has_m_int() const;
private:
bool _internal_has_m_int() const;
public:
void clear_m_int();
::PROTOBUF_NAMESPACE_ID::int32 m_int() const;
void set_m_int(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_m_int() const;
void _internal_set_m_int(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.Cyclic)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author > m_author_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr m_str_;
::proto_util_converter::testing::Book* m_book_;
::proto_util_converter::testing::Cyclic* m_cyclic_;
::PROTOBUF_NAMESPACE_ID::int32 m_int_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class TestJsonName1 PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.TestJsonName1) */ {
public:
inline TestJsonName1() : TestJsonName1(nullptr) {}
virtual ~TestJsonName1();
TestJsonName1(const TestJsonName1& from);
TestJsonName1(TestJsonName1&& from) noexcept
: TestJsonName1() {
*this = ::std::move(from);
}
inline TestJsonName1& operator=(const TestJsonName1& from) {
CopyFrom(from);
return *this;
}
inline TestJsonName1& operator=(TestJsonName1&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const TestJsonName1& default_instance();
static inline const TestJsonName1* internal_default_instance() {
return reinterpret_cast<const TestJsonName1*>(
&_TestJsonName1_default_instance_);
}
static constexpr int kIndexInFileMessages =
11;
friend void swap(TestJsonName1& a, TestJsonName1& b) {
a.Swap(&b);
}
inline void Swap(TestJsonName1* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(TestJsonName1* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TestJsonName1* New() const final {
return CreateMaybeMessage<TestJsonName1>(nullptr);
}
TestJsonName1* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TestJsonName1>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const TestJsonName1& from);
void MergeFrom(const TestJsonName1& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(TestJsonName1* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.TestJsonName1";
}
protected:
explicit TestJsonName1(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kOneValueFieldNumber = 1,
};
// optional int32 one_value = 1 [json_name = "value"];
bool has_one_value() const;
private:
bool _internal_has_one_value() const;
public:
void clear_one_value();
::PROTOBUF_NAMESPACE_ID::int32 one_value() const;
void set_one_value(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_one_value() const;
void _internal_set_one_value(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.TestJsonName1)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::int32 one_value_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class TestJsonName2 PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.TestJsonName2) */ {
public:
inline TestJsonName2() : TestJsonName2(nullptr) {}
virtual ~TestJsonName2();
TestJsonName2(const TestJsonName2& from);
TestJsonName2(TestJsonName2&& from) noexcept
: TestJsonName2() {
*this = ::std::move(from);
}
inline TestJsonName2& operator=(const TestJsonName2& from) {
CopyFrom(from);
return *this;
}
inline TestJsonName2& operator=(TestJsonName2&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const TestJsonName2& default_instance();
static inline const TestJsonName2* internal_default_instance() {
return reinterpret_cast<const TestJsonName2*>(
&_TestJsonName2_default_instance_);
}
static constexpr int kIndexInFileMessages =
12;
friend void swap(TestJsonName2& a, TestJsonName2& b) {
a.Swap(&b);
}
inline void Swap(TestJsonName2* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(TestJsonName2* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TestJsonName2* New() const final {
return CreateMaybeMessage<TestJsonName2>(nullptr);
}
TestJsonName2* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TestJsonName2>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const TestJsonName2& from);
void MergeFrom(const TestJsonName2& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(TestJsonName2* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.TestJsonName2";
}
protected:
explicit TestJsonName2(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kAnotherValueFieldNumber = 1,
};
// optional int32 another_value = 1 [json_name = "value"];
bool has_another_value() const;
private:
bool _internal_has_another_value() const;
public:
void clear_another_value();
::PROTOBUF_NAMESPACE_ID::int32 another_value() const;
void set_another_value(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_another_value() const;
void _internal_set_another_value(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.TestJsonName2)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::int32 another_value_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class TestPrimitiveFieldsWithSameJsonName PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName) */ {
public:
inline TestPrimitiveFieldsWithSameJsonName() : TestPrimitiveFieldsWithSameJsonName(nullptr) {}
virtual ~TestPrimitiveFieldsWithSameJsonName();
TestPrimitiveFieldsWithSameJsonName(const TestPrimitiveFieldsWithSameJsonName& from);
TestPrimitiveFieldsWithSameJsonName(TestPrimitiveFieldsWithSameJsonName&& from) noexcept
: TestPrimitiveFieldsWithSameJsonName() {
*this = ::std::move(from);
}
inline TestPrimitiveFieldsWithSameJsonName& operator=(const TestPrimitiveFieldsWithSameJsonName& from) {
CopyFrom(from);
return *this;
}
inline TestPrimitiveFieldsWithSameJsonName& operator=(TestPrimitiveFieldsWithSameJsonName&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const TestPrimitiveFieldsWithSameJsonName& default_instance();
static inline const TestPrimitiveFieldsWithSameJsonName* internal_default_instance() {
return reinterpret_cast<const TestPrimitiveFieldsWithSameJsonName*>(
&_TestPrimitiveFieldsWithSameJsonName_default_instance_);
}
static constexpr int kIndexInFileMessages =
13;
friend void swap(TestPrimitiveFieldsWithSameJsonName& a, TestPrimitiveFieldsWithSameJsonName& b) {
a.Swap(&b);
}
inline void Swap(TestPrimitiveFieldsWithSameJsonName* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(TestPrimitiveFieldsWithSameJsonName* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TestPrimitiveFieldsWithSameJsonName* New() const final {
return CreateMaybeMessage<TestPrimitiveFieldsWithSameJsonName>(nullptr);
}
TestPrimitiveFieldsWithSameJsonName* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TestPrimitiveFieldsWithSameJsonName>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const TestPrimitiveFieldsWithSameJsonName& from);
void MergeFrom(const TestPrimitiveFieldsWithSameJsonName& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(TestPrimitiveFieldsWithSameJsonName* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName";
}
protected:
explicit TestPrimitiveFieldsWithSameJsonName(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kValStr1FieldNumber = 1,
kValStr1FieldNumber_2 = 2,
kValInt321FieldNumber = 3,
kValInt321FieldNumber_4 = 4,
kValUint321FieldNumber = 5,
kValUint321FieldNumber_6 = 6,
kValInt641FieldNumber = 7,
kValInt641FieldNumber_8 = 8,
kValUint641FieldNumber = 9,
kValUint641FieldNumber_10 = 10,
kValBool1FieldNumber = 11,
kValBool1FieldNumber_12 = 12,
kValFloat1FieldNumber = 15,
kValDouble1FieldNumber = 13,
kValDouble1FieldNumber_14 = 14,
kValFloat1FieldNumber_16 = 16,
};
// optional string val_str1 = 1;
bool has_val_str1() const;
private:
bool _internal_has_val_str1() const;
public:
void clear_val_str1();
const std::string& val_str1() const;
void set_val_str1(const std::string& value);
void set_val_str1(std::string&& value);
void set_val_str1(const char* value);
void set_val_str1(const char* value, size_t size);
std::string* mutable_val_str1();
std::string* release_val_str1();
void set_allocated_val_str1(std::string* val_str1);
private:
const std::string& _internal_val_str1() const;
void _internal_set_val_str1(const std::string& value);
std::string* _internal_mutable_val_str1();
public:
// optional string val_str_1 = 2;
bool has_val_str_1() const;
private:
bool _internal_has_val_str_1() const;
public:
void clear_val_str_1();
const std::string& val_str_1() const;
void set_val_str_1(const std::string& value);
void set_val_str_1(std::string&& value);
void set_val_str_1(const char* value);
void set_val_str_1(const char* value, size_t size);
std::string* mutable_val_str_1();
std::string* release_val_str_1();
void set_allocated_val_str_1(std::string* val_str_1);
private:
const std::string& _internal_val_str_1() const;
void _internal_set_val_str_1(const std::string& value);
std::string* _internal_mutable_val_str_1();
public:
// optional int32 val_int321 = 3;
bool has_val_int321() const;
private:
bool _internal_has_val_int321() const;
public:
void clear_val_int321();
::PROTOBUF_NAMESPACE_ID::int32 val_int321() const;
void set_val_int321(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_val_int321() const;
void _internal_set_val_int321(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// optional int32 val_int32_1 = 4;
bool has_val_int32_1() const;
private:
bool _internal_has_val_int32_1() const;
public:
void clear_val_int32_1();
::PROTOBUF_NAMESPACE_ID::int32 val_int32_1() const;
void set_val_int32_1(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_val_int32_1() const;
void _internal_set_val_int32_1(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// optional uint32 val_uint321 = 5;
bool has_val_uint321() const;
private:
bool _internal_has_val_uint321() const;
public:
void clear_val_uint321();
::PROTOBUF_NAMESPACE_ID::uint32 val_uint321() const;
void set_val_uint321(::PROTOBUF_NAMESPACE_ID::uint32 value);
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_val_uint321() const;
void _internal_set_val_uint321(::PROTOBUF_NAMESPACE_ID::uint32 value);
public:
// optional uint32 val_uint32_1 = 6;
bool has_val_uint32_1() const;
private:
bool _internal_has_val_uint32_1() const;
public:
void clear_val_uint32_1();
::PROTOBUF_NAMESPACE_ID::uint32 val_uint32_1() const;
void set_val_uint32_1(::PROTOBUF_NAMESPACE_ID::uint32 value);
private:
::PROTOBUF_NAMESPACE_ID::uint32 _internal_val_uint32_1() const;
void _internal_set_val_uint32_1(::PROTOBUF_NAMESPACE_ID::uint32 value);
public:
// optional int64 val_int641 = 7;
bool has_val_int641() const;
private:
bool _internal_has_val_int641() const;
public:
void clear_val_int641();
::PROTOBUF_NAMESPACE_ID::int64 val_int641() const;
void set_val_int641(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_val_int641() const;
void _internal_set_val_int641(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional int64 val_int64_1 = 8;
bool has_val_int64_1() const;
private:
bool _internal_has_val_int64_1() const;
public:
void clear_val_int64_1();
::PROTOBUF_NAMESPACE_ID::int64 val_int64_1() const;
void set_val_int64_1(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_val_int64_1() const;
void _internal_set_val_int64_1(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional uint64 val_uint641 = 9;
bool has_val_uint641() const;
private:
bool _internal_has_val_uint641() const;
public:
void clear_val_uint641();
::PROTOBUF_NAMESPACE_ID::uint64 val_uint641() const;
void set_val_uint641(::PROTOBUF_NAMESPACE_ID::uint64 value);
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_val_uint641() const;
void _internal_set_val_uint641(::PROTOBUF_NAMESPACE_ID::uint64 value);
public:
// optional uint64 val_uint64_1 = 10;
bool has_val_uint64_1() const;
private:
bool _internal_has_val_uint64_1() const;
public:
void clear_val_uint64_1();
::PROTOBUF_NAMESPACE_ID::uint64 val_uint64_1() const;
void set_val_uint64_1(::PROTOBUF_NAMESPACE_ID::uint64 value);
private:
::PROTOBUF_NAMESPACE_ID::uint64 _internal_val_uint64_1() const;
void _internal_set_val_uint64_1(::PROTOBUF_NAMESPACE_ID::uint64 value);
public:
// optional bool val_bool1 = 11;
bool has_val_bool1() const;
private:
bool _internal_has_val_bool1() const;
public:
void clear_val_bool1();
bool val_bool1() const;
void set_val_bool1(bool value);
private:
bool _internal_val_bool1() const;
void _internal_set_val_bool1(bool value);
public:
// optional bool val_bool_1 = 12;
bool has_val_bool_1() const;
private:
bool _internal_has_val_bool_1() const;
public:
void clear_val_bool_1();
bool val_bool_1() const;
void set_val_bool_1(bool value);
private:
bool _internal_val_bool_1() const;
void _internal_set_val_bool_1(bool value);
public:
// optional float val_float1 = 15;
bool has_val_float1() const;
private:
bool _internal_has_val_float1() const;
public:
void clear_val_float1();
float val_float1() const;
void set_val_float1(float value);
private:
float _internal_val_float1() const;
void _internal_set_val_float1(float value);
public:
// optional double val_double1 = 13;
bool has_val_double1() const;
private:
bool _internal_has_val_double1() const;
public:
void clear_val_double1();
double val_double1() const;
void set_val_double1(double value);
private:
double _internal_val_double1() const;
void _internal_set_val_double1(double value);
public:
// optional double val_double_1 = 14;
bool has_val_double_1() const;
private:
bool _internal_has_val_double_1() const;
public:
void clear_val_double_1();
double val_double_1() const;
void set_val_double_1(double value);
private:
double _internal_val_double_1() const;
void _internal_set_val_double_1(double value);
public:
// optional float val_float_1 = 16;
bool has_val_float_1() const;
private:
bool _internal_has_val_float_1() const;
public:
void clear_val_float_1();
float val_float_1() const;
void set_val_float_1(float value);
private:
float _internal_val_float_1() const;
void _internal_set_val_float_1(float value);
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr val_str1_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr val_str_1_;
::PROTOBUF_NAMESPACE_ID::int32 val_int321_;
::PROTOBUF_NAMESPACE_ID::int32 val_int32_1_;
::PROTOBUF_NAMESPACE_ID::uint32 val_uint321_;
::PROTOBUF_NAMESPACE_ID::uint32 val_uint32_1_;
::PROTOBUF_NAMESPACE_ID::int64 val_int641_;
::PROTOBUF_NAMESPACE_ID::int64 val_int64_1_;
::PROTOBUF_NAMESPACE_ID::uint64 val_uint641_;
::PROTOBUF_NAMESPACE_ID::uint64 val_uint64_1_;
bool val_bool1_;
bool val_bool_1_;
float val_float1_;
double val_double1_;
double val_double_1_;
float val_float_1_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class TestRepeatedFieldsWithSameJsonName PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName) */ {
public:
inline TestRepeatedFieldsWithSameJsonName() : TestRepeatedFieldsWithSameJsonName(nullptr) {}
virtual ~TestRepeatedFieldsWithSameJsonName();
TestRepeatedFieldsWithSameJsonName(const TestRepeatedFieldsWithSameJsonName& from);
TestRepeatedFieldsWithSameJsonName(TestRepeatedFieldsWithSameJsonName&& from) noexcept
: TestRepeatedFieldsWithSameJsonName() {
*this = ::std::move(from);
}
inline TestRepeatedFieldsWithSameJsonName& operator=(const TestRepeatedFieldsWithSameJsonName& from) {
CopyFrom(from);
return *this;
}
inline TestRepeatedFieldsWithSameJsonName& operator=(TestRepeatedFieldsWithSameJsonName&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const TestRepeatedFieldsWithSameJsonName& default_instance();
static inline const TestRepeatedFieldsWithSameJsonName* internal_default_instance() {
return reinterpret_cast<const TestRepeatedFieldsWithSameJsonName*>(
&_TestRepeatedFieldsWithSameJsonName_default_instance_);
}
static constexpr int kIndexInFileMessages =
14;
friend void swap(TestRepeatedFieldsWithSameJsonName& a, TestRepeatedFieldsWithSameJsonName& b) {
a.Swap(&b);
}
inline void Swap(TestRepeatedFieldsWithSameJsonName* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(TestRepeatedFieldsWithSameJsonName* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TestRepeatedFieldsWithSameJsonName* New() const final {
return CreateMaybeMessage<TestRepeatedFieldsWithSameJsonName>(nullptr);
}
TestRepeatedFieldsWithSameJsonName* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TestRepeatedFieldsWithSameJsonName>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const TestRepeatedFieldsWithSameJsonName& from);
void MergeFrom(const TestRepeatedFieldsWithSameJsonName& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(TestRepeatedFieldsWithSameJsonName* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName";
}
protected:
explicit TestRepeatedFieldsWithSameJsonName(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kRepStr1FieldNumber = 1,
kRepStr1FieldNumber_2 = 2,
};
// repeated string rep_str1 = 1;
int rep_str1_size() const;
private:
int _internal_rep_str1_size() const;
public:
void clear_rep_str1();
const std::string& rep_str1(int index) const;
std::string* mutable_rep_str1(int index);
void set_rep_str1(int index, const std::string& value);
void set_rep_str1(int index, std::string&& value);
void set_rep_str1(int index, const char* value);
void set_rep_str1(int index, const char* value, size_t size);
std::string* add_rep_str1();
void add_rep_str1(const std::string& value);
void add_rep_str1(std::string&& value);
void add_rep_str1(const char* value);
void add_rep_str1(const char* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& rep_str1() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_rep_str1();
private:
const std::string& _internal_rep_str1(int index) const;
std::string* _internal_add_rep_str1();
public:
// repeated string rep_str_1 = 2;
int rep_str_1_size() const;
private:
int _internal_rep_str_1_size() const;
public:
void clear_rep_str_1();
const std::string& rep_str_1(int index) const;
std::string* mutable_rep_str_1(int index);
void set_rep_str_1(int index, const std::string& value);
void set_rep_str_1(int index, std::string&& value);
void set_rep_str_1(int index, const char* value);
void set_rep_str_1(int index, const char* value, size_t size);
std::string* add_rep_str_1();
void add_rep_str_1(const std::string& value);
void add_rep_str_1(std::string&& value);
void add_rep_str_1(const char* value);
void add_rep_str_1(const char* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& rep_str_1() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_rep_str_1();
private:
const std::string& _internal_rep_str_1(int index) const;
std::string* _internal_add_rep_str_1();
public:
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> rep_str1_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> rep_str_1_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// -------------------------------------------------------------------
class TestMessageFieldsWithSameJsonName PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:proto_util_converter.testing.TestMessageFieldsWithSameJsonName) */ {
public:
inline TestMessageFieldsWithSameJsonName() : TestMessageFieldsWithSameJsonName(nullptr) {}
virtual ~TestMessageFieldsWithSameJsonName();
TestMessageFieldsWithSameJsonName(const TestMessageFieldsWithSameJsonName& from);
TestMessageFieldsWithSameJsonName(TestMessageFieldsWithSameJsonName&& from) noexcept
: TestMessageFieldsWithSameJsonName() {
*this = ::std::move(from);
}
inline TestMessageFieldsWithSameJsonName& operator=(const TestMessageFieldsWithSameJsonName& from) {
CopyFrom(from);
return *this;
}
inline TestMessageFieldsWithSameJsonName& operator=(TestMessageFieldsWithSameJsonName&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const TestMessageFieldsWithSameJsonName& default_instance();
static inline const TestMessageFieldsWithSameJsonName* internal_default_instance() {
return reinterpret_cast<const TestMessageFieldsWithSameJsonName*>(
&_TestMessageFieldsWithSameJsonName_default_instance_);
}
static constexpr int kIndexInFileMessages =
15;
friend void swap(TestMessageFieldsWithSameJsonName& a, TestMessageFieldsWithSameJsonName& b) {
a.Swap(&b);
}
inline void Swap(TestMessageFieldsWithSameJsonName* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(TestMessageFieldsWithSameJsonName* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline TestMessageFieldsWithSameJsonName* New() const final {
return CreateMaybeMessage<TestMessageFieldsWithSameJsonName>(nullptr);
}
TestMessageFieldsWithSameJsonName* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<TestMessageFieldsWithSameJsonName>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const TestMessageFieldsWithSameJsonName& from);
void MergeFrom(const TestMessageFieldsWithSameJsonName& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(TestMessageFieldsWithSameJsonName* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "proto_util_converter.testing.TestMessageFieldsWithSameJsonName";
}
protected:
explicit TestMessageFieldsWithSameJsonName(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto);
return ::descriptor_table_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kPrim1FieldNumber = 1,
kPrim1FieldNumber_2 = 2,
};
// optional .proto_util_converter.testing.Primitive prim1 = 1;
bool has_prim1() const;
private:
bool _internal_has_prim1() const;
public:
void clear_prim1();
const ::proto_util_converter::testing::Primitive& prim1() const;
::proto_util_converter::testing::Primitive* release_prim1();
::proto_util_converter::testing::Primitive* mutable_prim1();
void set_allocated_prim1(::proto_util_converter::testing::Primitive* prim1);
private:
const ::proto_util_converter::testing::Primitive& _internal_prim1() const;
::proto_util_converter::testing::Primitive* _internal_mutable_prim1();
public:
void unsafe_arena_set_allocated_prim1(
::proto_util_converter::testing::Primitive* prim1);
::proto_util_converter::testing::Primitive* unsafe_arena_release_prim1();
// optional .proto_util_converter.testing.Primitive prim_1 = 2;
bool has_prim_1() const;
private:
bool _internal_has_prim_1() const;
public:
void clear_prim_1();
const ::proto_util_converter::testing::Primitive& prim_1() const;
::proto_util_converter::testing::Primitive* release_prim_1();
::proto_util_converter::testing::Primitive* mutable_prim_1();
void set_allocated_prim_1(::proto_util_converter::testing::Primitive* prim_1);
private:
const ::proto_util_converter::testing::Primitive& _internal_prim_1() const;
::proto_util_converter::testing::Primitive* _internal_mutable_prim_1();
public:
void unsafe_arena_set_allocated_prim_1(
::proto_util_converter::testing::Primitive* prim_1);
::proto_util_converter::testing::Primitive* unsafe_arena_release_prim_1();
// @@protoc_insertion_point(class_scope:proto_util_converter.testing.TestMessageFieldsWithSameJsonName)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::proto_util_converter::testing::Primitive* prim1_;
::proto_util_converter::testing::Primitive* prim_1_;
friend struct ::TableStruct_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto;
};
// ===================================================================
static const int kMoreAuthorFieldNumber = 201;
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::proto_util_converter::testing::Book,
::PROTOBUF_NAMESPACE_ID::internal::RepeatedMessageTypeTraits< ::proto_util_converter::testing::Author >, 11, false >
more_author;
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// Book_Data
// optional uint32 year = 7;
inline bool Book_Data::_internal_has_year() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool Book_Data::has_year() const {
return _internal_has_year();
}
inline void Book_Data::clear_year() {
year_ = 0u;
_has_bits_[0] &= ~0x00000002u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Book_Data::_internal_year() const {
return year_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Book_Data::year() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.Data.year)
return _internal_year();
}
inline void Book_Data::_internal_set_year(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000002u;
year_ = value;
}
inline void Book_Data::set_year(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_set_year(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.Data.year)
}
// optional string copyright = 8;
inline bool Book_Data::_internal_has_copyright() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool Book_Data::has_copyright() const {
return _internal_has_copyright();
}
inline void Book_Data::clear_copyright() {
copyright_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& Book_Data::copyright() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.Data.copyright)
return _internal_copyright();
}
inline void Book_Data::set_copyright(const std::string& value) {
_internal_set_copyright(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.Data.copyright)
}
inline std::string* Book_Data::mutable_copyright() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.Data.copyright)
return _internal_mutable_copyright();
}
inline const std::string& Book_Data::_internal_copyright() const {
return copyright_.Get();
}
inline void Book_Data::_internal_set_copyright(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
copyright_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Book_Data::set_copyright(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
copyright_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Book.Data.copyright)
}
inline void Book_Data::set_copyright(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
copyright_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Book.Data.copyright)
}
inline void Book_Data::set_copyright(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
copyright_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Book.Data.copyright)
}
inline std::string* Book_Data::_internal_mutable_copyright() {
_has_bits_[0] |= 0x00000001u;
return copyright_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Book_Data::release_copyright() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.Data.copyright)
if (!_internal_has_copyright()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return copyright_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Book_Data::set_allocated_copyright(std::string* copyright) {
if (copyright != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
copyright_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), copyright,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.Data.copyright)
}
// -------------------------------------------------------------------
// Book_Label
// optional string key = 1;
inline bool Book_Label::_internal_has_key() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool Book_Label::has_key() const {
return _internal_has_key();
}
inline void Book_Label::clear_key() {
key_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& Book_Label::key() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.Label.key)
return _internal_key();
}
inline void Book_Label::set_key(const std::string& value) {
_internal_set_key(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.Label.key)
}
inline std::string* Book_Label::mutable_key() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.Label.key)
return _internal_mutable_key();
}
inline const std::string& Book_Label::_internal_key() const {
return key_.Get();
}
inline void Book_Label::_internal_set_key(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
key_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Book_Label::set_key(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
key_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Book.Label.key)
}
inline void Book_Label::set_key(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
key_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Book.Label.key)
}
inline void Book_Label::set_key(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
key_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Book.Label.key)
}
inline std::string* Book_Label::_internal_mutable_key() {
_has_bits_[0] |= 0x00000001u;
return key_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Book_Label::release_key() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.Label.key)
if (!_internal_has_key()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return key_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Book_Label::set_allocated_key(std::string* key) {
if (key != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
key_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), key,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.Label.key)
}
// optional string value = 2;
inline bool Book_Label::_internal_has_value() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool Book_Label::has_value() const {
return _internal_has_value();
}
inline void Book_Label::clear_value() {
value_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& Book_Label::value() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.Label.value)
return _internal_value();
}
inline void Book_Label::set_value(const std::string& value) {
_internal_set_value(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.Label.value)
}
inline std::string* Book_Label::mutable_value() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.Label.value)
return _internal_mutable_value();
}
inline const std::string& Book_Label::_internal_value() const {
return value_.Get();
}
inline void Book_Label::_internal_set_value(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
value_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Book_Label::set_value(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
value_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Book.Label.value)
}
inline void Book_Label::set_value(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
value_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Book.Label.value)
}
inline void Book_Label::set_value(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
value_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Book.Label.value)
}
inline std::string* Book_Label::_internal_mutable_value() {
_has_bits_[0] |= 0x00000002u;
return value_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Book_Label::release_value() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.Label.value)
if (!_internal_has_value()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return value_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Book_Label::set_allocated_value(std::string* value) {
if (value != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.Label.value)
}
// -------------------------------------------------------------------
// Book
// optional string title = 1;
inline bool Book::_internal_has_title() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool Book::has_title() const {
return _internal_has_title();
}
inline void Book::clear_title() {
title_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& Book::title() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.title)
return _internal_title();
}
inline void Book::set_title(const std::string& value) {
_internal_set_title(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.title)
}
inline std::string* Book::mutable_title() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.title)
return _internal_mutable_title();
}
inline const std::string& Book::_internal_title() const {
return title_.Get();
}
inline void Book::_internal_set_title(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
title_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Book::set_title(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
title_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Book.title)
}
inline void Book::set_title(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
title_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Book.title)
}
inline void Book::set_title(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
title_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Book.title)
}
inline std::string* Book::_internal_mutable_title() {
_has_bits_[0] |= 0x00000001u;
return title_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Book::release_title() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.title)
if (!_internal_has_title()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return title_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Book::set_allocated_title(std::string* title) {
if (title != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
title_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), title,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.title)
}
// optional .proto_util_converter.testing.Author author = 2;
inline bool Book::_internal_has_author() const {
bool value = (_has_bits_[0] & 0x00000008u) != 0;
PROTOBUF_ASSUME(!value || author_ != nullptr);
return value;
}
inline bool Book::has_author() const {
return _internal_has_author();
}
inline void Book::clear_author() {
if (author_ != nullptr) author_->Clear();
_has_bits_[0] &= ~0x00000008u;
}
inline const ::proto_util_converter::testing::Author& Book::_internal_author() const {
const ::proto_util_converter::testing::Author* p = author_;
return p != nullptr ? *p : reinterpret_cast<const ::proto_util_converter::testing::Author&>(
::proto_util_converter::testing::_Author_default_instance_);
}
inline const ::proto_util_converter::testing::Author& Book::author() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.author)
return _internal_author();
}
inline void Book::unsafe_arena_set_allocated_author(
::proto_util_converter::testing::Author* author) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(author_);
}
author_ = author;
if (author) {
_has_bits_[0] |= 0x00000008u;
} else {
_has_bits_[0] &= ~0x00000008u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:proto_util_converter.testing.Book.author)
}
inline ::proto_util_converter::testing::Author* Book::release_author() {
_has_bits_[0] &= ~0x00000008u;
::proto_util_converter::testing::Author* temp = author_;
author_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::proto_util_converter::testing::Author* Book::unsafe_arena_release_author() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.author)
_has_bits_[0] &= ~0x00000008u;
::proto_util_converter::testing::Author* temp = author_;
author_ = nullptr;
return temp;
}
inline ::proto_util_converter::testing::Author* Book::_internal_mutable_author() {
_has_bits_[0] |= 0x00000008u;
if (author_ == nullptr) {
auto* p = CreateMaybeMessage<::proto_util_converter::testing::Author>(GetArena());
author_ = p;
}
return author_;
}
inline ::proto_util_converter::testing::Author* Book::mutable_author() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.author)
return _internal_mutable_author();
}
inline void Book::set_allocated_author(::proto_util_converter::testing::Author* author) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete author_;
}
if (author) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(author);
if (message_arena != submessage_arena) {
author = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, author, submessage_arena);
}
_has_bits_[0] |= 0x00000008u;
} else {
_has_bits_[0] &= ~0x00000008u;
}
author_ = author;
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.author)
}
// optional uint32 length = 3;
inline bool Book::_internal_has_length() const {
bool value = (_has_bits_[0] & 0x00000100u) != 0;
return value;
}
inline bool Book::has_length() const {
return _internal_has_length();
}
inline void Book::clear_length() {
length_ = 0u;
_has_bits_[0] &= ~0x00000100u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Book::_internal_length() const {
return length_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Book::length() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.length)
return _internal_length();
}
inline void Book::_internal_set_length(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000100u;
length_ = value;
}
inline void Book::set_length(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_set_length(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.length)
}
// optional int64 published = 4;
inline bool Book::_internal_has_published() const {
bool value = (_has_bits_[0] & 0x00000080u) != 0;
return value;
}
inline bool Book::has_published() const {
return _internal_has_published();
}
inline void Book::clear_published() {
published_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00000080u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Book::_internal_published() const {
return published_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Book::published() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.published)
return _internal_published();
}
inline void Book::_internal_set_published(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000080u;
published_ = value;
}
inline void Book::set_published(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_published(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.published)
}
// optional bytes content = 5;
inline bool Book::_internal_has_content() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool Book::has_content() const {
return _internal_has_content();
}
inline void Book::clear_content() {
content_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& Book::content() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.content)
return _internal_content();
}
inline void Book::set_content(const std::string& value) {
_internal_set_content(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.content)
}
inline std::string* Book::mutable_content() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.content)
return _internal_mutable_content();
}
inline const std::string& Book::_internal_content() const {
return content_.Get();
}
inline void Book::_internal_set_content(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
content_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Book::set_content(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
content_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Book.content)
}
inline void Book::set_content(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
content_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Book.content)
}
inline void Book::set_content(const void* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
content_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Book.content)
}
inline std::string* Book::_internal_mutable_content() {
_has_bits_[0] |= 0x00000002u;
return content_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Book::release_content() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.content)
if (!_internal_has_content()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return content_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Book::set_allocated_content(std::string* content) {
if (content != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
content_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), content,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.content)
}
// optional group Data = 6 { ... };
inline bool Book::_internal_has_data() const {
bool value = (_has_bits_[0] & 0x00000010u) != 0;
PROTOBUF_ASSUME(!value || data_ != nullptr);
return value;
}
inline bool Book::has_data() const {
return _internal_has_data();
}
inline void Book::clear_data() {
if (data_ != nullptr) data_->Clear();
_has_bits_[0] &= ~0x00000010u;
}
inline const ::proto_util_converter::testing::Book_Data& Book::_internal_data() const {
const ::proto_util_converter::testing::Book_Data* p = data_;
return p != nullptr ? *p : reinterpret_cast<const ::proto_util_converter::testing::Book_Data&>(
::proto_util_converter::testing::_Book_Data_default_instance_);
}
inline const ::proto_util_converter::testing::Book_Data& Book::data() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.data)
return _internal_data();
}
inline void Book::unsafe_arena_set_allocated_data(
::proto_util_converter::testing::Book_Data* data) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(data_);
}
data_ = data;
if (data) {
_has_bits_[0] |= 0x00000010u;
} else {
_has_bits_[0] &= ~0x00000010u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:proto_util_converter.testing.Book.data)
}
inline ::proto_util_converter::testing::Book_Data* Book::release_data() {
_has_bits_[0] &= ~0x00000010u;
::proto_util_converter::testing::Book_Data* temp = data_;
data_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::proto_util_converter::testing::Book_Data* Book::unsafe_arena_release_data() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.data)
_has_bits_[0] &= ~0x00000010u;
::proto_util_converter::testing::Book_Data* temp = data_;
data_ = nullptr;
return temp;
}
inline ::proto_util_converter::testing::Book_Data* Book::_internal_mutable_data() {
_has_bits_[0] |= 0x00000010u;
if (data_ == nullptr) {
auto* p = CreateMaybeMessage<::proto_util_converter::testing::Book_Data>(GetArena());
data_ = p;
}
return data_;
}
inline ::proto_util_converter::testing::Book_Data* Book::mutable_data() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.data)
return _internal_mutable_data();
}
inline void Book::set_allocated_data(::proto_util_converter::testing::Book_Data* data) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete data_;
}
if (data) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(data);
if (message_arena != submessage_arena) {
data = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, data, submessage_arena);
}
_has_bits_[0] |= 0x00000010u;
} else {
_has_bits_[0] &= ~0x00000010u;
}
data_ = data;
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.data)
}
// optional .proto_util_converter.testing.Publisher publisher = 9;
inline bool Book::_internal_has_publisher() const {
bool value = (_has_bits_[0] & 0x00000020u) != 0;
PROTOBUF_ASSUME(!value || publisher_ != nullptr);
return value;
}
inline bool Book::has_publisher() const {
return _internal_has_publisher();
}
inline void Book::clear_publisher() {
if (publisher_ != nullptr) publisher_->Clear();
_has_bits_[0] &= ~0x00000020u;
}
inline const ::proto_util_converter::testing::Publisher& Book::_internal_publisher() const {
const ::proto_util_converter::testing::Publisher* p = publisher_;
return p != nullptr ? *p : reinterpret_cast<const ::proto_util_converter::testing::Publisher&>(
::proto_util_converter::testing::_Publisher_default_instance_);
}
inline const ::proto_util_converter::testing::Publisher& Book::publisher() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.publisher)
return _internal_publisher();
}
inline void Book::unsafe_arena_set_allocated_publisher(
::proto_util_converter::testing::Publisher* publisher) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(publisher_);
}
publisher_ = publisher;
if (publisher) {
_has_bits_[0] |= 0x00000020u;
} else {
_has_bits_[0] &= ~0x00000020u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:proto_util_converter.testing.Book.publisher)
}
inline ::proto_util_converter::testing::Publisher* Book::release_publisher() {
_has_bits_[0] &= ~0x00000020u;
::proto_util_converter::testing::Publisher* temp = publisher_;
publisher_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::proto_util_converter::testing::Publisher* Book::unsafe_arena_release_publisher() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.publisher)
_has_bits_[0] &= ~0x00000020u;
::proto_util_converter::testing::Publisher* temp = publisher_;
publisher_ = nullptr;
return temp;
}
inline ::proto_util_converter::testing::Publisher* Book::_internal_mutable_publisher() {
_has_bits_[0] |= 0x00000020u;
if (publisher_ == nullptr) {
auto* p = CreateMaybeMessage<::proto_util_converter::testing::Publisher>(GetArena());
publisher_ = p;
}
return publisher_;
}
inline ::proto_util_converter::testing::Publisher* Book::mutable_publisher() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.publisher)
return _internal_mutable_publisher();
}
inline void Book::set_allocated_publisher(::proto_util_converter::testing::Publisher* publisher) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete publisher_;
}
if (publisher) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(publisher);
if (message_arena != submessage_arena) {
publisher = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, publisher, submessage_arena);
}
_has_bits_[0] |= 0x00000020u;
} else {
_has_bits_[0] &= ~0x00000020u;
}
publisher_ = publisher;
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.publisher)
}
// repeated .proto_util_converter.testing.Book.Label labels = 10;
inline int Book::_internal_labels_size() const {
return labels_.size();
}
inline int Book::labels_size() const {
return _internal_labels_size();
}
inline void Book::clear_labels() {
labels_.Clear();
}
inline ::proto_util_converter::testing::Book_Label* Book::mutable_labels(int index) {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.labels)
return labels_.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Book_Label >*
Book::mutable_labels() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Book.labels)
return &labels_;
}
inline const ::proto_util_converter::testing::Book_Label& Book::_internal_labels(int index) const {
return labels_.Get(index);
}
inline const ::proto_util_converter::testing::Book_Label& Book::labels(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.labels)
return _internal_labels(index);
}
inline ::proto_util_converter::testing::Book_Label* Book::_internal_add_labels() {
return labels_.Add();
}
inline ::proto_util_converter::testing::Book_Label* Book::add_labels() {
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Book.labels)
return _internal_add_labels();
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Book_Label >&
Book::labels() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Book.labels)
return labels_;
}
// optional .proto_util_converter.testing.Book.Type type = 11;
inline bool Book::_internal_has_type() const {
bool value = (_has_bits_[0] & 0x00000200u) != 0;
return value;
}
inline bool Book::has_type() const {
return _internal_has_type();
}
inline void Book::clear_type() {
type_ = 1;
_has_bits_[0] &= ~0x00000200u;
}
inline ::proto_util_converter::testing::Book_Type Book::_internal_type() const {
return static_cast< ::proto_util_converter::testing::Book_Type >(type_);
}
inline ::proto_util_converter::testing::Book_Type Book::type() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.type)
return _internal_type();
}
inline void Book::_internal_set_type(::proto_util_converter::testing::Book_Type value) {
assert(::proto_util_converter::testing::Book_Type_IsValid(value));
_has_bits_[0] |= 0x00000200u;
type_ = value;
}
inline void Book::set_type(::proto_util_converter::testing::Book_Type value) {
_internal_set_type(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.type)
}
// optional string snake_field = 12;
inline bool Book::_internal_has_snake_field() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
return value;
}
inline bool Book::has_snake_field() const {
return _internal_has_snake_field();
}
inline void Book::clear_snake_field() {
snake_field_.ClearToEmpty();
_has_bits_[0] &= ~0x00000004u;
}
inline const std::string& Book::snake_field() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.snake_field)
return _internal_snake_field();
}
inline void Book::set_snake_field(const std::string& value) {
_internal_set_snake_field(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.snake_field)
}
inline std::string* Book::mutable_snake_field() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.snake_field)
return _internal_mutable_snake_field();
}
inline const std::string& Book::_internal_snake_field() const {
return snake_field_.Get();
}
inline void Book::_internal_set_snake_field(const std::string& value) {
_has_bits_[0] |= 0x00000004u;
snake_field_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Book::set_snake_field(std::string&& value) {
_has_bits_[0] |= 0x00000004u;
snake_field_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Book.snake_field)
}
inline void Book::set_snake_field(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000004u;
snake_field_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Book.snake_field)
}
inline void Book::set_snake_field(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000004u;
snake_field_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Book.snake_field)
}
inline std::string* Book::_internal_mutable_snake_field() {
_has_bits_[0] |= 0x00000004u;
return snake_field_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Book::release_snake_field() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.snake_field)
if (!_internal_has_snake_field()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000004u;
return snake_field_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Book::set_allocated_snake_field(std::string* snake_field) {
if (snake_field != nullptr) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
snake_field_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), snake_field,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.snake_field)
}
// optional .proto_util_converter.testing.AnyWrapper type_not_found = 13;
inline bool Book::_internal_has_type_not_found() const {
bool value = (_has_bits_[0] & 0x00000040u) != 0;
PROTOBUF_ASSUME(!value || type_not_found_ != nullptr);
return value;
}
inline bool Book::has_type_not_found() const {
return _internal_has_type_not_found();
}
inline const ::proto_util_converter::testing::AnyWrapper& Book::_internal_type_not_found() const {
const ::proto_util_converter::testing::AnyWrapper* p = type_not_found_;
return p != nullptr ? *p : reinterpret_cast<const ::proto_util_converter::testing::AnyWrapper&>(
::proto_util_converter::testing::_AnyWrapper_default_instance_);
}
inline const ::proto_util_converter::testing::AnyWrapper& Book::type_not_found() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.type_not_found)
return _internal_type_not_found();
}
inline void Book::unsafe_arena_set_allocated_type_not_found(
::proto_util_converter::testing::AnyWrapper* type_not_found) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(type_not_found_);
}
type_not_found_ = type_not_found;
if (type_not_found) {
_has_bits_[0] |= 0x00000040u;
} else {
_has_bits_[0] &= ~0x00000040u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:proto_util_converter.testing.Book.type_not_found)
}
inline ::proto_util_converter::testing::AnyWrapper* Book::release_type_not_found() {
_has_bits_[0] &= ~0x00000040u;
::proto_util_converter::testing::AnyWrapper* temp = type_not_found_;
type_not_found_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::proto_util_converter::testing::AnyWrapper* Book::unsafe_arena_release_type_not_found() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Book.type_not_found)
_has_bits_[0] &= ~0x00000040u;
::proto_util_converter::testing::AnyWrapper* temp = type_not_found_;
type_not_found_ = nullptr;
return temp;
}
inline ::proto_util_converter::testing::AnyWrapper* Book::_internal_mutable_type_not_found() {
_has_bits_[0] |= 0x00000040u;
if (type_not_found_ == nullptr) {
auto* p = CreateMaybeMessage<::proto_util_converter::testing::AnyWrapper>(GetArena());
type_not_found_ = p;
}
return type_not_found_;
}
inline ::proto_util_converter::testing::AnyWrapper* Book::mutable_type_not_found() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Book.type_not_found)
return _internal_mutable_type_not_found();
}
inline void Book::set_allocated_type_not_found(::proto_util_converter::testing::AnyWrapper* type_not_found) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(type_not_found_);
}
if (type_not_found) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(type_not_found)->GetArena();
if (message_arena != submessage_arena) {
type_not_found = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, type_not_found, submessage_arena);
}
_has_bits_[0] |= 0x00000040u;
} else {
_has_bits_[0] &= ~0x00000040u;
}
type_not_found_ = type_not_found;
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Book.type_not_found)
}
// repeated int32 primitive_repeated = 14;
inline int Book::_internal_primitive_repeated_size() const {
return primitive_repeated_.size();
}
inline int Book::primitive_repeated_size() const {
return _internal_primitive_repeated_size();
}
inline void Book::clear_primitive_repeated() {
primitive_repeated_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Book::_internal_primitive_repeated(int index) const {
return primitive_repeated_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Book::primitive_repeated(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Book.primitive_repeated)
return _internal_primitive_repeated(index);
}
inline void Book::set_primitive_repeated(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) {
primitive_repeated_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Book.primitive_repeated)
}
inline void Book::_internal_add_primitive_repeated(::PROTOBUF_NAMESPACE_ID::int32 value) {
primitive_repeated_.Add(value);
}
inline void Book::add_primitive_repeated(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_add_primitive_repeated(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Book.primitive_repeated)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
Book::_internal_primitive_repeated() const {
return primitive_repeated_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
Book::primitive_repeated() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Book.primitive_repeated)
return _internal_primitive_repeated();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
Book::_internal_mutable_primitive_repeated() {
return &primitive_repeated_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
Book::mutable_primitive_repeated() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Book.primitive_repeated)
return _internal_mutable_primitive_repeated();
}
// -------------------------------------------------------------------
// Publisher
// required string name = 1;
inline bool Publisher::_internal_has_name() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool Publisher::has_name() const {
return _internal_has_name();
}
inline void Publisher::clear_name() {
name_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& Publisher::name() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Publisher.name)
return _internal_name();
}
inline void Publisher::set_name(const std::string& value) {
_internal_set_name(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Publisher.name)
}
inline std::string* Publisher::mutable_name() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Publisher.name)
return _internal_mutable_name();
}
inline const std::string& Publisher::_internal_name() const {
return name_.Get();
}
inline void Publisher::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Publisher::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Publisher.name)
}
inline void Publisher::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Publisher.name)
}
inline void Publisher::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Publisher.name)
}
inline std::string* Publisher::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
return name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Publisher::release_name() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Publisher.name)
if (!_internal_has_name()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Publisher::set_allocated_name(std::string* name) {
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Publisher.name)
}
// -------------------------------------------------------------------
// Author
// optional uint64 id = 1 [json_name = "@id"];
inline bool Author::_internal_has_id() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool Author::has_id() const {
return _internal_has_id();
}
inline void Author::clear_id() {
id_ = PROTOBUF_ULONGLONG(0);
_has_bits_[0] &= ~0x00000002u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Author::_internal_id() const {
return id_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Author::id() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Author.id)
return _internal_id();
}
inline void Author::_internal_set_id(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_has_bits_[0] |= 0x00000002u;
id_ = value;
}
inline void Author::set_id(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_set_id(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Author.id)
}
// optional string name = 2;
inline bool Author::_internal_has_name() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool Author::has_name() const {
return _internal_has_name();
}
inline void Author::clear_name() {
name_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& Author::name() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Author.name)
return _internal_name();
}
inline void Author::set_name(const std::string& value) {
_internal_set_name(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Author.name)
}
inline std::string* Author::mutable_name() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Author.name)
return _internal_mutable_name();
}
inline const std::string& Author::_internal_name() const {
return name_.Get();
}
inline void Author::_internal_set_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Author::set_name(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
name_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Author.name)
}
inline void Author::set_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Author.name)
}
inline void Author::set_name(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Author.name)
}
inline std::string* Author::_internal_mutable_name() {
_has_bits_[0] |= 0x00000001u;
return name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Author::release_name() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Author.name)
if (!_internal_has_name()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Author::set_allocated_name(std::string* name) {
if (name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Author.name)
}
// repeated string pseudonym = 3;
inline int Author::_internal_pseudonym_size() const {
return pseudonym_.size();
}
inline int Author::pseudonym_size() const {
return _internal_pseudonym_size();
}
inline void Author::clear_pseudonym() {
pseudonym_.Clear();
}
inline std::string* Author::add_pseudonym() {
// @@protoc_insertion_point(field_add_mutable:proto_util_converter.testing.Author.pseudonym)
return _internal_add_pseudonym();
}
inline const std::string& Author::_internal_pseudonym(int index) const {
return pseudonym_.Get(index);
}
inline const std::string& Author::pseudonym(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Author.pseudonym)
return _internal_pseudonym(index);
}
inline std::string* Author::mutable_pseudonym(int index) {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Author.pseudonym)
return pseudonym_.Mutable(index);
}
inline void Author::set_pseudonym(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Author.pseudonym)
pseudonym_.Mutable(index)->assign(value);
}
inline void Author::set_pseudonym(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Author.pseudonym)
pseudonym_.Mutable(index)->assign(std::move(value));
}
inline void Author::set_pseudonym(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
pseudonym_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Author.pseudonym)
}
inline void Author::set_pseudonym(int index, const char* value, size_t size) {
pseudonym_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Author.pseudonym)
}
inline std::string* Author::_internal_add_pseudonym() {
return pseudonym_.Add();
}
inline void Author::add_pseudonym(const std::string& value) {
pseudonym_.Add()->assign(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Author.pseudonym)
}
inline void Author::add_pseudonym(std::string&& value) {
pseudonym_.Add(std::move(value));
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Author.pseudonym)
}
inline void Author::add_pseudonym(const char* value) {
GOOGLE_DCHECK(value != nullptr);
pseudonym_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:proto_util_converter.testing.Author.pseudonym)
}
inline void Author::add_pseudonym(const char* value, size_t size) {
pseudonym_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:proto_util_converter.testing.Author.pseudonym)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
Author::pseudonym() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Author.pseudonym)
return pseudonym_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
Author::mutable_pseudonym() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Author.pseudonym)
return &pseudonym_;
}
// optional bool alive = 4;
inline bool Author::_internal_has_alive() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
return value;
}
inline bool Author::has_alive() const {
return _internal_has_alive();
}
inline void Author::clear_alive() {
alive_ = false;
_has_bits_[0] &= ~0x00000004u;
}
inline bool Author::_internal_alive() const {
return alive_;
}
inline bool Author::alive() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Author.alive)
return _internal_alive();
}
inline void Author::_internal_set_alive(bool value) {
_has_bits_[0] |= 0x00000004u;
alive_ = value;
}
inline void Author::set_alive(bool value) {
_internal_set_alive(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Author.alive)
}
// repeated .proto_util_converter.testing.Author friend = 5;
inline int Author::_internal_friend__size() const {
return friend__.size();
}
inline int Author::friend__size() const {
return _internal_friend__size();
}
inline void Author::clear_friend_() {
friend__.Clear();
}
inline ::proto_util_converter::testing::Author* Author::mutable_friend_(int index) {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Author.friend)
return friend__.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author >*
Author::mutable_friend_() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Author.friend)
return &friend__;
}
inline const ::proto_util_converter::testing::Author& Author::_internal_friend_(int index) const {
return friend__.Get(index);
}
inline const ::proto_util_converter::testing::Author& Author::friend_(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Author.friend)
return _internal_friend_(index);
}
inline ::proto_util_converter::testing::Author* Author::_internal_add_friend_() {
return friend__.Add();
}
inline ::proto_util_converter::testing::Author* Author::add_friend_() {
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Author.friend)
return _internal_add_friend_();
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author >&
Author::friend_() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Author.friend)
return friend__;
}
// -------------------------------------------------------------------
// BadAuthor
// optional string id = 1;
inline bool BadAuthor::_internal_has_id() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool BadAuthor::has_id() const {
return _internal_has_id();
}
inline void BadAuthor::clear_id() {
id_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& BadAuthor::id() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.BadAuthor.id)
return _internal_id();
}
inline void BadAuthor::set_id(const std::string& value) {
_internal_set_id(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.BadAuthor.id)
}
inline std::string* BadAuthor::mutable_id() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.BadAuthor.id)
return _internal_mutable_id();
}
inline const std::string& BadAuthor::_internal_id() const {
return id_.Get();
}
inline void BadAuthor::_internal_set_id(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void BadAuthor::set_id(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
id_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.BadAuthor.id)
}
inline void BadAuthor::set_id(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.BadAuthor.id)
}
inline void BadAuthor::set_id(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.BadAuthor.id)
}
inline std::string* BadAuthor::_internal_mutable_id() {
_has_bits_[0] |= 0x00000001u;
return id_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* BadAuthor::release_id() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.BadAuthor.id)
if (!_internal_has_id()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return id_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void BadAuthor::set_allocated_id(std::string* id) {
if (id != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
id_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), id,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.BadAuthor.id)
}
// repeated uint64 name = 2;
inline int BadAuthor::_internal_name_size() const {
return name_.size();
}
inline int BadAuthor::name_size() const {
return _internal_name_size();
}
inline void BadAuthor::clear_name() {
name_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 BadAuthor::_internal_name(int index) const {
return name_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 BadAuthor::name(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.BadAuthor.name)
return _internal_name(index);
}
inline void BadAuthor::set_name(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value) {
name_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.BadAuthor.name)
}
inline void BadAuthor::_internal_add_name(::PROTOBUF_NAMESPACE_ID::uint64 value) {
name_.Add(value);
}
inline void BadAuthor::add_name(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_add_name(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.BadAuthor.name)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
BadAuthor::_internal_name() const {
return name_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
BadAuthor::name() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.BadAuthor.name)
return _internal_name();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
BadAuthor::_internal_mutable_name() {
return &name_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
BadAuthor::mutable_name() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.BadAuthor.name)
return _internal_mutable_name();
}
// optional string pseudonym = 3;
inline bool BadAuthor::_internal_has_pseudonym() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool BadAuthor::has_pseudonym() const {
return _internal_has_pseudonym();
}
inline void BadAuthor::clear_pseudonym() {
pseudonym_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& BadAuthor::pseudonym() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.BadAuthor.pseudonym)
return _internal_pseudonym();
}
inline void BadAuthor::set_pseudonym(const std::string& value) {
_internal_set_pseudonym(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.BadAuthor.pseudonym)
}
inline std::string* BadAuthor::mutable_pseudonym() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.BadAuthor.pseudonym)
return _internal_mutable_pseudonym();
}
inline const std::string& BadAuthor::_internal_pseudonym() const {
return pseudonym_.Get();
}
inline void BadAuthor::_internal_set_pseudonym(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
pseudonym_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void BadAuthor::set_pseudonym(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
pseudonym_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.BadAuthor.pseudonym)
}
inline void BadAuthor::set_pseudonym(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
pseudonym_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.BadAuthor.pseudonym)
}
inline void BadAuthor::set_pseudonym(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
pseudonym_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.BadAuthor.pseudonym)
}
inline std::string* BadAuthor::_internal_mutable_pseudonym() {
_has_bits_[0] |= 0x00000002u;
return pseudonym_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* BadAuthor::release_pseudonym() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.BadAuthor.pseudonym)
if (!_internal_has_pseudonym()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return pseudonym_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void BadAuthor::set_allocated_pseudonym(std::string* pseudonym) {
if (pseudonym != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
pseudonym_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), pseudonym,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.BadAuthor.pseudonym)
}
// repeated bool alive = 4 [packed = true];
inline int BadAuthor::_internal_alive_size() const {
return alive_.size();
}
inline int BadAuthor::alive_size() const {
return _internal_alive_size();
}
inline void BadAuthor::clear_alive() {
alive_.Clear();
}
inline bool BadAuthor::_internal_alive(int index) const {
return alive_.Get(index);
}
inline bool BadAuthor::alive(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.BadAuthor.alive)
return _internal_alive(index);
}
inline void BadAuthor::set_alive(int index, bool value) {
alive_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.BadAuthor.alive)
}
inline void BadAuthor::_internal_add_alive(bool value) {
alive_.Add(value);
}
inline void BadAuthor::add_alive(bool value) {
_internal_add_alive(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.BadAuthor.alive)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
BadAuthor::_internal_alive() const {
return alive_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
BadAuthor::alive() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.BadAuthor.alive)
return _internal_alive();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
BadAuthor::_internal_mutable_alive() {
return &alive_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
BadAuthor::mutable_alive() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.BadAuthor.alive)
return _internal_mutable_alive();
}
// -------------------------------------------------------------------
// Primitive
// optional fixed32 fix32 = 1;
inline bool Primitive::_internal_has_fix32() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
return value;
}
inline bool Primitive::has_fix32() const {
return _internal_has_fix32();
}
inline void Primitive::clear_fix32() {
fix32_ = 0u;
_has_bits_[0] &= ~0x00000004u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Primitive::_internal_fix32() const {
return fix32_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Primitive::fix32() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.fix32)
return _internal_fix32();
}
inline void Primitive::_internal_set_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000004u;
fix32_ = value;
}
inline void Primitive::set_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_set_fix32(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.fix32)
}
// optional uint32 u32 = 2;
inline bool Primitive::_internal_has_u32() const {
bool value = (_has_bits_[0] & 0x00000008u) != 0;
return value;
}
inline bool Primitive::has_u32() const {
return _internal_has_u32();
}
inline void Primitive::clear_u32() {
u32_ = 0u;
_has_bits_[0] &= ~0x00000008u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Primitive::_internal_u32() const {
return u32_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Primitive::u32() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.u32)
return _internal_u32();
}
inline void Primitive::_internal_set_u32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000008u;
u32_ = value;
}
inline void Primitive::set_u32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_set_u32(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.u32)
}
// optional int32 i32 = 3;
inline bool Primitive::_internal_has_i32() const {
bool value = (_has_bits_[0] & 0x00000010u) != 0;
return value;
}
inline bool Primitive::has_i32() const {
return _internal_has_i32();
}
inline void Primitive::clear_i32() {
i32_ = 0;
_has_bits_[0] &= ~0x00000010u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::_internal_i32() const {
return i32_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::i32() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.i32)
return _internal_i32();
}
inline void Primitive::_internal_set_i32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000010u;
i32_ = value;
}
inline void Primitive::set_i32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_i32(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.i32)
}
// optional sfixed32 sf32 = 4;
inline bool Primitive::_internal_has_sf32() const {
bool value = (_has_bits_[0] & 0x00000020u) != 0;
return value;
}
inline bool Primitive::has_sf32() const {
return _internal_has_sf32();
}
inline void Primitive::clear_sf32() {
sf32_ = 0;
_has_bits_[0] &= ~0x00000020u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::_internal_sf32() const {
return sf32_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::sf32() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.sf32)
return _internal_sf32();
}
inline void Primitive::_internal_set_sf32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000020u;
sf32_ = value;
}
inline void Primitive::set_sf32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_sf32(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.sf32)
}
// optional sint32 s32 = 5;
inline bool Primitive::_internal_has_s32() const {
bool value = (_has_bits_[0] & 0x00000400u) != 0;
return value;
}
inline bool Primitive::has_s32() const {
return _internal_has_s32();
}
inline void Primitive::clear_s32() {
s32_ = 0;
_has_bits_[0] &= ~0x00000400u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::_internal_s32() const {
return s32_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::s32() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.s32)
return _internal_s32();
}
inline void Primitive::_internal_set_s32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000400u;
s32_ = value;
}
inline void Primitive::set_s32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_s32(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.s32)
}
// optional fixed64 fix64 = 6;
inline bool Primitive::_internal_has_fix64() const {
bool value = (_has_bits_[0] & 0x00000040u) != 0;
return value;
}
inline bool Primitive::has_fix64() const {
return _internal_has_fix64();
}
inline void Primitive::clear_fix64() {
fix64_ = PROTOBUF_ULONGLONG(0);
_has_bits_[0] &= ~0x00000040u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Primitive::_internal_fix64() const {
return fix64_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Primitive::fix64() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.fix64)
return _internal_fix64();
}
inline void Primitive::_internal_set_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_has_bits_[0] |= 0x00000040u;
fix64_ = value;
}
inline void Primitive::set_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_set_fix64(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.fix64)
}
// optional uint64 u64 = 7;
inline bool Primitive::_internal_has_u64() const {
bool value = (_has_bits_[0] & 0x00000080u) != 0;
return value;
}
inline bool Primitive::has_u64() const {
return _internal_has_u64();
}
inline void Primitive::clear_u64() {
u64_ = PROTOBUF_ULONGLONG(0);
_has_bits_[0] &= ~0x00000080u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Primitive::_internal_u64() const {
return u64_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Primitive::u64() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.u64)
return _internal_u64();
}
inline void Primitive::_internal_set_u64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_has_bits_[0] |= 0x00000080u;
u64_ = value;
}
inline void Primitive::set_u64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_set_u64(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.u64)
}
// optional int64 i64 = 8;
inline bool Primitive::_internal_has_i64() const {
bool value = (_has_bits_[0] & 0x00000100u) != 0;
return value;
}
inline bool Primitive::has_i64() const {
return _internal_has_i64();
}
inline void Primitive::clear_i64() {
i64_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00000100u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::_internal_i64() const {
return i64_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::i64() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.i64)
return _internal_i64();
}
inline void Primitive::_internal_set_i64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000100u;
i64_ = value;
}
inline void Primitive::set_i64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_i64(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.i64)
}
// optional sfixed64 sf64 = 9;
inline bool Primitive::_internal_has_sf64() const {
bool value = (_has_bits_[0] & 0x00000200u) != 0;
return value;
}
inline bool Primitive::has_sf64() const {
return _internal_has_sf64();
}
inline void Primitive::clear_sf64() {
sf64_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00000200u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::_internal_sf64() const {
return sf64_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::sf64() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.sf64)
return _internal_sf64();
}
inline void Primitive::_internal_set_sf64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000200u;
sf64_ = value;
}
inline void Primitive::set_sf64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_sf64(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.sf64)
}
// optional sint64 s64 = 10;
inline bool Primitive::_internal_has_s64() const {
bool value = (_has_bits_[0] & 0x00001000u) != 0;
return value;
}
inline bool Primitive::has_s64() const {
return _internal_has_s64();
}
inline void Primitive::clear_s64() {
s64_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00001000u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::_internal_s64() const {
return s64_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::s64() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.s64)
return _internal_s64();
}
inline void Primitive::_internal_set_s64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00001000u;
s64_ = value;
}
inline void Primitive::set_s64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_s64(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.s64)
}
// optional string str = 11;
inline bool Primitive::_internal_has_str() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool Primitive::has_str() const {
return _internal_has_str();
}
inline void Primitive::clear_str() {
str_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& Primitive::str() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.str)
return _internal_str();
}
inline void Primitive::set_str(const std::string& value) {
_internal_set_str(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.str)
}
inline std::string* Primitive::mutable_str() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Primitive.str)
return _internal_mutable_str();
}
inline const std::string& Primitive::_internal_str() const {
return str_.Get();
}
inline void Primitive::_internal_set_str(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
str_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Primitive::set_str(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
str_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Primitive.str)
}
inline void Primitive::set_str(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
str_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Primitive.str)
}
inline void Primitive::set_str(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
str_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Primitive.str)
}
inline std::string* Primitive::_internal_mutable_str() {
_has_bits_[0] |= 0x00000001u;
return str_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Primitive::release_str() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Primitive.str)
if (!_internal_has_str()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return str_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Primitive::set_allocated_str(std::string* str) {
if (str != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
str_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), str,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Primitive.str)
}
// optional bytes bytes = 12;
inline bool Primitive::_internal_has_bytes() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool Primitive::has_bytes() const {
return _internal_has_bytes();
}
inline void Primitive::clear_bytes() {
bytes_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& Primitive::bytes() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.bytes)
return _internal_bytes();
}
inline void Primitive::set_bytes(const std::string& value) {
_internal_set_bytes(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.bytes)
}
inline std::string* Primitive::mutable_bytes() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Primitive.bytes)
return _internal_mutable_bytes();
}
inline const std::string& Primitive::_internal_bytes() const {
return bytes_.Get();
}
inline void Primitive::_internal_set_bytes(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
bytes_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Primitive::set_bytes(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
bytes_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Primitive.bytes)
}
inline void Primitive::set_bytes(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
bytes_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Primitive.bytes)
}
inline void Primitive::set_bytes(const void* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
bytes_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Primitive.bytes)
}
inline std::string* Primitive::_internal_mutable_bytes() {
_has_bits_[0] |= 0x00000002u;
return bytes_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Primitive::release_bytes() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Primitive.bytes)
if (!_internal_has_bytes()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return bytes_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Primitive::set_allocated_bytes(std::string* bytes) {
if (bytes != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
bytes_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), bytes,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Primitive.bytes)
}
// optional float float = 13;
inline bool Primitive::_internal_has_float_() const {
bool value = (_has_bits_[0] & 0x00000800u) != 0;
return value;
}
inline bool Primitive::has_float_() const {
return _internal_has_float_();
}
inline void Primitive::clear_float_() {
float__ = 0;
_has_bits_[0] &= ~0x00000800u;
}
inline float Primitive::_internal_float_() const {
return float__;
}
inline float Primitive::float_() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.float)
return _internal_float_();
}
inline void Primitive::_internal_set_float_(float value) {
_has_bits_[0] |= 0x00000800u;
float__ = value;
}
inline void Primitive::set_float_(float value) {
_internal_set_float_(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.float)
}
// optional double double = 14;
inline bool Primitive::_internal_has_double_() const {
bool value = (_has_bits_[0] & 0x00002000u) != 0;
return value;
}
inline bool Primitive::has_double_() const {
return _internal_has_double_();
}
inline void Primitive::clear_double_() {
double__ = 0;
_has_bits_[0] &= ~0x00002000u;
}
inline double Primitive::_internal_double_() const {
return double__;
}
inline double Primitive::double_() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.double)
return _internal_double_();
}
inline void Primitive::_internal_set_double_(double value) {
_has_bits_[0] |= 0x00002000u;
double__ = value;
}
inline void Primitive::set_double_(double value) {
_internal_set_double_(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.double)
}
// optional bool bool = 15;
inline bool Primitive::_internal_has_bool_() const {
bool value = (_has_bits_[0] & 0x00004000u) != 0;
return value;
}
inline bool Primitive::has_bool_() const {
return _internal_has_bool_();
}
inline void Primitive::clear_bool_() {
bool__ = false;
_has_bits_[0] &= ~0x00004000u;
}
inline bool Primitive::_internal_bool_() const {
return bool__;
}
inline bool Primitive::bool_() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.bool)
return _internal_bool_();
}
inline void Primitive::_internal_set_bool_(bool value) {
_has_bits_[0] |= 0x00004000u;
bool__ = value;
}
inline void Primitive::set_bool_(bool value) {
_internal_set_bool_(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.bool)
}
// repeated fixed32 rep_fix32 = 16;
inline int Primitive::_internal_rep_fix32_size() const {
return rep_fix32_.size();
}
inline int Primitive::rep_fix32_size() const {
return _internal_rep_fix32_size();
}
inline void Primitive::clear_rep_fix32() {
rep_fix32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Primitive::_internal_rep_fix32(int index) const {
return rep_fix32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Primitive::rep_fix32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_fix32)
return _internal_rep_fix32(index);
}
inline void Primitive::set_rep_fix32(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value) {
rep_fix32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_fix32)
}
inline void Primitive::_internal_add_rep_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
rep_fix32_.Add(value);
}
inline void Primitive::add_rep_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_add_rep_fix32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_fix32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
Primitive::_internal_rep_fix32() const {
return rep_fix32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
Primitive::rep_fix32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_fix32)
return _internal_rep_fix32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
Primitive::_internal_mutable_rep_fix32() {
return &rep_fix32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
Primitive::mutable_rep_fix32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_fix32)
return _internal_mutable_rep_fix32();
}
// repeated uint32 rep_u32 = 17;
inline int Primitive::_internal_rep_u32_size() const {
return rep_u32_.size();
}
inline int Primitive::rep_u32_size() const {
return _internal_rep_u32_size();
}
inline void Primitive::clear_rep_u32() {
rep_u32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Primitive::_internal_rep_u32(int index) const {
return rep_u32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 Primitive::rep_u32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_u32)
return _internal_rep_u32(index);
}
inline void Primitive::set_rep_u32(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value) {
rep_u32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_u32)
}
inline void Primitive::_internal_add_rep_u32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
rep_u32_.Add(value);
}
inline void Primitive::add_rep_u32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_add_rep_u32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_u32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
Primitive::_internal_rep_u32() const {
return rep_u32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
Primitive::rep_u32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_u32)
return _internal_rep_u32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
Primitive::_internal_mutable_rep_u32() {
return &rep_u32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
Primitive::mutable_rep_u32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_u32)
return _internal_mutable_rep_u32();
}
// repeated int32 rep_i32 = 18;
inline int Primitive::_internal_rep_i32_size() const {
return rep_i32_.size();
}
inline int Primitive::rep_i32_size() const {
return _internal_rep_i32_size();
}
inline void Primitive::clear_rep_i32() {
rep_i32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::_internal_rep_i32(int index) const {
return rep_i32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::rep_i32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_i32)
return _internal_rep_i32(index);
}
inline void Primitive::set_rep_i32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_i32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_i32)
}
inline void Primitive::_internal_add_rep_i32(::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_i32_.Add(value);
}
inline void Primitive::add_rep_i32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_add_rep_i32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_i32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
Primitive::_internal_rep_i32() const {
return rep_i32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
Primitive::rep_i32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_i32)
return _internal_rep_i32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
Primitive::_internal_mutable_rep_i32() {
return &rep_i32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
Primitive::mutable_rep_i32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_i32)
return _internal_mutable_rep_i32();
}
// repeated sfixed32 rep_sf32 = 19;
inline int Primitive::_internal_rep_sf32_size() const {
return rep_sf32_.size();
}
inline int Primitive::rep_sf32_size() const {
return _internal_rep_sf32_size();
}
inline void Primitive::clear_rep_sf32() {
rep_sf32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::_internal_rep_sf32(int index) const {
return rep_sf32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::rep_sf32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_sf32)
return _internal_rep_sf32(index);
}
inline void Primitive::set_rep_sf32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_sf32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_sf32)
}
inline void Primitive::_internal_add_rep_sf32(::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_sf32_.Add(value);
}
inline void Primitive::add_rep_sf32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_add_rep_sf32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_sf32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
Primitive::_internal_rep_sf32() const {
return rep_sf32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
Primitive::rep_sf32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_sf32)
return _internal_rep_sf32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
Primitive::_internal_mutable_rep_sf32() {
return &rep_sf32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
Primitive::mutable_rep_sf32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_sf32)
return _internal_mutable_rep_sf32();
}
// repeated sint32 rep_s32 = 20;
inline int Primitive::_internal_rep_s32_size() const {
return rep_s32_.size();
}
inline int Primitive::rep_s32_size() const {
return _internal_rep_s32_size();
}
inline void Primitive::clear_rep_s32() {
rep_s32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::_internal_rep_s32(int index) const {
return rep_s32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Primitive::rep_s32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_s32)
return _internal_rep_s32(index);
}
inline void Primitive::set_rep_s32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_s32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_s32)
}
inline void Primitive::_internal_add_rep_s32(::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_s32_.Add(value);
}
inline void Primitive::add_rep_s32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_add_rep_s32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_s32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
Primitive::_internal_rep_s32() const {
return rep_s32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
Primitive::rep_s32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_s32)
return _internal_rep_s32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
Primitive::_internal_mutable_rep_s32() {
return &rep_s32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
Primitive::mutable_rep_s32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_s32)
return _internal_mutable_rep_s32();
}
// repeated fixed64 rep_fix64 = 21;
inline int Primitive::_internal_rep_fix64_size() const {
return rep_fix64_.size();
}
inline int Primitive::rep_fix64_size() const {
return _internal_rep_fix64_size();
}
inline void Primitive::clear_rep_fix64() {
rep_fix64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Primitive::_internal_rep_fix64(int index) const {
return rep_fix64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Primitive::rep_fix64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_fix64)
return _internal_rep_fix64(index);
}
inline void Primitive::set_rep_fix64(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value) {
rep_fix64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_fix64)
}
inline void Primitive::_internal_add_rep_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
rep_fix64_.Add(value);
}
inline void Primitive::add_rep_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_add_rep_fix64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_fix64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
Primitive::_internal_rep_fix64() const {
return rep_fix64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
Primitive::rep_fix64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_fix64)
return _internal_rep_fix64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
Primitive::_internal_mutable_rep_fix64() {
return &rep_fix64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
Primitive::mutable_rep_fix64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_fix64)
return _internal_mutable_rep_fix64();
}
// repeated uint64 rep_u64 = 22;
inline int Primitive::_internal_rep_u64_size() const {
return rep_u64_.size();
}
inline int Primitive::rep_u64_size() const {
return _internal_rep_u64_size();
}
inline void Primitive::clear_rep_u64() {
rep_u64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Primitive::_internal_rep_u64(int index) const {
return rep_u64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 Primitive::rep_u64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_u64)
return _internal_rep_u64(index);
}
inline void Primitive::set_rep_u64(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value) {
rep_u64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_u64)
}
inline void Primitive::_internal_add_rep_u64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
rep_u64_.Add(value);
}
inline void Primitive::add_rep_u64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_add_rep_u64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_u64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
Primitive::_internal_rep_u64() const {
return rep_u64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
Primitive::rep_u64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_u64)
return _internal_rep_u64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
Primitive::_internal_mutable_rep_u64() {
return &rep_u64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
Primitive::mutable_rep_u64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_u64)
return _internal_mutable_rep_u64();
}
// repeated int64 rep_i64 = 23;
inline int Primitive::_internal_rep_i64_size() const {
return rep_i64_.size();
}
inline int Primitive::rep_i64_size() const {
return _internal_rep_i64_size();
}
inline void Primitive::clear_rep_i64() {
rep_i64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::_internal_rep_i64(int index) const {
return rep_i64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::rep_i64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_i64)
return _internal_rep_i64(index);
}
inline void Primitive::set_rep_i64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_i64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_i64)
}
inline void Primitive::_internal_add_rep_i64(::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_i64_.Add(value);
}
inline void Primitive::add_rep_i64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_add_rep_i64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_i64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
Primitive::_internal_rep_i64() const {
return rep_i64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
Primitive::rep_i64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_i64)
return _internal_rep_i64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
Primitive::_internal_mutable_rep_i64() {
return &rep_i64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
Primitive::mutable_rep_i64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_i64)
return _internal_mutable_rep_i64();
}
// repeated sfixed64 rep_sf64 = 24;
inline int Primitive::_internal_rep_sf64_size() const {
return rep_sf64_.size();
}
inline int Primitive::rep_sf64_size() const {
return _internal_rep_sf64_size();
}
inline void Primitive::clear_rep_sf64() {
rep_sf64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::_internal_rep_sf64(int index) const {
return rep_sf64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::rep_sf64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_sf64)
return _internal_rep_sf64(index);
}
inline void Primitive::set_rep_sf64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_sf64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_sf64)
}
inline void Primitive::_internal_add_rep_sf64(::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_sf64_.Add(value);
}
inline void Primitive::add_rep_sf64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_add_rep_sf64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_sf64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
Primitive::_internal_rep_sf64() const {
return rep_sf64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
Primitive::rep_sf64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_sf64)
return _internal_rep_sf64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
Primitive::_internal_mutable_rep_sf64() {
return &rep_sf64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
Primitive::mutable_rep_sf64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_sf64)
return _internal_mutable_rep_sf64();
}
// repeated sint64 rep_s64 = 25;
inline int Primitive::_internal_rep_s64_size() const {
return rep_s64_.size();
}
inline int Primitive::rep_s64_size() const {
return _internal_rep_s64_size();
}
inline void Primitive::clear_rep_s64() {
rep_s64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::_internal_rep_s64(int index) const {
return rep_s64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int64 Primitive::rep_s64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_s64)
return _internal_rep_s64(index);
}
inline void Primitive::set_rep_s64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_s64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_s64)
}
inline void Primitive::_internal_add_rep_s64(::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_s64_.Add(value);
}
inline void Primitive::add_rep_s64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_add_rep_s64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_s64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
Primitive::_internal_rep_s64() const {
return rep_s64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
Primitive::rep_s64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_s64)
return _internal_rep_s64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
Primitive::_internal_mutable_rep_s64() {
return &rep_s64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
Primitive::mutable_rep_s64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_s64)
return _internal_mutable_rep_s64();
}
// repeated string rep_str = 26;
inline int Primitive::_internal_rep_str_size() const {
return rep_str_.size();
}
inline int Primitive::rep_str_size() const {
return _internal_rep_str_size();
}
inline void Primitive::clear_rep_str() {
rep_str_.Clear();
}
inline std::string* Primitive::add_rep_str() {
// @@protoc_insertion_point(field_add_mutable:proto_util_converter.testing.Primitive.rep_str)
return _internal_add_rep_str();
}
inline const std::string& Primitive::_internal_rep_str(int index) const {
return rep_str_.Get(index);
}
inline const std::string& Primitive::rep_str(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_str)
return _internal_rep_str(index);
}
inline std::string* Primitive::mutable_rep_str(int index) {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Primitive.rep_str)
return rep_str_.Mutable(index);
}
inline void Primitive::set_rep_str(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_str)
rep_str_.Mutable(index)->assign(value);
}
inline void Primitive::set_rep_str(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_str)
rep_str_.Mutable(index)->assign(std::move(value));
}
inline void Primitive::set_rep_str(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
rep_str_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Primitive.rep_str)
}
inline void Primitive::set_rep_str(int index, const char* value, size_t size) {
rep_str_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Primitive.rep_str)
}
inline std::string* Primitive::_internal_add_rep_str() {
return rep_str_.Add();
}
inline void Primitive::add_rep_str(const std::string& value) {
rep_str_.Add()->assign(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_str)
}
inline void Primitive::add_rep_str(std::string&& value) {
rep_str_.Add(std::move(value));
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_str)
}
inline void Primitive::add_rep_str(const char* value) {
GOOGLE_DCHECK(value != nullptr);
rep_str_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:proto_util_converter.testing.Primitive.rep_str)
}
inline void Primitive::add_rep_str(const char* value, size_t size) {
rep_str_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:proto_util_converter.testing.Primitive.rep_str)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
Primitive::rep_str() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_str)
return rep_str_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
Primitive::mutable_rep_str() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_str)
return &rep_str_;
}
// repeated bytes rep_bytes = 27;
inline int Primitive::_internal_rep_bytes_size() const {
return rep_bytes_.size();
}
inline int Primitive::rep_bytes_size() const {
return _internal_rep_bytes_size();
}
inline void Primitive::clear_rep_bytes() {
rep_bytes_.Clear();
}
inline std::string* Primitive::add_rep_bytes() {
// @@protoc_insertion_point(field_add_mutable:proto_util_converter.testing.Primitive.rep_bytes)
return _internal_add_rep_bytes();
}
inline const std::string& Primitive::_internal_rep_bytes(int index) const {
return rep_bytes_.Get(index);
}
inline const std::string& Primitive::rep_bytes(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_bytes)
return _internal_rep_bytes(index);
}
inline std::string* Primitive::mutable_rep_bytes(int index) {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Primitive.rep_bytes)
return rep_bytes_.Mutable(index);
}
inline void Primitive::set_rep_bytes(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_bytes)
rep_bytes_.Mutable(index)->assign(value);
}
inline void Primitive::set_rep_bytes(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_bytes)
rep_bytes_.Mutable(index)->assign(std::move(value));
}
inline void Primitive::set_rep_bytes(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
rep_bytes_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Primitive.rep_bytes)
}
inline void Primitive::set_rep_bytes(int index, const void* value, size_t size) {
rep_bytes_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Primitive.rep_bytes)
}
inline std::string* Primitive::_internal_add_rep_bytes() {
return rep_bytes_.Add();
}
inline void Primitive::add_rep_bytes(const std::string& value) {
rep_bytes_.Add()->assign(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_bytes)
}
inline void Primitive::add_rep_bytes(std::string&& value) {
rep_bytes_.Add(std::move(value));
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_bytes)
}
inline void Primitive::add_rep_bytes(const char* value) {
GOOGLE_DCHECK(value != nullptr);
rep_bytes_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:proto_util_converter.testing.Primitive.rep_bytes)
}
inline void Primitive::add_rep_bytes(const void* value, size_t size) {
rep_bytes_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:proto_util_converter.testing.Primitive.rep_bytes)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
Primitive::rep_bytes() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_bytes)
return rep_bytes_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
Primitive::mutable_rep_bytes() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_bytes)
return &rep_bytes_;
}
// repeated float rep_float = 28;
inline int Primitive::_internal_rep_float_size() const {
return rep_float_.size();
}
inline int Primitive::rep_float_size() const {
return _internal_rep_float_size();
}
inline void Primitive::clear_rep_float() {
rep_float_.Clear();
}
inline float Primitive::_internal_rep_float(int index) const {
return rep_float_.Get(index);
}
inline float Primitive::rep_float(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_float)
return _internal_rep_float(index);
}
inline void Primitive::set_rep_float(int index, float value) {
rep_float_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_float)
}
inline void Primitive::_internal_add_rep_float(float value) {
rep_float_.Add(value);
}
inline void Primitive::add_rep_float(float value) {
_internal_add_rep_float(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_float)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >&
Primitive::_internal_rep_float() const {
return rep_float_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >&
Primitive::rep_float() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_float)
return _internal_rep_float();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >*
Primitive::_internal_mutable_rep_float() {
return &rep_float_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >*
Primitive::mutable_rep_float() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_float)
return _internal_mutable_rep_float();
}
// repeated double rep_double = 29;
inline int Primitive::_internal_rep_double_size() const {
return rep_double_.size();
}
inline int Primitive::rep_double_size() const {
return _internal_rep_double_size();
}
inline void Primitive::clear_rep_double() {
rep_double_.Clear();
}
inline double Primitive::_internal_rep_double(int index) const {
return rep_double_.Get(index);
}
inline double Primitive::rep_double(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_double)
return _internal_rep_double(index);
}
inline void Primitive::set_rep_double(int index, double value) {
rep_double_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_double)
}
inline void Primitive::_internal_add_rep_double(double value) {
rep_double_.Add(value);
}
inline void Primitive::add_rep_double(double value) {
_internal_add_rep_double(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_double)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
Primitive::_internal_rep_double() const {
return rep_double_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
Primitive::rep_double() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_double)
return _internal_rep_double();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
Primitive::_internal_mutable_rep_double() {
return &rep_double_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
Primitive::mutable_rep_double() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_double)
return _internal_mutable_rep_double();
}
// repeated bool rep_bool = 30;
inline int Primitive::_internal_rep_bool_size() const {
return rep_bool_.size();
}
inline int Primitive::rep_bool_size() const {
return _internal_rep_bool_size();
}
inline void Primitive::clear_rep_bool() {
rep_bool_.Clear();
}
inline bool Primitive::_internal_rep_bool(int index) const {
return rep_bool_.Get(index);
}
inline bool Primitive::rep_bool(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Primitive.rep_bool)
return _internal_rep_bool(index);
}
inline void Primitive::set_rep_bool(int index, bool value) {
rep_bool_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Primitive.rep_bool)
}
inline void Primitive::_internal_add_rep_bool(bool value) {
rep_bool_.Add(value);
}
inline void Primitive::add_rep_bool(bool value) {
_internal_add_rep_bool(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Primitive.rep_bool)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
Primitive::_internal_rep_bool() const {
return rep_bool_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
Primitive::rep_bool() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Primitive.rep_bool)
return _internal_rep_bool();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
Primitive::_internal_mutable_rep_bool() {
return &rep_bool_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
Primitive::mutable_rep_bool() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Primitive.rep_bool)
return _internal_mutable_rep_bool();
}
// -------------------------------------------------------------------
// PackedPrimitive
// repeated fixed32 rep_fix32 = 16 [packed = true];
inline int PackedPrimitive::_internal_rep_fix32_size() const {
return rep_fix32_.size();
}
inline int PackedPrimitive::rep_fix32_size() const {
return _internal_rep_fix32_size();
}
inline void PackedPrimitive::clear_rep_fix32() {
rep_fix32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 PackedPrimitive::_internal_rep_fix32(int index) const {
return rep_fix32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 PackedPrimitive::rep_fix32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_fix32)
return _internal_rep_fix32(index);
}
inline void PackedPrimitive::set_rep_fix32(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value) {
rep_fix32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_fix32)
}
inline void PackedPrimitive::_internal_add_rep_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
rep_fix32_.Add(value);
}
inline void PackedPrimitive::add_rep_fix32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_add_rep_fix32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_fix32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
PackedPrimitive::_internal_rep_fix32() const {
return rep_fix32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
PackedPrimitive::rep_fix32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_fix32)
return _internal_rep_fix32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
PackedPrimitive::_internal_mutable_rep_fix32() {
return &rep_fix32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
PackedPrimitive::mutable_rep_fix32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_fix32)
return _internal_mutable_rep_fix32();
}
// repeated uint32 rep_u32 = 17 [packed = true];
inline int PackedPrimitive::_internal_rep_u32_size() const {
return rep_u32_.size();
}
inline int PackedPrimitive::rep_u32_size() const {
return _internal_rep_u32_size();
}
inline void PackedPrimitive::clear_rep_u32() {
rep_u32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 PackedPrimitive::_internal_rep_u32(int index) const {
return rep_u32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 PackedPrimitive::rep_u32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_u32)
return _internal_rep_u32(index);
}
inline void PackedPrimitive::set_rep_u32(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value) {
rep_u32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_u32)
}
inline void PackedPrimitive::_internal_add_rep_u32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
rep_u32_.Add(value);
}
inline void PackedPrimitive::add_rep_u32(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_add_rep_u32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_u32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
PackedPrimitive::_internal_rep_u32() const {
return rep_u32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
PackedPrimitive::rep_u32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_u32)
return _internal_rep_u32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
PackedPrimitive::_internal_mutable_rep_u32() {
return &rep_u32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
PackedPrimitive::mutable_rep_u32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_u32)
return _internal_mutable_rep_u32();
}
// repeated int32 rep_i32 = 18 [packed = true];
inline int PackedPrimitive::_internal_rep_i32_size() const {
return rep_i32_.size();
}
inline int PackedPrimitive::rep_i32_size() const {
return _internal_rep_i32_size();
}
inline void PackedPrimitive::clear_rep_i32() {
rep_i32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int32 PackedPrimitive::_internal_rep_i32(int index) const {
return rep_i32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int32 PackedPrimitive::rep_i32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_i32)
return _internal_rep_i32(index);
}
inline void PackedPrimitive::set_rep_i32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_i32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_i32)
}
inline void PackedPrimitive::_internal_add_rep_i32(::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_i32_.Add(value);
}
inline void PackedPrimitive::add_rep_i32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_add_rep_i32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_i32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
PackedPrimitive::_internal_rep_i32() const {
return rep_i32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
PackedPrimitive::rep_i32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_i32)
return _internal_rep_i32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
PackedPrimitive::_internal_mutable_rep_i32() {
return &rep_i32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
PackedPrimitive::mutable_rep_i32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_i32)
return _internal_mutable_rep_i32();
}
// repeated sfixed32 rep_sf32 = 19 [packed = true];
inline int PackedPrimitive::_internal_rep_sf32_size() const {
return rep_sf32_.size();
}
inline int PackedPrimitive::rep_sf32_size() const {
return _internal_rep_sf32_size();
}
inline void PackedPrimitive::clear_rep_sf32() {
rep_sf32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int32 PackedPrimitive::_internal_rep_sf32(int index) const {
return rep_sf32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int32 PackedPrimitive::rep_sf32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_sf32)
return _internal_rep_sf32(index);
}
inline void PackedPrimitive::set_rep_sf32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_sf32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_sf32)
}
inline void PackedPrimitive::_internal_add_rep_sf32(::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_sf32_.Add(value);
}
inline void PackedPrimitive::add_rep_sf32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_add_rep_sf32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_sf32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
PackedPrimitive::_internal_rep_sf32() const {
return rep_sf32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
PackedPrimitive::rep_sf32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_sf32)
return _internal_rep_sf32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
PackedPrimitive::_internal_mutable_rep_sf32() {
return &rep_sf32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
PackedPrimitive::mutable_rep_sf32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_sf32)
return _internal_mutable_rep_sf32();
}
// repeated sint32 rep_s32 = 20 [packed = true];
inline int PackedPrimitive::_internal_rep_s32_size() const {
return rep_s32_.size();
}
inline int PackedPrimitive::rep_s32_size() const {
return _internal_rep_s32_size();
}
inline void PackedPrimitive::clear_rep_s32() {
rep_s32_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int32 PackedPrimitive::_internal_rep_s32(int index) const {
return rep_s32_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int32 PackedPrimitive::rep_s32(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_s32)
return _internal_rep_s32(index);
}
inline void PackedPrimitive::set_rep_s32(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_s32_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_s32)
}
inline void PackedPrimitive::_internal_add_rep_s32(::PROTOBUF_NAMESPACE_ID::int32 value) {
rep_s32_.Add(value);
}
inline void PackedPrimitive::add_rep_s32(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_add_rep_s32(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_s32)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
PackedPrimitive::_internal_rep_s32() const {
return rep_s32_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
PackedPrimitive::rep_s32() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_s32)
return _internal_rep_s32();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
PackedPrimitive::_internal_mutable_rep_s32() {
return &rep_s32_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
PackedPrimitive::mutable_rep_s32() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_s32)
return _internal_mutable_rep_s32();
}
// repeated fixed64 rep_fix64 = 21 [packed = true];
inline int PackedPrimitive::_internal_rep_fix64_size() const {
return rep_fix64_.size();
}
inline int PackedPrimitive::rep_fix64_size() const {
return _internal_rep_fix64_size();
}
inline void PackedPrimitive::clear_rep_fix64() {
rep_fix64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 PackedPrimitive::_internal_rep_fix64(int index) const {
return rep_fix64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 PackedPrimitive::rep_fix64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_fix64)
return _internal_rep_fix64(index);
}
inline void PackedPrimitive::set_rep_fix64(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value) {
rep_fix64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_fix64)
}
inline void PackedPrimitive::_internal_add_rep_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
rep_fix64_.Add(value);
}
inline void PackedPrimitive::add_rep_fix64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_add_rep_fix64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_fix64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
PackedPrimitive::_internal_rep_fix64() const {
return rep_fix64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
PackedPrimitive::rep_fix64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_fix64)
return _internal_rep_fix64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
PackedPrimitive::_internal_mutable_rep_fix64() {
return &rep_fix64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
PackedPrimitive::mutable_rep_fix64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_fix64)
return _internal_mutable_rep_fix64();
}
// repeated uint64 rep_u64 = 22 [packed = true];
inline int PackedPrimitive::_internal_rep_u64_size() const {
return rep_u64_.size();
}
inline int PackedPrimitive::rep_u64_size() const {
return _internal_rep_u64_size();
}
inline void PackedPrimitive::clear_rep_u64() {
rep_u64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 PackedPrimitive::_internal_rep_u64(int index) const {
return rep_u64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 PackedPrimitive::rep_u64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_u64)
return _internal_rep_u64(index);
}
inline void PackedPrimitive::set_rep_u64(int index, ::PROTOBUF_NAMESPACE_ID::uint64 value) {
rep_u64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_u64)
}
inline void PackedPrimitive::_internal_add_rep_u64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
rep_u64_.Add(value);
}
inline void PackedPrimitive::add_rep_u64(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_add_rep_u64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_u64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
PackedPrimitive::_internal_rep_u64() const {
return rep_u64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >&
PackedPrimitive::rep_u64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_u64)
return _internal_rep_u64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
PackedPrimitive::_internal_mutable_rep_u64() {
return &rep_u64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint64 >*
PackedPrimitive::mutable_rep_u64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_u64)
return _internal_mutable_rep_u64();
}
// repeated int64 rep_i64 = 23 [packed = true];
inline int PackedPrimitive::_internal_rep_i64_size() const {
return rep_i64_.size();
}
inline int PackedPrimitive::rep_i64_size() const {
return _internal_rep_i64_size();
}
inline void PackedPrimitive::clear_rep_i64() {
rep_i64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int64 PackedPrimitive::_internal_rep_i64(int index) const {
return rep_i64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int64 PackedPrimitive::rep_i64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_i64)
return _internal_rep_i64(index);
}
inline void PackedPrimitive::set_rep_i64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_i64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_i64)
}
inline void PackedPrimitive::_internal_add_rep_i64(::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_i64_.Add(value);
}
inline void PackedPrimitive::add_rep_i64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_add_rep_i64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_i64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
PackedPrimitive::_internal_rep_i64() const {
return rep_i64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
PackedPrimitive::rep_i64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_i64)
return _internal_rep_i64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
PackedPrimitive::_internal_mutable_rep_i64() {
return &rep_i64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
PackedPrimitive::mutable_rep_i64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_i64)
return _internal_mutable_rep_i64();
}
// repeated sfixed64 rep_sf64 = 24 [packed = true];
inline int PackedPrimitive::_internal_rep_sf64_size() const {
return rep_sf64_.size();
}
inline int PackedPrimitive::rep_sf64_size() const {
return _internal_rep_sf64_size();
}
inline void PackedPrimitive::clear_rep_sf64() {
rep_sf64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int64 PackedPrimitive::_internal_rep_sf64(int index) const {
return rep_sf64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int64 PackedPrimitive::rep_sf64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_sf64)
return _internal_rep_sf64(index);
}
inline void PackedPrimitive::set_rep_sf64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_sf64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_sf64)
}
inline void PackedPrimitive::_internal_add_rep_sf64(::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_sf64_.Add(value);
}
inline void PackedPrimitive::add_rep_sf64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_add_rep_sf64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_sf64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
PackedPrimitive::_internal_rep_sf64() const {
return rep_sf64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
PackedPrimitive::rep_sf64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_sf64)
return _internal_rep_sf64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
PackedPrimitive::_internal_mutable_rep_sf64() {
return &rep_sf64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
PackedPrimitive::mutable_rep_sf64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_sf64)
return _internal_mutable_rep_sf64();
}
// repeated sint64 rep_s64 = 25 [packed = true];
inline int PackedPrimitive::_internal_rep_s64_size() const {
return rep_s64_.size();
}
inline int PackedPrimitive::rep_s64_size() const {
return _internal_rep_s64_size();
}
inline void PackedPrimitive::clear_rep_s64() {
rep_s64_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::int64 PackedPrimitive::_internal_rep_s64(int index) const {
return rep_s64_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::int64 PackedPrimitive::rep_s64(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_s64)
return _internal_rep_s64(index);
}
inline void PackedPrimitive::set_rep_s64(int index, ::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_s64_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_s64)
}
inline void PackedPrimitive::_internal_add_rep_s64(::PROTOBUF_NAMESPACE_ID::int64 value) {
rep_s64_.Add(value);
}
inline void PackedPrimitive::add_rep_s64(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_add_rep_s64(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_s64)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
PackedPrimitive::_internal_rep_s64() const {
return rep_s64_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >&
PackedPrimitive::rep_s64() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_s64)
return _internal_rep_s64();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
PackedPrimitive::_internal_mutable_rep_s64() {
return &rep_s64_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int64 >*
PackedPrimitive::mutable_rep_s64() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_s64)
return _internal_mutable_rep_s64();
}
// repeated float rep_float = 28 [packed = true];
inline int PackedPrimitive::_internal_rep_float_size() const {
return rep_float_.size();
}
inline int PackedPrimitive::rep_float_size() const {
return _internal_rep_float_size();
}
inline void PackedPrimitive::clear_rep_float() {
rep_float_.Clear();
}
inline float PackedPrimitive::_internal_rep_float(int index) const {
return rep_float_.Get(index);
}
inline float PackedPrimitive::rep_float(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_float)
return _internal_rep_float(index);
}
inline void PackedPrimitive::set_rep_float(int index, float value) {
rep_float_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_float)
}
inline void PackedPrimitive::_internal_add_rep_float(float value) {
rep_float_.Add(value);
}
inline void PackedPrimitive::add_rep_float(float value) {
_internal_add_rep_float(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_float)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >&
PackedPrimitive::_internal_rep_float() const {
return rep_float_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >&
PackedPrimitive::rep_float() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_float)
return _internal_rep_float();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >*
PackedPrimitive::_internal_mutable_rep_float() {
return &rep_float_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >*
PackedPrimitive::mutable_rep_float() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_float)
return _internal_mutable_rep_float();
}
// repeated double rep_double = 29 [packed = true];
inline int PackedPrimitive::_internal_rep_double_size() const {
return rep_double_.size();
}
inline int PackedPrimitive::rep_double_size() const {
return _internal_rep_double_size();
}
inline void PackedPrimitive::clear_rep_double() {
rep_double_.Clear();
}
inline double PackedPrimitive::_internal_rep_double(int index) const {
return rep_double_.Get(index);
}
inline double PackedPrimitive::rep_double(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_double)
return _internal_rep_double(index);
}
inline void PackedPrimitive::set_rep_double(int index, double value) {
rep_double_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_double)
}
inline void PackedPrimitive::_internal_add_rep_double(double value) {
rep_double_.Add(value);
}
inline void PackedPrimitive::add_rep_double(double value) {
_internal_add_rep_double(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_double)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
PackedPrimitive::_internal_rep_double() const {
return rep_double_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >&
PackedPrimitive::rep_double() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_double)
return _internal_rep_double();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
PackedPrimitive::_internal_mutable_rep_double() {
return &rep_double_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >*
PackedPrimitive::mutable_rep_double() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_double)
return _internal_mutable_rep_double();
}
// repeated bool rep_bool = 30 [packed = true];
inline int PackedPrimitive::_internal_rep_bool_size() const {
return rep_bool_.size();
}
inline int PackedPrimitive::rep_bool_size() const {
return _internal_rep_bool_size();
}
inline void PackedPrimitive::clear_rep_bool() {
rep_bool_.Clear();
}
inline bool PackedPrimitive::_internal_rep_bool(int index) const {
return rep_bool_.Get(index);
}
inline bool PackedPrimitive::rep_bool(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.PackedPrimitive.rep_bool)
return _internal_rep_bool(index);
}
inline void PackedPrimitive::set_rep_bool(int index, bool value) {
rep_bool_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.PackedPrimitive.rep_bool)
}
inline void PackedPrimitive::_internal_add_rep_bool(bool value) {
rep_bool_.Add(value);
}
inline void PackedPrimitive::add_rep_bool(bool value) {
_internal_add_rep_bool(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.PackedPrimitive.rep_bool)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
PackedPrimitive::_internal_rep_bool() const {
return rep_bool_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >&
PackedPrimitive::rep_bool() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.PackedPrimitive.rep_bool)
return _internal_rep_bool();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
PackedPrimitive::_internal_mutable_rep_bool() {
return &rep_bool_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >*
PackedPrimitive::mutable_rep_bool() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.PackedPrimitive.rep_bool)
return _internal_mutable_rep_bool();
}
// -------------------------------------------------------------------
// NestedBook
// optional .proto_util_converter.testing.Book book = 1;
inline bool NestedBook::_internal_has_book() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
PROTOBUF_ASSUME(!value || book_ != nullptr);
return value;
}
inline bool NestedBook::has_book() const {
return _internal_has_book();
}
inline void NestedBook::clear_book() {
if (book_ != nullptr) book_->Clear();
_has_bits_[0] &= ~0x00000001u;
}
inline const ::proto_util_converter::testing::Book& NestedBook::_internal_book() const {
const ::proto_util_converter::testing::Book* p = book_;
return p != nullptr ? *p : reinterpret_cast<const ::proto_util_converter::testing::Book&>(
::proto_util_converter::testing::_Book_default_instance_);
}
inline const ::proto_util_converter::testing::Book& NestedBook::book() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.NestedBook.book)
return _internal_book();
}
inline void NestedBook::unsafe_arena_set_allocated_book(
::proto_util_converter::testing::Book* book) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(book_);
}
book_ = book;
if (book) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:proto_util_converter.testing.NestedBook.book)
}
inline ::proto_util_converter::testing::Book* NestedBook::release_book() {
_has_bits_[0] &= ~0x00000001u;
::proto_util_converter::testing::Book* temp = book_;
book_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::proto_util_converter::testing::Book* NestedBook::unsafe_arena_release_book() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.NestedBook.book)
_has_bits_[0] &= ~0x00000001u;
::proto_util_converter::testing::Book* temp = book_;
book_ = nullptr;
return temp;
}
inline ::proto_util_converter::testing::Book* NestedBook::_internal_mutable_book() {
_has_bits_[0] |= 0x00000001u;
if (book_ == nullptr) {
auto* p = CreateMaybeMessage<::proto_util_converter::testing::Book>(GetArena());
book_ = p;
}
return book_;
}
inline ::proto_util_converter::testing::Book* NestedBook::mutable_book() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.NestedBook.book)
return _internal_mutable_book();
}
inline void NestedBook::set_allocated_book(::proto_util_converter::testing::Book* book) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete book_;
}
if (book) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(book);
if (message_arena != submessage_arena) {
book = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, book, submessage_arena);
}
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
book_ = book;
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.NestedBook.book)
}
// -------------------------------------------------------------------
// BadNestedBook
// repeated uint32 book = 1 [packed = true];
inline int BadNestedBook::_internal_book_size() const {
return book_.size();
}
inline int BadNestedBook::book_size() const {
return _internal_book_size();
}
inline void BadNestedBook::clear_book() {
book_.Clear();
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 BadNestedBook::_internal_book(int index) const {
return book_.Get(index);
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 BadNestedBook::book(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.BadNestedBook.book)
return _internal_book(index);
}
inline void BadNestedBook::set_book(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value) {
book_.Set(index, value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.BadNestedBook.book)
}
inline void BadNestedBook::_internal_add_book(::PROTOBUF_NAMESPACE_ID::uint32 value) {
book_.Add(value);
}
inline void BadNestedBook::add_book(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_add_book(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.BadNestedBook.book)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
BadNestedBook::_internal_book() const {
return book_;
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
BadNestedBook::book() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.BadNestedBook.book)
return _internal_book();
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
BadNestedBook::_internal_mutable_book() {
return &book_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
BadNestedBook::mutable_book() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.BadNestedBook.book)
return _internal_mutable_book();
}
// -------------------------------------------------------------------
// Cyclic
// optional int32 m_int = 1;
inline bool Cyclic::_internal_has_m_int() const {
bool value = (_has_bits_[0] & 0x00000008u) != 0;
return value;
}
inline bool Cyclic::has_m_int() const {
return _internal_has_m_int();
}
inline void Cyclic::clear_m_int() {
m_int_ = 0;
_has_bits_[0] &= ~0x00000008u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Cyclic::_internal_m_int() const {
return m_int_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 Cyclic::m_int() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Cyclic.m_int)
return _internal_m_int();
}
inline void Cyclic::_internal_set_m_int(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000008u;
m_int_ = value;
}
inline void Cyclic::set_m_int(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_m_int(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Cyclic.m_int)
}
// optional string m_str = 2;
inline bool Cyclic::_internal_has_m_str() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool Cyclic::has_m_str() const {
return _internal_has_m_str();
}
inline void Cyclic::clear_m_str() {
m_str_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& Cyclic::m_str() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Cyclic.m_str)
return _internal_m_str();
}
inline void Cyclic::set_m_str(const std::string& value) {
_internal_set_m_str(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.Cyclic.m_str)
}
inline std::string* Cyclic::mutable_m_str() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Cyclic.m_str)
return _internal_mutable_m_str();
}
inline const std::string& Cyclic::_internal_m_str() const {
return m_str_.Get();
}
inline void Cyclic::_internal_set_m_str(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
m_str_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Cyclic::set_m_str(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
m_str_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.Cyclic.m_str)
}
inline void Cyclic::set_m_str(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
m_str_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.Cyclic.m_str)
}
inline void Cyclic::set_m_str(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
m_str_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.Cyclic.m_str)
}
inline std::string* Cyclic::_internal_mutable_m_str() {
_has_bits_[0] |= 0x00000001u;
return m_str_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Cyclic::release_m_str() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Cyclic.m_str)
if (!_internal_has_m_str()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return m_str_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Cyclic::set_allocated_m_str(std::string* m_str) {
if (m_str != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
m_str_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), m_str,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Cyclic.m_str)
}
// optional .proto_util_converter.testing.Book m_book = 3;
inline bool Cyclic::_internal_has_m_book() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
PROTOBUF_ASSUME(!value || m_book_ != nullptr);
return value;
}
inline bool Cyclic::has_m_book() const {
return _internal_has_m_book();
}
inline void Cyclic::clear_m_book() {
if (m_book_ != nullptr) m_book_->Clear();
_has_bits_[0] &= ~0x00000002u;
}
inline const ::proto_util_converter::testing::Book& Cyclic::_internal_m_book() const {
const ::proto_util_converter::testing::Book* p = m_book_;
return p != nullptr ? *p : reinterpret_cast<const ::proto_util_converter::testing::Book&>(
::proto_util_converter::testing::_Book_default_instance_);
}
inline const ::proto_util_converter::testing::Book& Cyclic::m_book() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Cyclic.m_book)
return _internal_m_book();
}
inline void Cyclic::unsafe_arena_set_allocated_m_book(
::proto_util_converter::testing::Book* m_book) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(m_book_);
}
m_book_ = m_book;
if (m_book) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:proto_util_converter.testing.Cyclic.m_book)
}
inline ::proto_util_converter::testing::Book* Cyclic::release_m_book() {
_has_bits_[0] &= ~0x00000002u;
::proto_util_converter::testing::Book* temp = m_book_;
m_book_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::proto_util_converter::testing::Book* Cyclic::unsafe_arena_release_m_book() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Cyclic.m_book)
_has_bits_[0] &= ~0x00000002u;
::proto_util_converter::testing::Book* temp = m_book_;
m_book_ = nullptr;
return temp;
}
inline ::proto_util_converter::testing::Book* Cyclic::_internal_mutable_m_book() {
_has_bits_[0] |= 0x00000002u;
if (m_book_ == nullptr) {
auto* p = CreateMaybeMessage<::proto_util_converter::testing::Book>(GetArena());
m_book_ = p;
}
return m_book_;
}
inline ::proto_util_converter::testing::Book* Cyclic::mutable_m_book() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Cyclic.m_book)
return _internal_mutable_m_book();
}
inline void Cyclic::set_allocated_m_book(::proto_util_converter::testing::Book* m_book) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete m_book_;
}
if (m_book) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(m_book);
if (message_arena != submessage_arena) {
m_book = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, m_book, submessage_arena);
}
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
m_book_ = m_book;
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Cyclic.m_book)
}
// repeated .proto_util_converter.testing.Author m_author = 5;
inline int Cyclic::_internal_m_author_size() const {
return m_author_.size();
}
inline int Cyclic::m_author_size() const {
return _internal_m_author_size();
}
inline void Cyclic::clear_m_author() {
m_author_.Clear();
}
inline ::proto_util_converter::testing::Author* Cyclic::mutable_m_author(int index) {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Cyclic.m_author)
return m_author_.Mutable(index);
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author >*
Cyclic::mutable_m_author() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.Cyclic.m_author)
return &m_author_;
}
inline const ::proto_util_converter::testing::Author& Cyclic::_internal_m_author(int index) const {
return m_author_.Get(index);
}
inline const ::proto_util_converter::testing::Author& Cyclic::m_author(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Cyclic.m_author)
return _internal_m_author(index);
}
inline ::proto_util_converter::testing::Author* Cyclic::_internal_add_m_author() {
return m_author_.Add();
}
inline ::proto_util_converter::testing::Author* Cyclic::add_m_author() {
// @@protoc_insertion_point(field_add:proto_util_converter.testing.Cyclic.m_author)
return _internal_add_m_author();
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::proto_util_converter::testing::Author >&
Cyclic::m_author() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.Cyclic.m_author)
return m_author_;
}
// optional .proto_util_converter.testing.Cyclic m_cyclic = 4;
inline bool Cyclic::_internal_has_m_cyclic() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
PROTOBUF_ASSUME(!value || m_cyclic_ != nullptr);
return value;
}
inline bool Cyclic::has_m_cyclic() const {
return _internal_has_m_cyclic();
}
inline void Cyclic::clear_m_cyclic() {
if (m_cyclic_ != nullptr) m_cyclic_->Clear();
_has_bits_[0] &= ~0x00000004u;
}
inline const ::proto_util_converter::testing::Cyclic& Cyclic::_internal_m_cyclic() const {
const ::proto_util_converter::testing::Cyclic* p = m_cyclic_;
return p != nullptr ? *p : reinterpret_cast<const ::proto_util_converter::testing::Cyclic&>(
::proto_util_converter::testing::_Cyclic_default_instance_);
}
inline const ::proto_util_converter::testing::Cyclic& Cyclic::m_cyclic() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.Cyclic.m_cyclic)
return _internal_m_cyclic();
}
inline void Cyclic::unsafe_arena_set_allocated_m_cyclic(
::proto_util_converter::testing::Cyclic* m_cyclic) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(m_cyclic_);
}
m_cyclic_ = m_cyclic;
if (m_cyclic) {
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:proto_util_converter.testing.Cyclic.m_cyclic)
}
inline ::proto_util_converter::testing::Cyclic* Cyclic::release_m_cyclic() {
_has_bits_[0] &= ~0x00000004u;
::proto_util_converter::testing::Cyclic* temp = m_cyclic_;
m_cyclic_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::proto_util_converter::testing::Cyclic* Cyclic::unsafe_arena_release_m_cyclic() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.Cyclic.m_cyclic)
_has_bits_[0] &= ~0x00000004u;
::proto_util_converter::testing::Cyclic* temp = m_cyclic_;
m_cyclic_ = nullptr;
return temp;
}
inline ::proto_util_converter::testing::Cyclic* Cyclic::_internal_mutable_m_cyclic() {
_has_bits_[0] |= 0x00000004u;
if (m_cyclic_ == nullptr) {
auto* p = CreateMaybeMessage<::proto_util_converter::testing::Cyclic>(GetArena());
m_cyclic_ = p;
}
return m_cyclic_;
}
inline ::proto_util_converter::testing::Cyclic* Cyclic::mutable_m_cyclic() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.Cyclic.m_cyclic)
return _internal_mutable_m_cyclic();
}
inline void Cyclic::set_allocated_m_cyclic(::proto_util_converter::testing::Cyclic* m_cyclic) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete m_cyclic_;
}
if (m_cyclic) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(m_cyclic);
if (message_arena != submessage_arena) {
m_cyclic = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, m_cyclic, submessage_arena);
}
_has_bits_[0] |= 0x00000004u;
} else {
_has_bits_[0] &= ~0x00000004u;
}
m_cyclic_ = m_cyclic;
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.Cyclic.m_cyclic)
}
// -------------------------------------------------------------------
// TestJsonName1
// optional int32 one_value = 1 [json_name = "value"];
inline bool TestJsonName1::_internal_has_one_value() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool TestJsonName1::has_one_value() const {
return _internal_has_one_value();
}
inline void TestJsonName1::clear_one_value() {
one_value_ = 0;
_has_bits_[0] &= ~0x00000001u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TestJsonName1::_internal_one_value() const {
return one_value_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TestJsonName1::one_value() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestJsonName1.one_value)
return _internal_one_value();
}
inline void TestJsonName1::_internal_set_one_value(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000001u;
one_value_ = value;
}
inline void TestJsonName1::set_one_value(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_one_value(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestJsonName1.one_value)
}
// -------------------------------------------------------------------
// TestJsonName2
// optional int32 another_value = 1 [json_name = "value"];
inline bool TestJsonName2::_internal_has_another_value() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool TestJsonName2::has_another_value() const {
return _internal_has_another_value();
}
inline void TestJsonName2::clear_another_value() {
another_value_ = 0;
_has_bits_[0] &= ~0x00000001u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TestJsonName2::_internal_another_value() const {
return another_value_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TestJsonName2::another_value() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestJsonName2.another_value)
return _internal_another_value();
}
inline void TestJsonName2::_internal_set_another_value(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000001u;
another_value_ = value;
}
inline void TestJsonName2::set_another_value(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_another_value(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestJsonName2.another_value)
}
// -------------------------------------------------------------------
// TestPrimitiveFieldsWithSameJsonName
// optional string val_str1 = 1;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_str1() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_str1() const {
return _internal_has_val_str1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_str1() {
val_str1_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& TestPrimitiveFieldsWithSameJsonName::val_str1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str1)
return _internal_val_str1();
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_str1(const std::string& value) {
_internal_set_val_str1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str1)
}
inline std::string* TestPrimitiveFieldsWithSameJsonName::mutable_val_str1() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str1)
return _internal_mutable_val_str1();
}
inline const std::string& TestPrimitiveFieldsWithSameJsonName::_internal_val_str1() const {
return val_str1_.Get();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_str1(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
val_str1_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_str1(std::string&& value) {
_has_bits_[0] |= 0x00000001u;
val_str1_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str1)
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_str1(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000001u;
val_str1_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str1)
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_str1(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000001u;
val_str1_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str1)
}
inline std::string* TestPrimitiveFieldsWithSameJsonName::_internal_mutable_val_str1() {
_has_bits_[0] |= 0x00000001u;
return val_str1_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* TestPrimitiveFieldsWithSameJsonName::release_val_str1() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str1)
if (!_internal_has_val_str1()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return val_str1_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void TestPrimitiveFieldsWithSameJsonName::set_allocated_val_str1(std::string* val_str1) {
if (val_str1 != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
val_str1_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), val_str1,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str1)
}
// optional string val_str_1 = 2;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_str_1() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_str_1() const {
return _internal_has_val_str_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_str_1() {
val_str_1_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& TestPrimitiveFieldsWithSameJsonName::val_str_1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str_1)
return _internal_val_str_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_str_1(const std::string& value) {
_internal_set_val_str_1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str_1)
}
inline std::string* TestPrimitiveFieldsWithSameJsonName::mutable_val_str_1() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str_1)
return _internal_mutable_val_str_1();
}
inline const std::string& TestPrimitiveFieldsWithSameJsonName::_internal_val_str_1() const {
return val_str_1_.Get();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_str_1(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
val_str_1_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_str_1(std::string&& value) {
_has_bits_[0] |= 0x00000002u;
val_str_1_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str_1)
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_str_1(const char* value) {
GOOGLE_DCHECK(value != nullptr);
_has_bits_[0] |= 0x00000002u;
val_str_1_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str_1)
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_str_1(const char* value,
size_t size) {
_has_bits_[0] |= 0x00000002u;
val_str_1_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str_1)
}
inline std::string* TestPrimitiveFieldsWithSameJsonName::_internal_mutable_val_str_1() {
_has_bits_[0] |= 0x00000002u;
return val_str_1_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* TestPrimitiveFieldsWithSameJsonName::release_val_str_1() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str_1)
if (!_internal_has_val_str_1()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return val_str_1_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void TestPrimitiveFieldsWithSameJsonName::set_allocated_val_str_1(std::string* val_str_1) {
if (val_str_1 != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
val_str_1_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), val_str_1,
GetArena());
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_str_1)
}
// optional int32 val_int321 = 3;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_int321() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_int321() const {
return _internal_has_val_int321();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_int321() {
val_int321_ = 0;
_has_bits_[0] &= ~0x00000004u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TestPrimitiveFieldsWithSameJsonName::_internal_val_int321() const {
return val_int321_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TestPrimitiveFieldsWithSameJsonName::val_int321() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_int321)
return _internal_val_int321();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_int321(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000004u;
val_int321_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_int321(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_val_int321(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_int321)
}
// optional int32 val_int32_1 = 4;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_int32_1() const {
bool value = (_has_bits_[0] & 0x00000008u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_int32_1() const {
return _internal_has_val_int32_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_int32_1() {
val_int32_1_ = 0;
_has_bits_[0] &= ~0x00000008u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TestPrimitiveFieldsWithSameJsonName::_internal_val_int32_1() const {
return val_int32_1_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 TestPrimitiveFieldsWithSameJsonName::val_int32_1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_int32_1)
return _internal_val_int32_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_int32_1(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000008u;
val_int32_1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_int32_1(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_val_int32_1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_int32_1)
}
// optional uint32 val_uint321 = 5;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_uint321() const {
bool value = (_has_bits_[0] & 0x00000010u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_uint321() const {
return _internal_has_val_uint321();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_uint321() {
val_uint321_ = 0u;
_has_bits_[0] &= ~0x00000010u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TestPrimitiveFieldsWithSameJsonName::_internal_val_uint321() const {
return val_uint321_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TestPrimitiveFieldsWithSameJsonName::val_uint321() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_uint321)
return _internal_val_uint321();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_uint321(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000010u;
val_uint321_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_uint321(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_set_val_uint321(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_uint321)
}
// optional uint32 val_uint32_1 = 6;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_uint32_1() const {
bool value = (_has_bits_[0] & 0x00000020u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_uint32_1() const {
return _internal_has_val_uint32_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_uint32_1() {
val_uint32_1_ = 0u;
_has_bits_[0] &= ~0x00000020u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TestPrimitiveFieldsWithSameJsonName::_internal_val_uint32_1() const {
return val_uint32_1_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint32 TestPrimitiveFieldsWithSameJsonName::val_uint32_1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_uint32_1)
return _internal_val_uint32_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_uint32_1(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_has_bits_[0] |= 0x00000020u;
val_uint32_1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_uint32_1(::PROTOBUF_NAMESPACE_ID::uint32 value) {
_internal_set_val_uint32_1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_uint32_1)
}
// optional int64 val_int641 = 7;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_int641() const {
bool value = (_has_bits_[0] & 0x00000040u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_int641() const {
return _internal_has_val_int641();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_int641() {
val_int641_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00000040u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 TestPrimitiveFieldsWithSameJsonName::_internal_val_int641() const {
return val_int641_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 TestPrimitiveFieldsWithSameJsonName::val_int641() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_int641)
return _internal_val_int641();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_int641(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000040u;
val_int641_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_int641(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_val_int641(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_int641)
}
// optional int64 val_int64_1 = 8;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_int64_1() const {
bool value = (_has_bits_[0] & 0x00000080u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_int64_1() const {
return _internal_has_val_int64_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_int64_1() {
val_int64_1_ = PROTOBUF_LONGLONG(0);
_has_bits_[0] &= ~0x00000080u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 TestPrimitiveFieldsWithSameJsonName::_internal_val_int64_1() const {
return val_int64_1_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 TestPrimitiveFieldsWithSameJsonName::val_int64_1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_int64_1)
return _internal_val_int64_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_int64_1(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000080u;
val_int64_1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_int64_1(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_val_int64_1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_int64_1)
}
// optional uint64 val_uint641 = 9;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_uint641() const {
bool value = (_has_bits_[0] & 0x00000100u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_uint641() const {
return _internal_has_val_uint641();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_uint641() {
val_uint641_ = PROTOBUF_ULONGLONG(0);
_has_bits_[0] &= ~0x00000100u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 TestPrimitiveFieldsWithSameJsonName::_internal_val_uint641() const {
return val_uint641_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 TestPrimitiveFieldsWithSameJsonName::val_uint641() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_uint641)
return _internal_val_uint641();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_uint641(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_has_bits_[0] |= 0x00000100u;
val_uint641_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_uint641(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_set_val_uint641(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_uint641)
}
// optional uint64 val_uint64_1 = 10;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_uint64_1() const {
bool value = (_has_bits_[0] & 0x00000200u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_uint64_1() const {
return _internal_has_val_uint64_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_uint64_1() {
val_uint64_1_ = PROTOBUF_ULONGLONG(0);
_has_bits_[0] &= ~0x00000200u;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 TestPrimitiveFieldsWithSameJsonName::_internal_val_uint64_1() const {
return val_uint64_1_;
}
inline ::PROTOBUF_NAMESPACE_ID::uint64 TestPrimitiveFieldsWithSameJsonName::val_uint64_1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_uint64_1)
return _internal_val_uint64_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_uint64_1(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_has_bits_[0] |= 0x00000200u;
val_uint64_1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_uint64_1(::PROTOBUF_NAMESPACE_ID::uint64 value) {
_internal_set_val_uint64_1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_uint64_1)
}
// optional bool val_bool1 = 11;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_bool1() const {
bool value = (_has_bits_[0] & 0x00000400u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_bool1() const {
return _internal_has_val_bool1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_bool1() {
val_bool1_ = false;
_has_bits_[0] &= ~0x00000400u;
}
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_val_bool1() const {
return val_bool1_;
}
inline bool TestPrimitiveFieldsWithSameJsonName::val_bool1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_bool1)
return _internal_val_bool1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_bool1(bool value) {
_has_bits_[0] |= 0x00000400u;
val_bool1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_bool1(bool value) {
_internal_set_val_bool1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_bool1)
}
// optional bool val_bool_1 = 12;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_bool_1() const {
bool value = (_has_bits_[0] & 0x00000800u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_bool_1() const {
return _internal_has_val_bool_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_bool_1() {
val_bool_1_ = false;
_has_bits_[0] &= ~0x00000800u;
}
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_val_bool_1() const {
return val_bool_1_;
}
inline bool TestPrimitiveFieldsWithSameJsonName::val_bool_1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_bool_1)
return _internal_val_bool_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_bool_1(bool value) {
_has_bits_[0] |= 0x00000800u;
val_bool_1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_bool_1(bool value) {
_internal_set_val_bool_1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_bool_1)
}
// optional double val_double1 = 13;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_double1() const {
bool value = (_has_bits_[0] & 0x00002000u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_double1() const {
return _internal_has_val_double1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_double1() {
val_double1_ = 0;
_has_bits_[0] &= ~0x00002000u;
}
inline double TestPrimitiveFieldsWithSameJsonName::_internal_val_double1() const {
return val_double1_;
}
inline double TestPrimitiveFieldsWithSameJsonName::val_double1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_double1)
return _internal_val_double1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_double1(double value) {
_has_bits_[0] |= 0x00002000u;
val_double1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_double1(double value) {
_internal_set_val_double1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_double1)
}
// optional double val_double_1 = 14;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_double_1() const {
bool value = (_has_bits_[0] & 0x00004000u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_double_1() const {
return _internal_has_val_double_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_double_1() {
val_double_1_ = 0;
_has_bits_[0] &= ~0x00004000u;
}
inline double TestPrimitiveFieldsWithSameJsonName::_internal_val_double_1() const {
return val_double_1_;
}
inline double TestPrimitiveFieldsWithSameJsonName::val_double_1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_double_1)
return _internal_val_double_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_double_1(double value) {
_has_bits_[0] |= 0x00004000u;
val_double_1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_double_1(double value) {
_internal_set_val_double_1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_double_1)
}
// optional float val_float1 = 15;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_float1() const {
bool value = (_has_bits_[0] & 0x00001000u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_float1() const {
return _internal_has_val_float1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_float1() {
val_float1_ = 0;
_has_bits_[0] &= ~0x00001000u;
}
inline float TestPrimitiveFieldsWithSameJsonName::_internal_val_float1() const {
return val_float1_;
}
inline float TestPrimitiveFieldsWithSameJsonName::val_float1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_float1)
return _internal_val_float1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_float1(float value) {
_has_bits_[0] |= 0x00001000u;
val_float1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_float1(float value) {
_internal_set_val_float1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_float1)
}
// optional float val_float_1 = 16;
inline bool TestPrimitiveFieldsWithSameJsonName::_internal_has_val_float_1() const {
bool value = (_has_bits_[0] & 0x00008000u) != 0;
return value;
}
inline bool TestPrimitiveFieldsWithSameJsonName::has_val_float_1() const {
return _internal_has_val_float_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::clear_val_float_1() {
val_float_1_ = 0;
_has_bits_[0] &= ~0x00008000u;
}
inline float TestPrimitiveFieldsWithSameJsonName::_internal_val_float_1() const {
return val_float_1_;
}
inline float TestPrimitiveFieldsWithSameJsonName::val_float_1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_float_1)
return _internal_val_float_1();
}
inline void TestPrimitiveFieldsWithSameJsonName::_internal_set_val_float_1(float value) {
_has_bits_[0] |= 0x00008000u;
val_float_1_ = value;
}
inline void TestPrimitiveFieldsWithSameJsonName::set_val_float_1(float value) {
_internal_set_val_float_1(value);
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestPrimitiveFieldsWithSameJsonName.val_float_1)
}
// -------------------------------------------------------------------
// TestRepeatedFieldsWithSameJsonName
// repeated string rep_str1 = 1;
inline int TestRepeatedFieldsWithSameJsonName::_internal_rep_str1_size() const {
return rep_str1_.size();
}
inline int TestRepeatedFieldsWithSameJsonName::rep_str1_size() const {
return _internal_rep_str1_size();
}
inline void TestRepeatedFieldsWithSameJsonName::clear_rep_str1() {
rep_str1_.Clear();
}
inline std::string* TestRepeatedFieldsWithSameJsonName::add_rep_str1() {
// @@protoc_insertion_point(field_add_mutable:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
return _internal_add_rep_str1();
}
inline const std::string& TestRepeatedFieldsWithSameJsonName::_internal_rep_str1(int index) const {
return rep_str1_.Get(index);
}
inline const std::string& TestRepeatedFieldsWithSameJsonName::rep_str1(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
return _internal_rep_str1(index);
}
inline std::string* TestRepeatedFieldsWithSameJsonName::mutable_rep_str1(int index) {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
return rep_str1_.Mutable(index);
}
inline void TestRepeatedFieldsWithSameJsonName::set_rep_str1(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
rep_str1_.Mutable(index)->assign(value);
}
inline void TestRepeatedFieldsWithSameJsonName::set_rep_str1(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
rep_str1_.Mutable(index)->assign(std::move(value));
}
inline void TestRepeatedFieldsWithSameJsonName::set_rep_str1(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
rep_str1_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
}
inline void TestRepeatedFieldsWithSameJsonName::set_rep_str1(int index, const char* value, size_t size) {
rep_str1_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
}
inline std::string* TestRepeatedFieldsWithSameJsonName::_internal_add_rep_str1() {
return rep_str1_.Add();
}
inline void TestRepeatedFieldsWithSameJsonName::add_rep_str1(const std::string& value) {
rep_str1_.Add()->assign(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
}
inline void TestRepeatedFieldsWithSameJsonName::add_rep_str1(std::string&& value) {
rep_str1_.Add(std::move(value));
// @@protoc_insertion_point(field_add:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
}
inline void TestRepeatedFieldsWithSameJsonName::add_rep_str1(const char* value) {
GOOGLE_DCHECK(value != nullptr);
rep_str1_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
}
inline void TestRepeatedFieldsWithSameJsonName::add_rep_str1(const char* value, size_t size) {
rep_str1_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
TestRepeatedFieldsWithSameJsonName::rep_str1() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
return rep_str1_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
TestRepeatedFieldsWithSameJsonName::mutable_rep_str1() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str1)
return &rep_str1_;
}
// repeated string rep_str_1 = 2;
inline int TestRepeatedFieldsWithSameJsonName::_internal_rep_str_1_size() const {
return rep_str_1_.size();
}
inline int TestRepeatedFieldsWithSameJsonName::rep_str_1_size() const {
return _internal_rep_str_1_size();
}
inline void TestRepeatedFieldsWithSameJsonName::clear_rep_str_1() {
rep_str_1_.Clear();
}
inline std::string* TestRepeatedFieldsWithSameJsonName::add_rep_str_1() {
// @@protoc_insertion_point(field_add_mutable:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
return _internal_add_rep_str_1();
}
inline const std::string& TestRepeatedFieldsWithSameJsonName::_internal_rep_str_1(int index) const {
return rep_str_1_.Get(index);
}
inline const std::string& TestRepeatedFieldsWithSameJsonName::rep_str_1(int index) const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
return _internal_rep_str_1(index);
}
inline std::string* TestRepeatedFieldsWithSameJsonName::mutable_rep_str_1(int index) {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
return rep_str_1_.Mutable(index);
}
inline void TestRepeatedFieldsWithSameJsonName::set_rep_str_1(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
rep_str_1_.Mutable(index)->assign(value);
}
inline void TestRepeatedFieldsWithSameJsonName::set_rep_str_1(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
rep_str_1_.Mutable(index)->assign(std::move(value));
}
inline void TestRepeatedFieldsWithSameJsonName::set_rep_str_1(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
rep_str_1_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
}
inline void TestRepeatedFieldsWithSameJsonName::set_rep_str_1(int index, const char* value, size_t size) {
rep_str_1_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
}
inline std::string* TestRepeatedFieldsWithSameJsonName::_internal_add_rep_str_1() {
return rep_str_1_.Add();
}
inline void TestRepeatedFieldsWithSameJsonName::add_rep_str_1(const std::string& value) {
rep_str_1_.Add()->assign(value);
// @@protoc_insertion_point(field_add:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
}
inline void TestRepeatedFieldsWithSameJsonName::add_rep_str_1(std::string&& value) {
rep_str_1_.Add(std::move(value));
// @@protoc_insertion_point(field_add:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
}
inline void TestRepeatedFieldsWithSameJsonName::add_rep_str_1(const char* value) {
GOOGLE_DCHECK(value != nullptr);
rep_str_1_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
}
inline void TestRepeatedFieldsWithSameJsonName::add_rep_str_1(const char* value, size_t size) {
rep_str_1_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
TestRepeatedFieldsWithSameJsonName::rep_str_1() const {
// @@protoc_insertion_point(field_list:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
return rep_str_1_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
TestRepeatedFieldsWithSameJsonName::mutable_rep_str_1() {
// @@protoc_insertion_point(field_mutable_list:proto_util_converter.testing.TestRepeatedFieldsWithSameJsonName.rep_str_1)
return &rep_str_1_;
}
// -------------------------------------------------------------------
// TestMessageFieldsWithSameJsonName
// optional .proto_util_converter.testing.Primitive prim1 = 1;
inline bool TestMessageFieldsWithSameJsonName::_internal_has_prim1() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
PROTOBUF_ASSUME(!value || prim1_ != nullptr);
return value;
}
inline bool TestMessageFieldsWithSameJsonName::has_prim1() const {
return _internal_has_prim1();
}
inline void TestMessageFieldsWithSameJsonName::clear_prim1() {
if (prim1_ != nullptr) prim1_->Clear();
_has_bits_[0] &= ~0x00000001u;
}
inline const ::proto_util_converter::testing::Primitive& TestMessageFieldsWithSameJsonName::_internal_prim1() const {
const ::proto_util_converter::testing::Primitive* p = prim1_;
return p != nullptr ? *p : reinterpret_cast<const ::proto_util_converter::testing::Primitive&>(
::proto_util_converter::testing::_Primitive_default_instance_);
}
inline const ::proto_util_converter::testing::Primitive& TestMessageFieldsWithSameJsonName::prim1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim1)
return _internal_prim1();
}
inline void TestMessageFieldsWithSameJsonName::unsafe_arena_set_allocated_prim1(
::proto_util_converter::testing::Primitive* prim1) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(prim1_);
}
prim1_ = prim1;
if (prim1) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim1)
}
inline ::proto_util_converter::testing::Primitive* TestMessageFieldsWithSameJsonName::release_prim1() {
_has_bits_[0] &= ~0x00000001u;
::proto_util_converter::testing::Primitive* temp = prim1_;
prim1_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::proto_util_converter::testing::Primitive* TestMessageFieldsWithSameJsonName::unsafe_arena_release_prim1() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim1)
_has_bits_[0] &= ~0x00000001u;
::proto_util_converter::testing::Primitive* temp = prim1_;
prim1_ = nullptr;
return temp;
}
inline ::proto_util_converter::testing::Primitive* TestMessageFieldsWithSameJsonName::_internal_mutable_prim1() {
_has_bits_[0] |= 0x00000001u;
if (prim1_ == nullptr) {
auto* p = CreateMaybeMessage<::proto_util_converter::testing::Primitive>(GetArena());
prim1_ = p;
}
return prim1_;
}
inline ::proto_util_converter::testing::Primitive* TestMessageFieldsWithSameJsonName::mutable_prim1() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim1)
return _internal_mutable_prim1();
}
inline void TestMessageFieldsWithSameJsonName::set_allocated_prim1(::proto_util_converter::testing::Primitive* prim1) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete prim1_;
}
if (prim1) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(prim1);
if (message_arena != submessage_arena) {
prim1 = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, prim1, submessage_arena);
}
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
prim1_ = prim1;
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim1)
}
// optional .proto_util_converter.testing.Primitive prim_1 = 2;
inline bool TestMessageFieldsWithSameJsonName::_internal_has_prim_1() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
PROTOBUF_ASSUME(!value || prim_1_ != nullptr);
return value;
}
inline bool TestMessageFieldsWithSameJsonName::has_prim_1() const {
return _internal_has_prim_1();
}
inline void TestMessageFieldsWithSameJsonName::clear_prim_1() {
if (prim_1_ != nullptr) prim_1_->Clear();
_has_bits_[0] &= ~0x00000002u;
}
inline const ::proto_util_converter::testing::Primitive& TestMessageFieldsWithSameJsonName::_internal_prim_1() const {
const ::proto_util_converter::testing::Primitive* p = prim_1_;
return p != nullptr ? *p : reinterpret_cast<const ::proto_util_converter::testing::Primitive&>(
::proto_util_converter::testing::_Primitive_default_instance_);
}
inline const ::proto_util_converter::testing::Primitive& TestMessageFieldsWithSameJsonName::prim_1() const {
// @@protoc_insertion_point(field_get:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim_1)
return _internal_prim_1();
}
inline void TestMessageFieldsWithSameJsonName::unsafe_arena_set_allocated_prim_1(
::proto_util_converter::testing::Primitive* prim_1) {
if (GetArena() == nullptr) {
delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(prim_1_);
}
prim_1_ = prim_1;
if (prim_1) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim_1)
}
inline ::proto_util_converter::testing::Primitive* TestMessageFieldsWithSameJsonName::release_prim_1() {
_has_bits_[0] &= ~0x00000002u;
::proto_util_converter::testing::Primitive* temp = prim_1_;
prim_1_ = nullptr;
if (GetArena() != nullptr) {
temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp);
}
return temp;
}
inline ::proto_util_converter::testing::Primitive* TestMessageFieldsWithSameJsonName::unsafe_arena_release_prim_1() {
// @@protoc_insertion_point(field_release:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim_1)
_has_bits_[0] &= ~0x00000002u;
::proto_util_converter::testing::Primitive* temp = prim_1_;
prim_1_ = nullptr;
return temp;
}
inline ::proto_util_converter::testing::Primitive* TestMessageFieldsWithSameJsonName::_internal_mutable_prim_1() {
_has_bits_[0] |= 0x00000002u;
if (prim_1_ == nullptr) {
auto* p = CreateMaybeMessage<::proto_util_converter::testing::Primitive>(GetArena());
prim_1_ = p;
}
return prim_1_;
}
inline ::proto_util_converter::testing::Primitive* TestMessageFieldsWithSameJsonName::mutable_prim_1() {
// @@protoc_insertion_point(field_mutable:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim_1)
return _internal_mutable_prim_1();
}
inline void TestMessageFieldsWithSameJsonName::set_allocated_prim_1(::proto_util_converter::testing::Primitive* prim_1) {
::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena();
if (message_arena == nullptr) {
delete prim_1_;
}
if (prim_1) {
::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena =
::PROTOBUF_NAMESPACE_ID::Arena::GetArena(prim_1);
if (message_arena != submessage_arena) {
prim_1 = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage(
message_arena, prim_1, submessage_arena);
}
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
prim_1_ = prim_1;
// @@protoc_insertion_point(field_set_allocated:proto_util_converter.testing.TestMessageFieldsWithSameJsonName.prim_1)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace testing
} // namespace proto_util_converter
PROTOBUF_NAMESPACE_OPEN
template <> struct is_proto_enum< ::proto_util_converter::testing::Book_Type> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::proto_util_converter::testing::Book_Type>() {
return ::proto_util_converter::testing::Book_Type_descriptor();
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2futil_2finternal_2ftestdata_2fbooks_2eproto
| [
"siddharth.sng@gmail.com"
] | siddharth.sng@gmail.com |
a46dee37eb2122644ecc8f64d99b665b56b81d93 | d01b150a730f4f941c541bb400bbda23edc9d8b1 | /Beginner/strng.cpp | d227a1c55222005fc1d6ca8e557f69f806b50e5d | [] | no_license | limina12/codekata | f763987f15e57a582ee0614597dbee0ce39fe527 | 05636114b7f764afbfef5bac5b92b464f99449d8 | refs/heads/master | 2021-09-10T23:21:02.898060 | 2018-04-04T06:48:01 | 2018-04-04T06:48:01 | 114,728,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 199 | cpp | #include <iostream>
#include<string.h>
using namespace std;
int main() {
char str[15];
int len,n,i;
cin>>str;
cin>>n;
len=strlen(str);
for(i=n;i<=len;i++)
{
cout<<str[i];
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
1d1a89c1bb1f046eaa6cf3bfdbb1c4e70aa8c51c | 1093b8a3dce579a3d9a1773d668134852a8a1113 | /Main.cpp | e145a25a46bce4ed54c6b7ac0b55e6b19b3eb827 | [] | no_license | guivmc/CPP_Ex_4 | 2f90bd083b8c26fa68f5a18fff7b54889a086e10 | b9b5f5749b11b2fb0f53b6914d282af4f14e0f43 | refs/heads/master | 2020-04-11T01:22:22.519065 | 2018-12-12T11:17:44 | 2018-12-12T11:17:44 | 161,413,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,020 | cpp | // ExDeSexta4.cpp : Este arquivo contém a função 'main'. A execução do programa começa e termina ali.
//
#include "pch.h"
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
int findSmallestInVector(int num, int pos, std::vector<int> vec)
{
if (pos >= vec.size()) return num;
if (num >= vec.at(pos))
{
num = vec.at(pos);
return findSmallestInVector(num, (pos + 1), vec);
}
else
{
return num;
}
}
void test(int size, int now)
{
if (size < 1 || size > 100) return;
std::vector<std::string> myListNames;
std::vector<int> myListGrades;
int smallest, pos = 0;
//populate
for (int i = 0; i < size; i++)
{
std::string name;
std::cin >> name;
name = name.substr(0, 19);
myListNames.push_back(name);
int grade;
std::cin >> grade;
myListGrades.push_back(grade);
}
smallest = findSmallestInVector(INT_MAX, 0, myListGrades);
for (int i = 0; i < size; i++)
if (smallest == myListGrades.at(i))
pos = i;
std::cout << "Instance: ";
std::cout << now << std::endl;
std::cout << "Failed: " + myListNames.at(pos) << std::endl;
}
int main()
{
int size = 1, now = 1;
while (size != 0)
{
std::cin >> size;
test(size, now);
now++;
}
}
// Executar programa: Ctrl + F5 ou Menu Depurar > Iniciar Sem Depuração
// Depurar programa: F5 ou menu Depurar > Iniciar Depuração
// Dicas para Começar:
// 1. Use a janela do Gerenciador de Soluções para adicionar/gerenciar arquivos
// 2. Use a janela do Team Explorer para conectar-se ao controle do código-fonte
// 3. Use a janela de Saída para ver mensagens de saída do build e outras mensagens
// 4. Use a janela Lista de Erros para exibir erros
// 5. Ir Para o Projeto > Adicionar Novo Item para criar novos arquivos de código, ou Projeto > Adicionar Item Existente para adicionar arquivos de código existentes ao projeto
// 6. No futuro, para abrir este projeto novamente, vá para Arquivo > Abrir > Projeto e selecione o arquivo. sln
| [
"noreply@github.com"
] | noreply@github.com |
021bfed473b5099f5d94bcbd044e0a87cde5c1b4 | 6dc0ab4ee026c952680a2fc7d37fc2646b360864 | /src/APFELgrid/APFELgrid.h | 37625e9a3d6844f5d9af7abe0b40287395b6e95f | [
"MIT"
] | permissive | nhartland/APFELgrid | c3c6dd4498af8b93b5840892fccda8b4be4358e0 | 3ca47aab85b76a5e1e677f7e39bfcf8152f01800 | refs/heads/master | 2021-01-14T08:22:03.840847 | 2020-05-11T13:38:55 | 2020-05-11T13:38:55 | 50,047,730 | 1 | 2 | NOASSERTION | 2023-06-03T10:25:19 | 2016-01-20T17:37:25 | C++ | UTF-8 | C++ | false | false | 3,703 | h | // The MIT License (MIT)
// Copyright (c) 2016 Nathan Hartland
// 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 <string>
#include "fastkernel.h"
// Forward decls
namespace appl { class grid; }
namespace APFELgrid
{
// ************************ Public utility functions **************************
// These functions are for use when initialising APFEL kinematics such that
// they are suitable for the relevant APPLgrid.
// Returns the minimum value in the APPLgrid x-grid
// If nonzero is true, returns the smallest x-value regardless of weight
// if false, returns the smallest x-value associated with a non-zero weight
double get_appl_Xmin(appl::grid const& g, const bool& nonzero);
// Returns the minimum (Q2min) and maximum (Q2max) reach in scale of the applgrid g
void get_appl_Q2lims(appl::grid const& g, double& Q2min, double& Q2max);
// ************************ FK table computation **************************
// Performs the combination of an APPLgrid g with evolution factors provided
// by APFEL, resulting in a new FK table. Required arguments are the initial
// scale for the FK tables (Q0), the name of the produced table (name), the appl::grid (g),
// the path to the appl::grid (gridfile) and an optional appl::grid directory (directory).
NNPDF::FKTable<double>* computeFK( double const& Q0, std::string const& name, appl::grid const& g, std::string const& gridfile, std::string directory = "grid" );
}
namespace NNPDF
{
/**
* \class FKGenerator
* \brief Class for filling FastKernel tables
*/
class FKGenerator : public FKTable<double>
{
private:
FKGenerator(); //!< Disable default constructor
FKGenerator( const FKGenerator& ); //!< Disable default copy-constructor
FKGenerator& operator=(const FKGenerator&); //!< Disable copy-assignment
public:
FKGenerator( std::istream& ); // Constructor
virtual ~FKGenerator(); //!< Destructor
// Fill the FKTable
void Fill( int const& d, // Datapoint index
int const& ix1, // First x-index
int const& ix2, // Second x-index
size_t const& ifl1, // First flavour index
size_t const& ifl2, // Second flavour index
double const& isig // FK Value
);
// DIS version of Fill
void Fill( int const& d, // Datapoint index
int const& ix, // x-index
size_t const& ifl, // flavour index
double const& isig // FK Value
);
};
} | [
"nathan.hartland@physics.ox.ac.uk"
] | nathan.hartland@physics.ox.ac.uk |
96f39800e12974d91f9ba0a57a7e14233be12b5a | 1e31dd6bb149e64ae236ea16e76269cfbea25314 | /standalone/PointMerger/gui/main.cpp | 8a22743a868a6b72321c56758741b516db5318ed | [] | no_license | Geoany/ttk | 2bbe1df9565916b3af0149bd11dadcd14824905a | 6a78e7e558f13fafa8e49d0ad3e4e4a7b3343de5 | refs/heads/master | 2020-03-10T00:52:04.694684 | 2018-04-05T18:44:52 | 2018-04-05T18:44:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,145 | cpp | /// \author Julien Tierny <julien.tierny@lip6.fr>.
/// \date February 2018.
///
/// \brief point merger program.
// include the local headers
#include <ttkPointMerger.h>
#include <ttkUserInterfaceBase.h>
vtkUserInterface<ttkPointMerger> program;
class myKeyHandler : public ttkKeyHandler{
public:
int OnKeyPress(vtkRenderWindowInteractor *interactor, string &key){
stringstream msg;
msg << "[myKeyHandler] The user pressed the key `" << key << "'." << endl;
dMsg(cout, msg.str(), infoMsg);
return 0;
}
};
int main(int argc, char **argv) {
bool boundaryOnly = true;
double distanceThreshold = 0.001;
program.parser_.setOption("b", &boundaryOnly, "Boundary only");
program.parser_.setArgument("t", &distanceThreshold,
"Distance threshold", true);
int ret = program.init(argc, argv);
if(ret != 0)
return ret;
program.ttkObject_->SetBoundaryOnly(boundaryOnly);
program.ttkObject_->SetDistanceThreshold(distanceThreshold);
myKeyHandler myHandler;
program.setKeyHandler(&myHandler);
program.run();
return 0;
}
| [
"julien.tierny@gmail.com"
] | julien.tierny@gmail.com |
95d511432fbfb0a995257ffaa5b14d06cff85ba6 | 7c3118cd363f1e8208294436932a15aaed22be14 | /Dice Game/Game.hpp | b08455c312703f57dcb46a126a21ea4a80911bb4 | [] | no_license | djbauman/Cpp-Projects | 1cc9fa44168e5d4c473d83edca8d8911b06d58cf | 9132544f10c5cb0006bd83dc25f7ecf9ab391ef1 | refs/heads/master | 2023-01-23T17:40:34.728808 | 2018-05-28T22:50:13 | 2018-05-28T22:50:13 | 135,215,851 | 3 | 1 | null | 2023-02-01T15:12:33 | 2018-05-28T22:46:32 | C++ | UTF-8 | C++ | false | false | 997 | hpp | /*********************************************************************
* Author: Daniel Bauman
* Date: 7/11/2017
* Description: This header file contains the class declaration for
* the Game class.
*********************************************************************/
#ifndef GAME_HPP
#define GAME_HPP
#include "LoadedDie.hpp"
class Game
{
private:
int turns; // Number of turns to be played
bool p1Loaded = false; // Whether Player 1 is using a loaded die
bool p2Loaded = false; // Whether Player 2 is using a loaded die
int p1Sides; // Number of sides on Player 1's die
int p2Sides; // Number of sides on Player 2's die
int p1Total = 0; // Total score for Player 1
int p2Total = 0; // Total score for Player 2
public:
int getP1Total(); // Returns Player 1's total score
int getP2Total(); // Returns Player 2's total score
void showState(); // Displays current player totals
void play(); // Gets inputs for starting conditions and runs the game
};
#endif | [
"danieljbauman@gmail.com"
] | danieljbauman@gmail.com |
be70bdac265ad755e2b8bcbc304bf3716796e48e | eda611194fa0cf6b016252e12aca65acde0f0a61 | /ZMPO_Lista3/CMenuItem.h | a6c6d76b0593bcc6a73b76d1a24d4b9088c6b90b | [] | no_license | Loreth/Menu-project | 7ec002ba3095c21453767dc5ff6bf0d1ccdc25de | d51d8c9ad8161695aadb602c300832010a91eedb | refs/heads/master | 2020-04-24T05:40:57.711636 | 2019-02-20T19:41:44 | 2019-02-20T19:41:44 | 171,737,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | h | #pragma once
#include <string>
using namespace std;
#define TEXT_INDICATOR '\''
#define TEXT_SEPARATOR ','
#define CHILD_SEPARATOR ';'
#define FAILURE_AT_POSITION "Blad odczytu na pozycji "
#define FAILURE_EXPECTED ", oczekiwano: "
class CMenuItem
{
public:
CMenuItem();
CMenuItem(string name, string command);
virtual ~CMenuItem();
virtual bool run() = 0;
string getName();
string getCommand();
void setName(string name);
void setCommand(string command);
virtual string toString() = 0;
protected:
string name;
string command;
};
| [
"kamil.przenioslo@gazeta.pl"
] | kamil.przenioslo@gazeta.pl |
254259642e56567090d5e5c1e82d30fa71944078 | 5214c82f7aa7382c51332ae6a3794ca6bfc3a42e | /kythe/cxx/common/kzip_writer.h | 3c375806c0e0c6250fc558ec71eab0cd6772bcd7 | [
"Apache-2.0",
"NCSA"
] | permissive | moul/kythe | 7eac3c108cb59d496d538683a5ef0843a35e194c | f9d97b299d6a5b2ebd224560b2ec506064dc4ace | refs/heads/master | 2023-08-31T12:54:34.642235 | 2023-08-30T20:46:58 | 2023-08-30T20:46:58 | 58,826,593 | 1 | 0 | Apache-2.0 | 2023-09-14T21:16:14 | 2016-05-14T19:37:49 | C++ | UTF-8 | C++ | false | false | 3,442 | h | /*
* Copyright 2018 The Kythe 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.
*/
#ifndef KYTHE_CXX_COMMON_KZIP_WRITER_H_
#define KYTHE_CXX_COMMON_KZIP_WRITER_H_
#include <zip.h>
#include <unordered_map>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "kythe/cxx/common/index_writer.h"
#include "kythe/cxx/common/kzip_encoding.h"
#include "kythe/proto/analysis.pb.h"
namespace kythe {
/// \brief Kzip implementation of IndexWriter.
/// see https://www.kythe.io/docs/kythe-kzip.html for format description.
class KzipWriter : public IndexWriterInterface {
public:
/// \brief Constructs a Kzip IndexWriter which will create and write to
/// \param path Path to the file to create. Must not currently exist.
/// \param encoding Encoding to use for compilation units.
static absl::StatusOr<IndexWriter> Create(
absl::string_view path, KzipEncoding encoding = DefaultEncoding());
/// \brief Constructs an IndexWriter from the libzip source pointer.
/// \param source zip_source_t to use as backing store.
/// See https://libzip.org/documentation/zip_source.html for ownership.
/// \param flags Flags to use when opening `source`.
/// \param encoding Encoding to use for compilation units.
static absl::StatusOr<IndexWriter> FromSource(
zip_source_t* source, KzipEncoding encoding = DefaultEncoding(),
int flags = ZIP_CREATE | ZIP_EXCL);
/// \brief Destroys the KzipWriter.
~KzipWriter() override;
/// \brief Writes the unit to the kzip file, returning its digest.
absl::StatusOr<std::string> WriteUnit(
const kythe::proto::IndexedCompilation& unit) override;
/// \brief Writes the file contents to the kzip file, returning their digest.
absl::StatusOr<std::string> WriteFile(absl::string_view content) override;
/// \brief Flushes accumulated writes and closes the kzip file.
/// Close must be called before the KzipWriter is destroyed!
absl::Status Close() override;
private:
using Path = std::string;
using Contents = std::string;
using FileMap = std::unordered_map<Path, Contents>;
explicit KzipWriter(zip_t* archive, KzipEncoding encoding);
absl::StatusOr<std::string> InsertFile(absl::string_view path,
absl::string_view content);
absl::Status InitializeArchive(zip_t* archive);
static KzipEncoding DefaultEncoding();
bool initialized_ = false; // Whether or not the `root` entry exists.
zip_t* archive_; // Owned, but must be manually deleted via `Close`.
// Memory for inserted files must be retained until close and
// we don't want to insert identical entries multiple times.
// This must be a node-based container to ensure pointer stability of the file
// contents.
FileMap contents_;
KzipEncoding encoding_;
};
} // namespace kythe
#endif // KYTHE_CXX_COMMON_KZIP_WRITER_H_
| [
"noreply@github.com"
] | noreply@github.com |
774f16bf8d67bdfb6eecf2591a18a83f5ab2d082 | 712723501b60b49575d0ceebc39c6a3205fbf1ba | /Software/Tests/TestMotion/TestMotion.ino | 0b74036f42582f17a56a05a6db247d966515ea42 | [
"MIT"
] | permissive | robdobsn/MugBot | 6c16fa26df84f5c282b30b20ebb25b44eb343e98 | e13842d1fbab652fbc255123b1c34f259e519f7a | refs/heads/master | 2021-01-19T00:36:19.510900 | 2019-10-20T08:50:47 | 2019-10-20T08:50:47 | 87,188,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,454 | ino | #include "application.h"
SYSTEM_MODE(MANUAL);
SYSTEM_THREAD(ENABLED);
#include <AccelStepper.h>
// Define the steppers and the pins they will use
AccelStepper cylinderStepper(1, A7, A6);
AccelStepper penStepper(1, A5, A4);
void setup()
{
// LED to blink
pinMode(D7, OUTPUT);
// Stepper Enable
pinMode(D4, OUTPUT);
digitalWrite(D4, true);
// Limit switch on linear
pinMode(D5, INPUT_PULLUP);
// Debug
Serial.begin(115200);
delay(5000);
Serial.printlnf("MugBot TestMotion motorEn(D4=%d) rot(A7=%d, A6=%d) lin(A5=%d, A4=%d)", D4, A7, A6, A5, A4);
}
bool particleConnectRequested = false;
unsigned long lastOutput = millis();
unsigned long lastStepPos = 0;
bool homePenStepper = true;
bool penStepperStarted = false;
int speedVal = 15000;
void loop()
{
bool limitSw = digitalRead(D5);
if (cylinderStepper.distanceToGo() <= 0)
{
// Random change to speed, position and acceleration
// Make sure we dont get 0 speed or accelerations
lastStepPos = lastStepPos + 3200 * ((rand() % 2 == 1) ? 1 : -1);
double maxSpeed = (rand() % 800) + 200;
double maxAccel = (rand() % 400) + 50;
cylinderStepper.moveTo(lastStepPos);
cylinderStepper.setMaxSpeed(maxSpeed);
cylinderStepper.setAcceleration(maxAccel);
/*cylinderStepper.moveTo(rand() % 200);
cylinderStepper.setMaxSpeed((rand() % 200) + 1);
cylinderStepper.setAcceleration((rand() % 200) + 1);*/
Serial.printlnf("Dist to go reqd = %ld, maxSpeed %f, maxAccel %f", cylinderStepper.distanceToGo(), maxSpeed, maxAccel);
}
if (millis() > lastOutput + 2000)
{
digitalWrite(D7, !digitalRead(D7));
lastOutput = millis();
Serial.printlnf("Cylinder to go = %ld, Pen to go %ld, limit sw %d", cylinderStepper.distanceToGo(), penStepper.distanceToGo(), limitSw);
}
cylinderStepper.run();
// Home sequence
if (homePenStepper)
{
if (limitSw)
{
homePenStepper = false;
penStepper.stop();
penStepper.setCurrentPosition(0);
penStepperStarted = false;
Serial.println("Pen stepper home - set 0");
}
else
{
if (!penStepperStarted)
{
Serial.println("Pen stepper moveto 2000000");
penStepper.moveTo(1000000);
penStepper.setMaxSpeed(speedVal);
penStepper.setAcceleration(speedVal);
speedVal += 1000;
if (speedVal > 20000)
speedVal = 20000;
penStepperStarted = true;
}
}
}
else
{
if (!penStepperStarted)
{
Serial.println("Pen stepper moveto -600000");
penStepper.moveTo(-600000);
penStepper.setMaxSpeed(speedVal);
penStepper.setAcceleration(speedVal);
speedVal += 1000;
penStepperStarted = true;
}
else if (penStepper.distanceToGo() == 0)
{
penStepperStarted = false;
homePenStepper = true;
}
}
penStepper.run();
//if (System.buttonPushed() > 1000)
if (!particleConnectRequested)
{
particleConnectRequested = true;
Particle.connect();
}
if (particleConnectRequested)
{
if (Particle.connected())
{
Particle.process();
}
}
}
| [
"rob@dobson.com"
] | rob@dobson.com |
8dcd4ecef104ab7ddb3f2bbfbe315f03f5097492 | f955b71bc89bdf8da84c9807394f096d444684b4 | /re2c/src/ir/regexp/regexp_match.h | 4905994141d0f1e5ab3423d61cdc180bf83aebdc | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | otaran/re2c | 0d8ae1f6bd855e5ae2c003b96fbfbe4a22516f63 | df19195968a158acf78eb4723c60925fbf1f6e04 | refs/heads/master | 2021-01-22T16:10:15.677837 | 2015-12-02T12:11:01 | 2015-12-02T12:11:01 | 47,002,105 | 1 | 0 | null | 2015-11-27T22:46:43 | 2015-11-27T22:46:43 | null | UTF-8 | C++ | false | false | 525 | h | #ifndef _RE2C_IR_REGEXP_REGEXP_MATCH_
#define _RE2C_IR_REGEXP_REGEXP_MATCH_
#include "src/ir/regexp/regexp.h"
#include "src/util/range.h"
namespace re2c
{
class MatchOp: public RegExp
{
public:
Range * match;
inline MatchOp (Range * m)
: match (m)
{}
void split (CharSet &);
void calcSize (Char *);
uint32_t fixedLength ();
uint32_t compile (Char *, Ins *);
void decompile ();
void display (std::ostream & o) const;
FORBID_COPY (MatchOp);
};
} // end namespace re2c
#endif // _RE2C_IR_REGEXP_REGEXP_MATCH_
| [
"skvadrik@gmail.com"
] | skvadrik@gmail.com |
6fbd43cccc19f354185742decc991e8f9836703c | ce56a2124f75c6172dfde643aa49c1773571b19b | /question46.cpp | 4509bb74c70ca04a9bb8e0a820d0550cab293c5d | [] | no_license | Electromagnetism-dog-technology/jianzhioffer | 91c3204d516e855ed4410aad631b87e96552bf3c | c5f20178bb9bb766e15aede7b2bc7dcc435db03e | refs/heads/main | 2023-06-18T15:06:11.584122 | 2021-07-17T07:49:17 | 2021-07-17T07:49:17 | 343,697,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 509 | cpp | #include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution {
public:
int translateNum(int num) {
string nums = to_string(num);
int len = nums.size();
vector<int>dp(len + 1);
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i < len + 1; i++)
{
if (nums[i - 2] == '1' || (nums[i - 2] == '2'&&nums[i - 1] < '6'))
{
dp[i] = dp[i - 1] + dp[i - 2];
}
else
dp[i] = dp[i - 1];
}
return dp[len];
}
};
int main()
{
system("pause");
return EXIT_SUCCESS;
} | [
"346322521@qq.com"
] | 346322521@qq.com |
8042b3a67a463cf50f7dc434826e267e382b53b1 | 216311623344fee7dd8088380b4f9149f088ce10 | /algorithm/codes/fig07_15.cpp | 75b6530ccf71a94929cae32b6f80b920448b4136 | [] | no_license | hhraymond/apple | 2ecedbe0d4d47d9a639a096dc7a55e25eea066c6 | 6349e10a09fff6b75d5382eac1d372ab28d3e06b | refs/heads/master | 2020-04-09T05:52:05.036173 | 2015-06-08T01:58:31 | 2015-06-08T01:58:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 595 | cpp | /**
* Return median of left, center, and right.
* Order these and hide the pivot.
*/
template <typename Comparable>
const Comparable & median3( vector<Comparable> & a, int left, int right )
{
int center = ( left + right ) / 2;
if( a[ center ] < a[ left ] )
swap( a[ left ], a[ center ] );
if( a[ right ] < a[ left ] )
swap( a[ left ], a[ right ] );
if( a[ right ] < a[ center ] )
swap( a[ center ], a[ right ] );
// Place pivot at position right - 1
swap( a[ center ], a[ right - 1 ] );
return a[ right - 1 ];
}
| [
"skyhuang007@163.com"
] | skyhuang007@163.com |
28eb4a8bf074833a2a5b1a1d8f3fd6c1d2dc59fa | 52505166e409b44caf7a0b144ef0c453b586fcee | /performance-eval/FlexNLP/s3/ac_include/mc_testbench_util.h | c32f3954f01cc6658123da87439278df0e465f72 | [] | no_license | yuex1994/ASPDAC-tandem | fb090975c65edbdda68c19a8d7e7a5f0ff96bcb8 | decdabc5743c2116d1fc0e339e434b9e13c430a8 | refs/heads/master | 2023-08-28T04:37:30.011721 | 2021-08-07T13:19:23 | 2021-08-07T13:19:30 | 419,089,461 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,076 | h |
#ifndef _INCLUDED_MC_TESTBENCH_UTIL_H_
#define _INCLUDED_MC_TESTBENCH_UTIL_H_
namespace mc_testbench_util {
static void process_wait_ctrl(
const sc_string &var, // variable name
mc_wait_ctrl &var_wait_ctrl, // new control variable
tlm::tlm_fifo_put_if< mc_wait_ctrl > *ccs_wait_ctrl_fifo_if, // FIFO for wait_ctrl objects
const int var_capture_count,
const int var_stopat,
const bool is_channel=false)
{
#ifdef MC_DEFAULT_TRANSACTOR_LOG
const bool log_event = (MC_DEFAULT_TRANSACTOR_LOG & MC_TRANSACTOR_WAIT);
#else
const bool log_event = true;
#endif
if (var_capture_count < var_stopat) {
var_wait_ctrl.ischannel = is_channel;
if (var_wait_ctrl.cycles != 0) {
var_wait_ctrl.iteration = var_capture_count;
var_wait_ctrl.stopat = var_stopat;
if (var_wait_ctrl.cycles < 0) {
if (log_event) {
std::ostringstream msg; msg.str("");
msg << "Ignoring negative value (" << var_wait_ctrl.cycles << ") for testbench control testbench::" << var << "_wait_ctrl.cycles.";
SC_REPORT_WARNING("User testbench", msg.str().c_str());
}
var_wait_ctrl.cycles = 0;
}
if (var_wait_ctrl.interval < 0) {
if (log_event) {
std::ostringstream msg; msg.str("");
msg << "Ignoring negative value (" << var_wait_ctrl.interval << ") for testbench control testbench::" << var << "_wait_ctrl.interval.";
SC_REPORT_WARNING("User testbench", msg.str().c_str());
}
var_wait_ctrl.interval = 0;
}
if (var_wait_ctrl.is_set()) {
if (log_event) {
std::ostringstream msg; msg.str("");
msg << "Captured " << var << "_wait_ctrl request " << var_wait_ctrl;
SC_REPORT_INFO("User testbench", msg.str().c_str());
}
ccs_wait_ctrl_fifo_if->put(var_wait_ctrl);
}
}
var_wait_ctrl.clear(); // reset wait_ctrl
}
}
} // end namespace mc_testbench_util
#endif
| [
"anonymizeddac2020submission@gmail.com"
] | anonymizeddac2020submission@gmail.com |
4dfc15d937f0ee89b74654a47ea81a356c51429b | c85b97ac269baf6d8a28fc7a7e7de554a56be7b6 | /src/EPLProxyContextMenuParams.cpp | b553f1b8c8e248076c11af98bd9b402ad558cae5 | [
"BSD-3-Clause"
] | permissive | Memorie6/ecef | 044afba923c9a157f60c89735dfdca42b2d50cd8 | b9214aec0462db26718fca1cdcc9add200fabfb8 | refs/heads/master | 2023-03-17T09:44:13.093857 | 2020-11-13T13:49:00 | 2020-11-13T13:49:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,596 | cpp | #include "stdafx.h"
#include "EPLProxyContextMenuParams.h"
#include <proxy/ProxyBrowser.h>
#include <proxy/ProxyFrame.h>
#include <proxy/ProxyRequest.h>
#include <proxy/ProxyResponse.h>
#include <proxy/proxyValue.h>
#include <proxy/proxyListValue.h>
#include <proxy/ProxyDictionaryValue.h>
#include <proxy/ProxyDOMNode.h>
#include <proxy/ProxyContextMenuParams.h>
//==========================================
extern "C"
void EDITIONF(ProxyContextMenuParams_Constructor)(PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
*pArgInf->m_ppCompoundData = NULL;
}
extern "C"
void EDITIONF(ProxyContextMenuParams_Destructor)(PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData) { return; }
shrewd_ptr<ProxyContextMenuParams> ptr = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
if(ptr){ ptr->release(); *pArgInf->m_ppCompoundData = NULL; }
}
extern "C"
void EDITIONF(ProxyContextMenuParams_CopyConstructor)(PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf[1].m_pCompoundData || NULL == *pArgInf[1].m_ppCompoundData) { return; }
shrewd_ptr<ProxyContextMenuParams> ptr = (ProxyContextMenuParams*)*pArgInf[1].m_ppCompoundData;
if(ptr){ ptr->retain(); *pArgInf->m_ppCompoundData = ptr.get(); }
else { *pArgInf->m_ppCompoundData = NULL; }
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetXCoord) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_int = 0;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_int = self->GetXCoord();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetYCoord) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_int = 0;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_int = self->GetYCoord();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetTypeFlags) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_int = 0;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_int = self->GetTypeFlags();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetLinkUrl) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_pText = NULL;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pText = self->GetLinkUrl();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetUnfilteredLinkUrl) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_pText = NULL;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pText = self->GetUnfilteredLinkUrl();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetSourceUrl) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_pText = NULL;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pText = self->GetSourceUrl();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_HasImageContents) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_bool = FALSE;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_bool = self->HasImageContents();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetTitleText) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_pText = NULL;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pText = self->GetTitleText();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetPageUrl) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_pText = NULL;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pText = self->GetPageUrl();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetFrameUrl) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_pText = NULL;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pText = self->GetFrameUrl();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetFrameCharset) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_pText = NULL;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pText = self->GetFrameCharset();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetMediaType) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_int = 0;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_int = self->GetMediaType();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetMediaStateFlags) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_int = 0;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_int = self->GetMediaStateFlags();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetSelectionText) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_pText = NULL;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pText = self->GetSelectionText();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetMisspelledWord) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_pText = NULL;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pText = self->GetMisspelledWord();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetDictionarySuggestions) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
DWORD* InternalPointer = (DWORD*)NotifySys(NRS_MALLOC, 8, 0);
InternalPointer[0] = 1;
InternalPointer[1] = 0;
pRetData->m_pCompoundData = InternalPointer;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_pCompoundData = (void*)self->GetDictionarySuggestions();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_IsEditable) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_bool = FALSE;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_bool = self->IsEditable();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_IsSpellCheckEnabled) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_bool = FALSE;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_bool = self->IsSpellCheckEnabled();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_GetEditStateFlags) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_int = 0;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_int = self->GetEditStateFlags();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_IsCustomMenu) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_bool = FALSE;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_bool = self->IsCustomMenu();
}
extern "C"
void EDITIONF(ProxyContextMenuParams_IsPepperMenu) (PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf){
if(NULL == pArgInf->m_pCompoundData || NULL == *pArgInf->m_ppCompoundData){
pRetData->m_bool = FALSE;
return ;
}
shrewd_ptr<ProxyContextMenuParams> self = (ProxyContextMenuParams*)*pArgInf->m_ppCompoundData;
pRetData->m_bool = self->IsPepperMenu();
}
//==========================================
| [
"kirino17@hotmail.com"
] | kirino17@hotmail.com |
c6572787e5b6081a5b9bed2c6b231f14c564eca0 | 7484053d1a8f7cb85850525db91cb0514a328a13 | /Ch11_Algorithms/partition1.cpp | f65cc7a412eb84ab7db57b5345e51facba057096 | [] | no_license | olcayatabey/Cpp-Standard-Library-Tutorial | 2a56b1806cee6c284832a80a7efd98633a1df338 | 325198b1652ccf4f9e5c338f3ef54ba8c83962d8 | refs/heads/master | 2021-08-29T10:27:09.129597 | 2017-12-13T17:44:08 | 2017-12-13T17:44:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | cpp | // Chapter 11 Algorithms -- partition
#include "algostuff.hpp"
using namespace std;
int main()
{
vector<int> coll1;
vector<int> coll2;
INSERT_ELEMENTS(coll1,1,9);
INSERT_ELEMENTS(coll2,1,9);
PRINT_ELEMENTS(coll1,"coll1: ");
PRINT_ELEMENTS(coll2,"coll2: ");
cout << endl;
// move all even elements to the front
vector<int>::iterator pos1, pos2;
pos1 = partition(coll1.begin(), coll1.end(), // range
[](int elem){ return elem%2==0; }
);
pos2 = stable_partition(coll2.begin(), coll2.end(),
[](int elem){ return elem%2==0; }
);
// print collections and first odd element
PRINT_ELEMENTS(coll1,"coll1: ");
cout << "first odd element: " << *pos1 << endl;
PRINT_ELEMENTS(coll2,"coll2: ");
cout << "first odd element: " << *pos2 << endl;
}
| [
"rockpaperbanan@gmail.com"
] | rockpaperbanan@gmail.com |
076a413575a5288bd92c1233c73695d87f0d5a00 | 289fe1cb18116556fd957141fb1d9def14b9f312 | /telnet_client/main.cpp | bbdfa179cb47fed0bd67f1814d3a63287a7720f3 | [] | no_license | dendergunov/mtosdadp | c59f78920425507be60c4274cd4329cda0368553 | 1c527bc04505fe2128e227a47cde3f518ffbd21d | refs/heads/master | 2022-11-13T08:09:59.236711 | 2020-06-28T22:05:39 | 2020-06-28T22:05:39 | 240,233,202 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,669 | cpp | #include "event_wrappers.hpp"
#include "filter_utils.hpp"
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/thread.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <sstream>
#include <charconv>
#include <optional>
#include <thread>
#include <vector>
#include <chrono>
#include <boost/program_options.hpp>
template<typename... Ts>
std::string format(Ts&&... args)
{
std::ostringstream out;
(out << ... << std::forward<Ts>(args));
return out.str();
}
class logger
{
public:
template<typename T>
logger& operator<<(T&& output)
{
std::cerr << std::forward<T>(output);
return *this;
}
~logger()
{
std::cerr << std::endl;
}
private:
static std::mutex m_;
std::lock_guard<std::mutex> l_{m_};
};
std::mutex logger::m_;
template<typename T>
std::optional<T> from_chars(std::string_view sv_) noexcept
{
T out;
auto end = sv_.data() + sv_.size();
auto res = std::from_chars(sv_.data(), end, out);
if(res.ec==std::errc{}&&res.ptr==end)
return out;
return {};
}
void eventcb(struct bufferevent *bev, short events, void *ptr)
{
if(events & BEV_EVENT_CONNECTED){
static int total_connected = 0;
// logger{} << "Sucessfully connected to telnet server! " << ++total_connected;
} else if(events & BEV_EVENT_ERROR){
throw std::runtime_error("Error connecting to server!");
}
}
void readcb(struct bufferevent *bev, void *ptr)
{
auto libev = static_cast<libevent::bufferevent_w*>(ptr);
struct evbuffer *in = bufferevent_get_input(bev);
std::size_t length = evbuffer_get_length(in);
if(length){
libev->bytes_read += length;
evbuffer_drain(in, length);
}
if(libev->bytes_read >= libev->bytes_read_threshold){
static int i = 0;
// logger{} << "bytes_read: " << libev->bytes_read << ", threshold: " << libev->bytes_read_threshold
// << "\nbytes_send: "<< libev->bytes_send << ", threshold: " << libev->bytes_send_threshold
// << ", socket: " << ++i;
libev->close();
}
}
void writecb(struct bufferevent *bev, void *ptr)
{
auto libev = static_cast<libevent::bufferevent_w*>(ptr);
libev->bytes_send += libev->send_message.size();
if(libev->bytes_send < libev->bytes_send_threshold){
bufferevent_write(bev, libev->send_message.data(), libev->send_message.size());
}
// else {
// logger{} << "bytes_send: " << libev->bytes_send;
// }
}
//void mainreadcb(struct bufferevent *bev, void *ptr)
//{
// auto libev = static_cast<libevent::bufferevent_w*>(ptr);
// struct evbuffer *in = bufferevent_get_input(bev);
// int length = evbuffer_get_length(in);
// if(length){
// libev->bytes_read += length;
//// evbuffer_drain(in, length);
// }
// std::string readbuf;
// readbuf.resize(length);
// int ec;
// ec = bufferevent_read(bev, readbuf.data(), length);
// logger{} << "Read " << ec << " bytes";
// logger{} << "Total: " << libev->bytes_read;
// std::cout << readbuf << std::flush;
// if(libev->bytes_read >= libev->bytes_read_threshold){
// logger{} << "bytes_read: " << libev->bytes_read << ", threshold: " << libev->bytes_read_threshold;
// libev->close();
// }
//}
//void stdinrcb(evutil_socket_t fd, short what, void* arg)
//{
//// logger{} << "srdinrcb!";
// std::vector<libevent::bufferevent_w> *bev = static_cast<std::vector<libevent::bufferevent_w>*>(arg);
// std::string input;
// input.resize(2048);
// std::cin.getline(input.data(), 2048);
// input.append("\n");
// auto size = input.size();
// add_r(input, size);
// auto bev_size = bev->size();
// for(std::size_t i = 0; i < bev_size; ++i){
// bufferevent_write((*bev)[i].bev, input.data(), size);
// }
//}
std::string get_send_message(int policy, std::size_t send_byte_threshold, std::size_t read_byte_threshold);
int main(int argc, char **argv)
{
try {
std::string address_str, port_str, thread_str, connection_str, recieve_threshold_str, policy_str;
boost::program_options::options_description desc("Allowed options");
desc.add_options()
("help", "Produce this message")
("ip-address", boost::program_options::value<std::string>(&address_str)->default_value("127.0.0.1"), "specify host ip-address")
("port", boost::program_options::value<std::string>(&port_str)->default_value("23"), "specify port")
("thread-number", boost::program_options::value<std::string>(&thread_str)->default_value("1"), "set the amount of working threads")
("connection-number", boost::program_options::value<std::string>(&connection_str)->default_value("1"), "set the number of connections")
("recieve-threshold", boost::program_options::value<std::string>(&recieve_threshold_str)->default_value("4096"), "set the number of bytes to recieve "
"before socket shutdown")
("policy", boost::program_options::value<std::string>(&policy_str)->default_value("0"), "set 0 to send a little message to get a light answer "
"or 1 to send a light message to get a heavy answer "
"or 2 to send a heavy message to get a heavy answer");
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if(vm.count("help")) {
std::cout << desc << std::endl;
return 0;
}
struct in_addr address;
if(!inet_pton(AF_INET, address_str.data(), &address))
throw std::runtime_error("Cannot convert ip address\n");
auto port = from_chars<std::uint16_t>(port_str);
if(!port || !*port)
throw std::runtime_error("Port must be in [1;65535]\n");
auto threads = from_chars<std::uint32_t>(thread_str);
if(!threads || !*threads || *threads > std::thread::hardware_concurrency())
throw std::runtime_error(format("Number of threads should be in [1;", std::thread::hardware_concurrency(), "]\n"));
auto connections = from_chars<std::uint32_t>(connection_str);
if(!connections || !*connections)
throw std::runtime_error(format("Number of connections must be in [1;", std::numeric_limits<std::uint32_t>::max, "]\n"));
auto read_byte_threshold = from_chars<std::size_t>(recieve_threshold_str);
if(!read_byte_threshold || !*read_byte_threshold)
throw std::runtime_error(format("Recieve threshold must be in [1;", std::numeric_limits<std::size_t>::max, "\n"));
auto policy = from_chars<int>(policy_str);
if(!policy)
throw std::runtime_error(format("policy must be in [0;2]"));
if(*policy < 0 || *policy > 2)
throw std::runtime_error(format("Policy must be in [0;2]"));
std::cout << "Execution with the next parameters:"
<< "\nip-address: " << address_str
<< "\nport: " << port_str
<< "\nnumber of threads: " << thread_str
<< "\nnumber of connections: " << connection_str
<< "\nrecieve threshold: " << recieve_threshold_str
<< "\ntransmission policy: " << policy_str << std::endl;
/**----------------------------------------------------------------------------------**/
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = address.s_addr;
sin.sin_port = htons(*port);
/**----------------------------------------------------------------------------------**/
evthread_use_pthreads();
std::vector<libevent::bufferevent_w> bevents;
bevents.reserve(*connections);
std::vector<libevent::event_base_w> evbases;
evbases.reserve(*threads);
for(std::size_t i = 0; i < *threads; ++i)
evbases.emplace_back();
std::vector<std::thread> workers;
workers.reserve(*threads-1);
std::size_t send_byte_threshold;
if(*policy == 1){
send_byte_threshold = 50;
} else {
send_byte_threshold = *read_byte_threshold;
}
std::string send_message = get_send_message(*policy, send_byte_threshold, *read_byte_threshold);
for(std::size_t i = 0; i < *connections; ++i){
bevents.emplace_back(libevent::bufferevent_w(evbases[i%evbases.size()], *read_byte_threshold,
send_byte_threshold, std::string_view(send_message.data(), send_message.size())));
// if(i == 0)
// bufferevent_setcb(bevents[i].bev, mainreadcb, NULL, eventcb, &bevents[i]);
// else
bufferevent_setcb(bevents[i].bev, readcb, writecb, eventcb, &bevents[i]);
bufferevent_enable(bevents[i].bev, EV_READ|EV_WRITE);
}
auto start = std::chrono::high_resolution_clock::now();
for(std::size_t i = 0; i < *connections; ++i){
if(bufferevent_socket_connect(bevents[i].bev,(struct sockaddr *) &sin, sizeof(sin)) < 0){
throw std::runtime_error(format("bufferevent_socket_connect error on ", i, " socket"));
return -1;
}
bufferevent_write(bevents[i].bev, send_message.data(), send_message.size());
}
for(unsigned int i = 1; i < *threads; ++i){
workers.emplace_back([&, index=i]{
event_base_dispatch(evbases[index].base);
});
}
// libevent::bufferevent_w stdcin(evbases[0], 0);
// libevent::event_w stdreading;
// stdreading.ev = event_new(evbases[0].base, 0, EV_READ | EV_PERSIST, stdinrcb, &bevents);
// event_add(stdreading.ev, NULL);
event_base_dispatch(evbases[0].base);
for(auto& x: workers){
x.join();
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end-start;
logger{} << "Processed in " <<diff.count()
<< "s, one client in: " << diff.count()/(*connections);
} catch (std::exception& e) {
std::cerr << e.what();
}
return 0;
}
std::string get_send_message(int policy, std::size_t send_bytes_threshold, std::size_t read_byte_threshold)
{
std::string message("light message");
std::size_t size = message.size();
switch(policy){
case 0:
return format("echo \"", message, "\"\n");
break;
case 1:
return format("for ((i=1;i<=", read_byte_threshold/message.size()+1, ";i+=1)); do echo \"", message ,"$i\"; done\n");
case 2:
if(send_bytes_threshold < 1048576){
for(std::size_t i = 0; i <= send_bytes_threshold/size; ++i)
message.append("light message");
} else {
for(std::size_t i = 0; i <= 1048576/size; ++i)
message.append("light message");
}
return format("echo \"", message, "\"\n");
default:
throw std::runtime_error(format("policy value ", policy, " cannot be accepted in get_send_message!"));
}
}
| [
"dan.dergunow@gmail.com"
] | dan.dergunow@gmail.com |
88fa9ce82a67f19c8cd5d3444926e10e7ed33291 | bc3e9b27585473f2ccbbc1406693a55d1ec086a0 | /Bulk Club Project/member.cpp | afd68726f6f29df8077336daa43a441a805349a3 | [] | no_license | eddierayo156/CS1C-Bulk-Club | ccb512163b8af2eae4e68029b4bbf320f91a064b | a04518112edb80393a2f725f8ae36bd5a31878c0 | refs/heads/master | 2020-03-08T00:02:49.652630 | 2018-04-02T20:26:21 | 2018-04-02T20:26:21 | 127,795,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49 | cpp | #include "member.h"
Member::Member()
{
}
| [
"noreply@github.com"
] | noreply@github.com |
0e5c3965c02c8715c6813549ca49e3039b99fa8d | 4b74fd95834ad40e173f2a2e370e39ca62f2a0f5 | /SELECT/MULTISERVICE/MSS.cpp | 65b88c579365467494069896e3541c51d1a02203 | [] | no_license | basushibam/Computer_Networks | 45817afe8e3aca9717ae94b035f35d673e2fc1ab | a3d1fd6cf210f0d758a98ae6c1c93bd2b734cf03 | refs/heads/master | 2020-12-21T05:34:50.146634 | 2020-01-26T15:00:44 | 2020-01-26T15:00:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,236 | cpp | #include <bits/stdc++.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#define BUFFER_SIZE 100
#define MAX_SERVICES 30
using namespace std;
char mainFIFO[] = "./mainFIFO";
char t1FIFO[] = "./t1FIFO";
char t2FIFO[] = "./t2FIFO";
char s4FIFO[] = "./s4FIFO" ;
char s5FIFO[] = "./s5FIFO";
char mBuffer[BUFFER_SIZE]; char t1Buffer[BUFFER_SIZE]; char t2Buffer[BUFFER_SIZE];
set<string> clients;
void service1(string clientName){
printf("Service 1 given to client %s by server \n",clientName.c_str() );
return;
}
void service2(string clientName){
printf("Service 2 given to client %s by server \n",clientName.c_str() );
return;
}
void service3(string clientName){
printf("Service 3 given to client %s by server \n",clientName.c_str() );
return;
}
void initialize(){
int ret = mkfifo(mainFIFO,0666);
if(ret<0){
printf("Error in creating main FIFO \n"); exit(0);
}
else{
printf("Main FIFO created successfully \n");
}
ret = mkfifo(t1FIFO,0666);
if(ret<0){
printf("Error in creating t1 FIFO \n"); exit(0);
}
else{
printf("t1 FIFO created successfully \n");
}
ret = mkfifo(t2FIFO,0666);
if(ret<0){
printf("Error in creating t2 FIFO \n"); exit(0);
}
else{
printf("t2 FIFO created successfully \n");
}
ret = mkfifo(s4FIFO,0666);
if(ret<0){
printf("Error in creating s4 FIFO \n"); exit(0);
}
else{
printf("s4 FIFO created successfully \n");
}
}
int main(int argc, char const *argv[])
{
initialize();
int ret,mfd,t1fd,t2fd,s4fd;
mfd = open(mainFIFO,O_RDONLY|O_NONBLOCK); t1fd = open(t1FIFO,O_RDONLY|O_NONBLOCK); t2fd = open(t2FIFO,O_RDONLY|O_NONBLOCK);
s4fd = open(s4FIFO,O_WRONLY|O_NONBLOCK);
int sret,l=0;
fd_set readfds;
struct timeval timeout;
while(1)
{
FD_ZERO(&readfds);
FD_SET(mfd,&readfds); FD_SET(t1fd,&readfds); FD_SET(t2fd,&readfds);
timeout.tv_sec = 10; timeout.tv_usec = 0;
printf("Selecting the readfds \n");
sret = select(MAX_SERVICES,&readfds,NULL,NULL,&timeout);
if(sret==0){
printf("sret = %d \n",sret );
printf("Timeout \n");
}
else{
printf("Number of bits set = %d \n",sret );
if(FD_ISSET(mfd,&readfds)){
ret = read(mfd,mBuffer,BUFFER_SIZE);
printf("ret in mFIFO read = %d\n",ret );
if(ret!=-1){
printf("Client %s wants to join \n",mBuffer );
}
string clientName(mBuffer); clients.insert(clientName); printf("%s client inserted successfully\n",clientName.c_str() );
}
if(FD_ISSET(t1fd,&readfds)){
printf("Inside FD_ISSET of service1 or service2 or service3 \n");
ret = read(t1fd,t1Buffer,BUFFER_SIZE);
printf("ret in t1 FIFO = %d\n",ret );
if(ret!=-1){
printf("buffer read from t1 FIFO = %s\n",t1Buffer );
}
string info(t1Buffer),clientName,clientID,service; stringstream ss; ss<<info; ss>>clientName; ss>>clientID; ss>>service;
if(clients.find(clientName)!=clients.end()){
if(service=="service1"){
service1(clientName);
}
if(service=="service2"){
service2(clientName);
}
if(service=="service3"){
service3(clientName);
}
}
else{
printf("Client %s not registered. Can't Provide service \n",clientName.c_str());
}
}
if(FD_ISSET(t2fd,&readfds)){
printf("Inside FD_ISSET of service4 \n");
ret = read(t2fd,t2Buffer,BUFFER_SIZE);
printf("ret in t2 FIFO = %d\n",ret );
if(ret!=-1){
printf("buffer read from t2 FIFO = %s\n",t2Buffer );
}
string info(t2Buffer),clientName,clientID,service; stringstream ss; ss<<info; ss>>clientName; ss>>clientID; ss>>service;
printf("Checking presence of client %s \n",clientName.c_str() );
if(clients.find(clientName)!=clients.end()){
printf("Writing in buffer %s\n",s4FIFO );
string msg = clientName+" "+clientID;
s4fd = open(s4FIFO,O_WRONLY);
if(s4fd<0){
printf("Error in opening s4FIFO \n"); exit(0);
}
write(s4fd,msg.c_str(),100);
printf("%s Written successfully in s4 FIFO \n",msg.c_str());
close(s4fd);
}
else{
printf("Client %s not registered. Can't Provide service \n",clientName.c_str());
}
}
}
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
fbe874e14b7a9638b167d5100089ebb32ae616e0 | 1ffbffe9aead619e659a5787b877d86976d16c96 | /Cube Transformations using Vertex Buffers/Quaternion.cpp | 98a0ea767dec5394bf8b11fb5a0f47beac1ed0ff | [] | no_license | CastBart/All-Projects | 602c669a1900a992bd3ef91c67caba2aac0154b9 | 5d3c27e7c67fdc5f9423f765848563d9116b3165 | refs/heads/master | 2021-09-06T10:21:13.164192 | 2018-02-05T13:32:16 | 2018-02-05T13:32:16 | 76,813,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,313 | cpp | #pragma once
#include "Quaternion.h"
Quaternion::Quaternion():
m_w(0),
m_x(0),
m_y(0),
m_z(0)
{
}
Quaternion::Quaternion(double w, double x, double y, double z):
m_w(w),
m_x(x),
m_y(y),
m_z(z)
{
}
Quaternion::Quaternion(float w, float x , float y, float z):
m_w(w),
m_x(x),
m_y(y),
m_z(z)
{
}
Quaternion::Quaternion(Vector3 &V) :
m_w(0),
m_x(V.M_X()),
m_y(V.M_Y()),
m_z(V.M_Z())
{
}
double Quaternion::length()
{
return sqrt((m_w * m_w) + (m_x * m_x) + (m_y * m_y) + (m_z * m_z));
}
double Quaternion::lengthSquared()
{
return ((m_w * m_w) + (m_x * m_x) + (m_y * m_y) + (m_z * m_z));
}
Quaternion operator*(const Quaternion &leftSide, const double &s)
{
return Quaternion(
leftSide.M_W() * s,
leftSide.M_X() * s,
leftSide.M_Y() * s,
leftSide.M_Z() * s
);
}
Quaternion Quaternion::conjugate()
{
return Quaternion(m_w, -m_x, -m_y, -m_z);
}
Quaternion Quaternion::inverse()
{
return Quaternion( conjugate() * (1/ lengthSquared()) );
}
Quaternion Quaternion::normalise()
{
Quaternion q(m_w, m_x, m_y, m_z);
return Quaternion( q * (1/length()) );
}
Vector3 Quaternion::Rotate(Vector3 &thisVector, const float &angle)
{
float angleRads = (float)(angle *(acos(-1) / 180));
Quaternion Q1 = normalise();
Quaternion Q2 = Quaternion(static_cast<float>(cos(angleRads / 2)), static_cast<float>(sin(angleRads / 2) * Q1.M_X()), static_cast<float>(sin(angleRads / 2) * Q1.M_Y()), static_cast<float>(sin(angleRads / 2) * Q1.M_Z()));
Quaternion Q3 = Q2.inverse();
Quaternion Q4 = Quaternion(thisVector);
Q4 = Q2 * Q4 * Q3;
return Q4.convertToVector();
}
Vector3 Quaternion::convertToVector()
{
return Vector3(m_x, m_y, m_z);
}
double Quaternion::M_W() const
{
return m_w;
}
double Quaternion::M_X() const
{
return m_x;
}
double Quaternion::M_Y() const
{
return m_y;
}
double Quaternion::M_Z() const
{
return m_z;
}
Quaternion::~Quaternion()
{
}
Quaternion operator+(const Quaternion &leftSide, const Quaternion &rightSide)
{
return Quaternion(
leftSide.M_W() + rightSide.M_W(),
leftSide.M_X() + rightSide.M_X(),
leftSide.M_Y() + rightSide.M_Y(),
leftSide.M_Z() + rightSide.M_Z()
);
}
Quaternion operator-(const Quaternion &Q)
{
return Quaternion(-Q.m_w, -Q.m_x, -Q.m_y, -Q.m_z);
}
Quaternion operator*(const Quaternion &leftSide, const Quaternion &rightSide)
{
return Quaternion(
(leftSide.M_W() * rightSide.M_W()) - (leftSide.M_X() * rightSide.M_X()) - (leftSide.M_Y() * rightSide.M_Y()) - (leftSide.M_Z() * rightSide.M_Z()),
(leftSide.M_W() * rightSide.M_X()) + (leftSide.M_X() * rightSide.M_W()) + (leftSide.M_Y() * rightSide.M_Z()) - (leftSide.M_Z() * rightSide.M_Y()),
(leftSide.M_W() * rightSide.M_Y()) + (leftSide.M_Y() * rightSide.M_W()) + (leftSide.M_Z() * rightSide.M_X()) - (leftSide.M_X() * rightSide.M_Z()),
(leftSide.M_W() * rightSide.M_Z()) + (leftSide.M_Z() * rightSide.M_W()) + (leftSide.M_X() * rightSide.M_Y()) - (leftSide.M_Y() * rightSide.M_X())
);
}
Quaternion operator*(const Quaternion &leftSide, const float &f)
{
return leftSide * static_cast<float>(f);
}
Quaternion operator-(const Quaternion &leftSide, const Quaternion &rightSide)
{
return Quaternion(
leftSide.M_W() - rightSide.M_W(),
leftSide.M_X() - rightSide.M_X(),
leftSide.M_Y() - rightSide.M_Y(),
leftSide.M_Z() - rightSide.M_Z()
);
}
| [
"C00205464@itcarlow.ie"
] | C00205464@itcarlow.ie |
ed2d3de07b86acb5250e12dd08c6dfe73726c385 | 421f68125425e881444c9ea387449ba6e4a0ec8c | /blib/ResourceManager.cpp | c9428fa7fdea2be47684c3cf61e939068b380e6f | [] | no_license | sdbezerra/blib | 6453445c25703112a53644a760477e4b53794e94 | 26f965f232448e414caff0f137f46fad33aaa557 | refs/heads/master | 2020-04-06T04:19:34.852828 | 2015-12-17T13:26:55 | 2015-12-17T13:26:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | cpp | #include "ResourceManager.h"
#include <blib/Resource.h>
#include <blib/util/Log.h>
#include <assert.h>
using blib::util::Log;
namespace blib
{
ResourceManager* ResourceManager::manager = nullptr;
ResourceManager::ResourceManager()
{
manager = this;
}
ResourceManager::~ResourceManager()
{
for (auto it : resources)
delete it.first;
}
ResourceManager& ResourceManager::getInstance()
{
return *manager;
}
Resource* ResourceManager::regResource(Resource* resource)
{
if (resources.find(resource) == resources.end())
resources[resource] = 0;
resources[resource]++;
// Log::out<<"Loading "<<resource->name<<Log::newline;
return resource;
}
void ResourceManager::dispose(Resource* resource)
{
assert(resources.find(resource) != resources.end());
resources[resource]--;
if (resources[resource] == 0)
{
// Log::out<<"deleting "<<resource->name<<Log::newline;
delete resource;
resources.erase(resources.find(resource));
}
}
void ResourceManager::printDebug()
{
for (auto r : resources)
{
if (r.second > 0)
{
Log::out << r.first->name << " still loaded " << r.second << " times" << Log::newline;
#ifdef RESOURCECALLSTACK
Log::out << r.first->callstack << Log::newline;
#endif
}
}
}
} | [
"borfje@gmail.com"
] | borfje@gmail.com |
01b352d8496b26eb641372a8a9129c6db3ab4c7e | 2f45db01f5836b68f4fe207c5aa8719ab8ea29a5 | /Direct3DEngine/Include/Component/UserComponent.cpp | 66d4fe1e1606a3fa3f21d9f1a4c076fd4e4a1ac2 | [] | no_license | KkyuCone/Direct3D_RPGPortfolio | 8cbce767321580b9802847a6574bd4ccabac2532 | 6e3ffdf681f84e453f5810164ad1ff93571fa882 | refs/heads/master | 2020-05-31T16:10:15.320999 | 2019-06-12T14:18:58 | 2019-06-12T14:18:58 | 190,375,094 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,036 | cpp | #include "UserComponent.h"
ENGINE_USING
UserComponent::UserComponent()
{
m_eComponentType = CT_USERCOMPONENT;
}
UserComponent::UserComponent(const UserComponent & _Component) : Component(_Component)
{
// 복사생성자로.. Clone역할을 맡는데
// 복사본이니까 ReferenceCount를 1로 고정시킨다.
// 그렇지 않으면 원본에 이어 증가되기 때문에 프로그램 종료시 소멸자에서 삭제되지 않아 릭이 발생한다.
*this = _Component;
m_iReferenceCount = 1;
}
UserComponent::~UserComponent()
{
}
void UserComponent::Start()
{
}
bool UserComponent::Init()
{
return true;
}
int UserComponent::Input(float _fTime)
{
return 0;
}
int UserComponent::Update(float _fTime)
{
return 0;
}
int UserComponent::LateUpdate(float _fTime)
{
return 0;
}
int UserComponent::Collision(float _fTime)
{
return 0;
}
int UserComponent::PrevRender(float _fTime)
{
return 0;
}
int UserComponent::Render(float _fTime)
{
return 0;
}
Component * UserComponent::Clone() const
{
return nullptr;
}
| [
"praesentia05@naver.com"
] | praesentia05@naver.com |
e724746bb20c186d11e245c393e29465c3627c63 | 29807cf867a816930f087a24fbf3f421ec04a5aa | /examples/google-code-jam/JeffreyHui/C-small-2-attempt0.cpp | 397114a5368cdb970a29de2e4d472aa25f71f639 | [
"MIT"
] | permissive | rbenic-fer/progauthfp | d1c02be7083482ca1d525146477e535d4f23350d | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | refs/heads/master | 2022-10-19T15:47:13.531190 | 2020-06-12T21:38:09 | 2020-06-12T21:38:09 | 267,689,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 612 | cpp | #include <cstdio>
int cnt[1000001];
int T, N, K;
int main (){
freopen ("C-small-2-attempt0.in", "r", stdin);
freopen ("C-small-2-attempt0.out", "w", stdout);
scanf("%d", &T);
for (int i = 1; i <= T; i++){
scanf("%d %d", &N, &K);
for (int j = 0; j <= N; j++)
cnt[j] = 0;
cnt[N] = 1;
while (cnt[N] == 0 || (N > 0 && K > 1)){
if (cnt[N] == 0)
N--;
else {
K--;
cnt[N]--;
cnt[N - 1 - (N - 1) / 2]++;
cnt[(N - 1) / 2]++;
}
}
printf("Case #%d: %d %d\n", i, N - 1 - (N - 1) / 2, (N - 1) / 2);
}
fclose (stdin);
fclose (stdout);
return 0;
}
| [
"robert.benic@fer.hr"
] | robert.benic@fer.hr |
6b59c1a9ec4d4b0c6147aded7d5aebc4d2b86d49 | c53475be4728b07d8185c3885cb2f8c7668d9d76 | /9.cpp | 2260e77f169a03658d6dfe85a72d0baeda79114a | [] | no_license | JiangMingchen/PAT-Advanced-Level-Problems-using-Cpp | 9a8d27169ad600764643785831849610f87e3a63 | 9424f96a30d2e5d7ea1c1c32793f830066f28bc0 | refs/heads/master | 2022-04-17T22:48:04.723958 | 2020-04-17T05:41:18 | 2020-04-17T05:41:18 | 239,486,707 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,271 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class item
{
public:
int exp;
float coe;
item(int e = 0, float c = 0) { exp = e; coe = c; }
item operator *(const item& b)
{
item t;
t.exp = this->exp + b.exp;
t.coe = this->coe * b.coe;
return t;
}
};
bool cmp(item a, item b)
{
return a.exp < b.exp ? 1 : 0;
}
int main()
{
int n;
int e;
float c;
item a[11];
item b[11];
vector<item> result;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d %f", &e,& c);
a[i].exp = e;
a[i].coe = c;
}
int m;
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
scanf("%d %f", &e, &c);
b[i].exp = e;
b[i].coe = c;
}
int count = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m ; j++)
{
result.push_back(a[i] * b[j]);
}
}
sort(result.begin(), result.end(), cmp);
for (vector<item>::iterator v = result.begin() + 1; v != result.end(); v++)
{
if ((*v).exp == (*(v - 1)).exp)
{
(*(v - 1)).coe += (*v).coe;
result.erase(v--);
if ((*v).coe == 0) result.erase(v--);
}
}
reverse(result.begin(), result.end());
cout << result.size();
for (int i = 0; i < result.size(); i++)
{
if (i != result.size())cout << " ";
cout << result[i].exp << " ";
printf("%.1f", result[i].coe);
}
}
| [
"jiangmingchen@live.com"
] | jiangmingchen@live.com |
f70f64d1f6589c920ff7d20330a789cf801d440b | 3a54bd04f0ba813076fcee820c20eab93297d8e2 | /OS/pwdCommand.cpp | c7a478335e7cb78220192f55c3fb7f58b887da64 | [] | no_license | aivus/os-emulator | c2e809553428046fe2794807979195f3f3164f0f | 154dac6ea3913165a835c64fe06d349f01829cd4 | refs/heads/master | 2020-06-01T16:05:58.208035 | 2017-03-07T13:41:38 | 2017-03-07T13:41:38 | 21,008,196 | 1 | 1 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 644 | cpp | #include <iostream>
#include <vector>
#include <string>
#include "pwdCommand.h"
#include "VFS.h"
#include "retCodes.h"
using namespace std;
std::vector<std::string> pwdCommand::path;
// Конструктор
pwdCommand::pwdCommand()
{
//
}
// Деструктор
pwdCommand::~pwdCommand()
{
//
}
int pwdCommand::action(VFS *vfs, std::vector<std::string> data)
{
if (vfs == NULL)
return OSERROR;
std::vector<std::string>::iterator it = pwdCommand::path.begin(), end = pwdCommand::path.end();
cout << "/" ;
for (; it != end; ++it)
cout << it->c_str() << "/";
cout << endl;
return OSSUCCESS;
} | [
"aivus@aivus.name"
] | aivus@aivus.name |
b3b559e39db6fb97758d4ba533bb4797df863ff7 | 6ed471f36e5188f77dc61cca24daa41496a6d4a0 | /SDK/Ceiling_Doorway_Stone_classes.h | bfe0c730085efd836205dd273ab5118233b70591 | [] | no_license | zH4x-SDK/zARKSotF-SDK | 77bfaf9b4b9b6a41951ee18db88f826dd720c367 | 714730f4bb79c07d065181caf360d168761223f6 | refs/heads/main | 2023-07-16T22:33:15.140456 | 2021-08-27T13:40:06 | 2021-08-27T13:40:06 | 400,521,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | h | #pragma once
// Name: ARKSotF, Version: 178.8.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Ceiling_Doorway_Stone.Ceiling_Doorway_Stone_C
// 0x0000 (0x0928 - 0x0928)
class ACeiling_Doorway_Stone_C : public ACeiling_Doorway_Base_SM_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Ceiling_Doorway_Stone.Ceiling_Doorway_Stone_C");
return ptr;
}
void UserConstructionScript();
void ExecuteUbergraph_Ceiling_Doorway_Stone(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
3fe4df441d8f5dae78bd2c972132e3a7adc1b340 | 0c384a65fb670fbc0a2dde7d33054cb18429634e | /SocketAnnotator/source/SocketAnnotator.cpp | f9794c2c74a77bcf1c979eb0a9701c7695eb7224 | [] | no_license | DURAARK/elecdetect | c204347a24ecb025a3f712d5f31ed845d0385516 | fb711de94893905e1e26be65924600ff4b188895 | refs/heads/master | 2016-09-03T07:09:09.205956 | 2015-04-24T13:00:23 | 2015-04-24T13:00:23 | 34,518,807 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,873 | cpp | #include <iostream>
#include <vector>
#include <dirent.h>
#include <opencv2/opencv.hpp>
#include "CAnnotation.h"
#include "Utils.h"
#include "tinyxml2.h"
using namespace std;
using namespace cv;
using namespace tinyxml2;
int main(int argc, char* argv[])
{
//------------------------------------------------
// Reading input parameters
CommandParams c_params;
parseCmd(argc, argv, c_params);
//--------------------------------------------
// Read unprocessed image files
vector<string> file_list;
getFileList(c_params.str_dir_, file_list);
srand(time(NULL));
switch(c_params.anno_mode_)
{
case ANNOTATION:
{
XMLDocument doc;
// check if there is already a file containing annotations
if(doc.LoadFile(c_params.str_filename_.c_str()) == XML_SUCCESS)
{
XMLElement* cur_image;
for(cur_image = doc.FirstChildElement("Annotation"); cur_image != NULL; cur_image = cur_image->NextSiblingElement())
{
string filename = cur_image->Attribute("image");
cout << "Annotation already exists for: " << filename << " skipping.. " << endl;
// if there exists already an annotation for a file that is in the list again, reject it now
vector<string>::iterator finder = find(file_list.begin(), file_list.end(), filename);
if(finder != file_list.end())
{
file_list.erase(finder);
}
}
}
else // if an opening error occured, create a new file
{
doc.InsertEndChild(doc.NewDeclaration(NULL));
}
// manual annotation
vector<CAnnotation> annotations;
vector<string>::const_iterator filename_it;
for(filename_it = file_list.begin(); filename_it != file_list.end(); ++filename_it)
{
CAnnotation annotation(*filename_it);
if(annotation.isImageLoaded() && annotation.annotate())
{
annotation.addXMLString(doc);
annotations.push_back(annotation);
}
else
{
break;
}
}
// save annotations
doc.SaveFile(c_params.str_filename_.c_str());
break;
}
case REANNOTATION:
{
// redefine already annotated points
// load existing XML
XMLDocument doc;
doc.Clear();
if(doc.LoadFile(c_params.str_filename_.c_str()) != XML_SUCCESS)
{
cerr << "Loading of XML file failed" << endl;
exit(-1);
}
vector<XMLElement*> to_delete;
XMLElement* cur_image_xml;
for(cur_image_xml = doc.FirstChildElement("Annotation"); cur_image_xml != NULL; cur_image_xml = cur_image_xml->NextSiblingElement("Annotation"))
{
string filename = cur_image_xml->Attribute("image");
cout << "Annotation: " << filename << endl;
CAnnotation cur_image(filename);
if(cur_image.isImageLoaded())
{
cur_image.loadFromXMLElement(cur_image_xml);
if(cur_image.annotate())
{
cout << "replacing information" << endl;
to_delete.push_back(cur_image_xml);
// add the new one (at the end)
cur_image.addXMLString(doc);
}
else
{
break;
}
}
}
// delete old XML Nodes
for(vector<XMLElement*>::const_iterator to_del_it = to_delete.begin(); to_del_it != to_delete.end(); ++ to_del_it)
{
doc.DeleteChild(*to_del_it);
}
// save annotations
doc.SaveFile(c_params.str_filename_.c_str());
break;
}
case CUTTING:
{
// automatic warping, cutting and renaming
XMLDocument doc;
doc.Clear();
if(doc.LoadFile(c_params.str_filename_.c_str()) != XML_SUCCESS)
{
cerr << "Loading of XML file failed" << endl;
exit(-1);
}
MKDIR(c_params.str_dir_.c_str());
XMLElement* cur_image_xml;
for(cur_image_xml = doc.FirstChildElement("Annotation"); cur_image_xml != NULL; cur_image_xml = cur_image_xml->NextSiblingElement("Annotation"))
{
string filename = cur_image_xml->Attribute("image");
cout << "Annotation: " << filename << endl;
CAnnotation cur_image(filename);
if(cur_image.isImageLoaded())
{
cur_image.loadFromXMLElement(cur_image_xml);
cur_image.saveAnnotatedImages(c_params.str_dir_);
}
}
// writing strictly negative files
if(!c_params.str_neg_dir_.empty())
{
cout << "writing strictly negative samples..." << endl;
vector<string> neg_file_list;
getFileList(c_params.str_neg_dir_, neg_file_list);
for(vector<string>::const_iterator neg_it = neg_file_list.begin(); neg_it != neg_file_list.end(); ++neg_it)
{
cout << "Negative Image: " << *neg_it << endl;
CAnnotation cur_image(*neg_it);
if(cur_image.isImageLoaded())
{
cur_image.saveAnnotatedImages(c_params.str_dir_);
}
}
}
break;
}
}
//-------------------------------------------
return 0;
}
| [
"robert.viehauser@student.tugraz.at"
] | robert.viehauser@student.tugraz.at |
e8fd9a7286b5109af42ccaa8eeec0cd4adc8f826 | e1a4acf1d41b152a0f811e82c27ad261315399cc | /algorithms/kernel/neural_networks/layers/tanh_layer/forward/tanh_layer_forward_dense_default_batch_fpt_dispatcher.cpp | 4f2007a37ae956ed02b5b48fd6ba1d3c98be9cec | [
"Apache-2.0",
"Intel"
] | permissive | ValeryiE/daal | e7572f16e692785db1e17bed23b6ab709db4e705 | d326bdc5291612bc9e090d95da65aa579588b81e | refs/heads/master | 2020-08-29T11:37:16.157315 | 2019-10-25T13:11:01 | 2019-10-25T13:11:01 | 218,020,419 | 0 | 0 | Apache-2.0 | 2019-10-28T10:22:19 | 2019-10-28T10:22:19 | null | UTF-8 | C++ | false | false | 1,284 | cpp | /* file: tanh_layer_forward_dense_default_batch_fpt_dispatcher.cpp */
/*******************************************************************************
* Copyright 2014-2019 Intel 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.
*******************************************************************************/
//++
// Implementation of hyperbolic tangent function calculation algorithm container.
//--
#include "tanh_layer_forward_batch_container.h"
namespace daal
{
namespace algorithms
{
namespace neural_networks
{
namespace layers
{
namespace forward
{
__DAAL_INSTANTIATE_DISPATCH_LAYER_CONTAINER_FORWARD(neural_networks::layers::tanh::forward::BatchContainer, DAAL_FPTYPE,
neural_networks::layers::tanh::defaultDense)
}
}
}
}
}
| [
"nikolay.a.petrov@intel.com"
] | nikolay.a.petrov@intel.com |
92b0056b3d83365cfc665b6a7dcb8fe8284393c2 | 2cf838b54b556987cfc49f42935f8aa7563ea1f4 | /aws-cpp-sdk-eventbridge/include/aws/eventbridge/model/CreateConnectionRequest.h | 386379f17cc39eb65085211347bfbf9926804ed1 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | QPC-database/aws-sdk-cpp | d11e9f0ff6958c64e793c87a49f1e034813dac32 | 9f83105f7e07fe04380232981ab073c247d6fc85 | refs/heads/main | 2023-06-14T17:41:04.817304 | 2021-07-09T20:28:20 | 2021-07-09T20:28:20 | 384,714,703 | 1 | 0 | Apache-2.0 | 2021-07-10T14:16:41 | 2021-07-10T14:16:41 | null | UTF-8 | C++ | false | false | 7,580 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/eventbridge/EventBridge_EXPORTS.h>
#include <aws/eventbridge/EventBridgeRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/eventbridge/model/ConnectionAuthorizationType.h>
#include <aws/eventbridge/model/CreateConnectionAuthRequestParameters.h>
#include <utility>
namespace Aws
{
namespace EventBridge
{
namespace Model
{
/**
*/
class AWS_EVENTBRIDGE_API CreateConnectionRequest : public EventBridgeRequest
{
public:
CreateConnectionRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "CreateConnection"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The name for the connection to create.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>The name for the connection to create.</p>
*/
inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }
/**
* <p>The name for the connection to create.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The name for the connection to create.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>The name for the connection to create.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>The name for the connection to create.</p>
*/
inline CreateConnectionRequest& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>The name for the connection to create.</p>
*/
inline CreateConnectionRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>The name for the connection to create.</p>
*/
inline CreateConnectionRequest& WithName(const char* value) { SetName(value); return *this;}
/**
* <p>A description for the connection to create.</p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>A description for the connection to create.</p>
*/
inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }
/**
* <p>A description for the connection to create.</p>
*/
inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }
/**
* <p>A description for the connection to create.</p>
*/
inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }
/**
* <p>A description for the connection to create.</p>
*/
inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }
/**
* <p>A description for the connection to create.</p>
*/
inline CreateConnectionRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>A description for the connection to create.</p>
*/
inline CreateConnectionRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}
/**
* <p>A description for the connection to create.</p>
*/
inline CreateConnectionRequest& WithDescription(const char* value) { SetDescription(value); return *this;}
/**
* <p>The type of authorization to use for the connection.</p>
*/
inline const ConnectionAuthorizationType& GetAuthorizationType() const{ return m_authorizationType; }
/**
* <p>The type of authorization to use for the connection.</p>
*/
inline bool AuthorizationTypeHasBeenSet() const { return m_authorizationTypeHasBeenSet; }
/**
* <p>The type of authorization to use for the connection.</p>
*/
inline void SetAuthorizationType(const ConnectionAuthorizationType& value) { m_authorizationTypeHasBeenSet = true; m_authorizationType = value; }
/**
* <p>The type of authorization to use for the connection.</p>
*/
inline void SetAuthorizationType(ConnectionAuthorizationType&& value) { m_authorizationTypeHasBeenSet = true; m_authorizationType = std::move(value); }
/**
* <p>The type of authorization to use for the connection.</p>
*/
inline CreateConnectionRequest& WithAuthorizationType(const ConnectionAuthorizationType& value) { SetAuthorizationType(value); return *this;}
/**
* <p>The type of authorization to use for the connection.</p>
*/
inline CreateConnectionRequest& WithAuthorizationType(ConnectionAuthorizationType&& value) { SetAuthorizationType(std::move(value)); return *this;}
/**
* <p>A <code>CreateConnectionAuthRequestParameters</code> object that contains the
* authorization parameters to use to authorize with the endpoint. </p>
*/
inline const CreateConnectionAuthRequestParameters& GetAuthParameters() const{ return m_authParameters; }
/**
* <p>A <code>CreateConnectionAuthRequestParameters</code> object that contains the
* authorization parameters to use to authorize with the endpoint. </p>
*/
inline bool AuthParametersHasBeenSet() const { return m_authParametersHasBeenSet; }
/**
* <p>A <code>CreateConnectionAuthRequestParameters</code> object that contains the
* authorization parameters to use to authorize with the endpoint. </p>
*/
inline void SetAuthParameters(const CreateConnectionAuthRequestParameters& value) { m_authParametersHasBeenSet = true; m_authParameters = value; }
/**
* <p>A <code>CreateConnectionAuthRequestParameters</code> object that contains the
* authorization parameters to use to authorize with the endpoint. </p>
*/
inline void SetAuthParameters(CreateConnectionAuthRequestParameters&& value) { m_authParametersHasBeenSet = true; m_authParameters = std::move(value); }
/**
* <p>A <code>CreateConnectionAuthRequestParameters</code> object that contains the
* authorization parameters to use to authorize with the endpoint. </p>
*/
inline CreateConnectionRequest& WithAuthParameters(const CreateConnectionAuthRequestParameters& value) { SetAuthParameters(value); return *this;}
/**
* <p>A <code>CreateConnectionAuthRequestParameters</code> object that contains the
* authorization parameters to use to authorize with the endpoint. </p>
*/
inline CreateConnectionRequest& WithAuthParameters(CreateConnectionAuthRequestParameters&& value) { SetAuthParameters(std::move(value)); return *this;}
private:
Aws::String m_name;
bool m_nameHasBeenSet;
Aws::String m_description;
bool m_descriptionHasBeenSet;
ConnectionAuthorizationType m_authorizationType;
bool m_authorizationTypeHasBeenSet;
CreateConnectionAuthRequestParameters m_authParameters;
bool m_authParametersHasBeenSet;
};
} // namespace Model
} // namespace EventBridge
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
9d824dad4898ce2e2c48de037d006577d7505810 | cc6f69541a77b227f0f122105ab73863cf443f0b | /Recipent.cpp | 130828c5828a797e1941f1d360cd97c494bcdfb7 | [] | no_license | sennar23a/NewAddressBook | 87cfc91366a3a9a6d2173cc0133fc16a7f243a47 | e64127b3d56212d291860961089fb44be18ec860 | refs/heads/master | 2020-04-18T09:17:22.971147 | 2019-01-24T20:05:25 | 2019-01-24T20:05:25 | 167,428,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,468 | cpp | #include "Recipent.h"
using namespace std;
Recipent::Recipent() {
individualNumberOfEachFriend = 0;
userId = 0;
name = "";
surname = "";
phoneNumber = "";
email = "";
address = "";
}
Recipent::~Recipent() {;}
int Recipent::getIndividualNumberOfEachFriend() {
return individualNumberOfEachFriend;
}
int Recipent::getUserId() {
return userId;
}
string Recipent::getName() {
return name;
}
string Recipent::getSurname() {
return surname;
}
string Recipent::getPhoneNumber() {
return phoneNumber;
}
string Recipent::getEmail() {
return email;
}
string Recipent::getAddress() {
return address;
}
void Recipent::setIndividualNumberOfEachFriend(int individualNumberOfEachFriend) {
this->individualNumberOfEachFriend = individualNumberOfEachFriend;
}
void Recipent::setUserId(int userId) {
this->userId = userId;
}
void Recipent::setName(string name) {
this->name = name;
}
void Recipent::setSurname(string surname) {
this->surname = surname;
}
void Recipent::setPhoneNumber(string phoneNumber) {
this->phoneNumber = phoneNumber;
}
void Recipent::setEmail(string email) {
this->email = email;
}
void Recipent::setAddress(string address) {
this->address = address;
}
Users Recipent::getTheIdLoggedUser(){
Users users;
users.takeIdLoggedUser();
return users;
}
| [
"noreply@github.com"
] | noreply@github.com |
8fc7c432914d46e6160269ac62eb6bdc58c5d2ce | 3c79edef27fe742f146e01a886a350ff13064058 | /Receiver_v1.01/Receiver_v1.01.ino | 5524753109f3e345ad8986e3df272627591896d9 | [] | no_license | amarotica/Remote-Operated-Vehicle | 0b5939ff1436f912c0325c899fd10e6b06aa9489 | a18da4a57404e12ed76368559d86e21a88f997e1 | refs/heads/master | 2020-03-23T20:40:53.443458 | 2019-02-20T18:26:21 | 2019-02-20T18:26:21 | 142,055,280 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,200 | ino | //-------Written by Taylor Amarotico-------//
// Remote Operated Vehicle Receiver //
char SoftwareVersion = "v1.02";
// transmissionArray Variable Inputs Declaration //
int transmissionArray[12];
int Rmotorvalue = transmissionArray[1];
int Lmotorvalue = transmissionArray[2];
int Rdirectionvalue = transmissionArray[3];
int Ldirectionvalue = transmissionArray[4];
int Ebrakevalue = transmissionArray[5];
int Lightsvalue = transmissionArray[6];
int Highbeamsvalue = transmissionArray[7];
int JSAXvalue = transmissionArray[8];
int JSAYvalue = transmissionArray[9];
int JSBvalue = transmissionArray[10];
int JSABvalue = transmissionArray[11];
int VerificationValue = transmissionArray[12];
// Pin and Constant Declaration //
const int Rmotor = 2;
const int Lmotor = 3;
const int Rdirection = 4;
const int Ldirection = 5;
const int Ebrake = 12;
const int Lights = 6;
const int Highbeams = 7;
const int JSAX = 8;
const int JSAY = 9;
const int JSB = 10;
const int JSAB = 11;
void setup() {
/* // Only used when debugging.
// Debugging //
Serial.begin(9600);
Serial.println("System Initializing");
delay(500);
Serial.print(".");
delay(500);
Serial.print(".");
delay(500);
Serial.println(".");
delay(500);
Serial.println(SoftwareVersion);
delay(250);
*/
// Output Setup //
pinMode(Rmotor, OUTPUT);
pinMode(Lmotor, OUTPUT);
pinMode(Rdirection, OUTPUT);
pinMode(Ldirection, OUTPUT);
pinMode(Ebrake, OUTPUT);
pinMode(Lights, OUTPUT);
pinMode(Highbeams, OUTPUT);
pinMode(JSAX, OUTPUT);
pinMode(JSAY, OUTPUT);
pinMode(JSB, OUTPUT);
pinMode(JSAB, OUTPUT);
// Serial.println("Outputs Initialized");
delay(50);
// Safe Initialize //
analogWrite(Rmotor, 0);
analogWrite(Lmotor, 0);
digitalWrite(Rdirection, 0);
digitalWrite(Ldirection, 0);
digitalWrite(Ebrake, 0);
digitalWrite(Lights, 0);
digitalWrite(Highbeams, 0);
analogWrite(JSAX, 0);
analogWrite(JSAY, 0);
digitalWrite(JSB, 0);
digitalWrite(JSAB, 0);
// Serial.println("Safe Output Initialized");
delay(50);
}
void loop() {
receiverModule();
enableModule();
}
void enableModule() { // This module tests to see if emergency brake is tripped and if so, disables actions and writes motors to 0/255 duty cycle
if (Ebrakevalue == 1){
analogWrite(Rmotor, 0);
analogWrite(Lmotor, 0);
digitalWrite(Ebrake, HIGH);
delay(1000);
}
else {
actionsModule();
}
//----------------------End of enableModule function----------------------//
}
void actionsModule() { // This module writes motor and accesory values to output pins via PWM and digital on/off
analogWrite(Rmotor, Rmotorvalue);
analogWrite(Lmotor, Lmotorvalue);
digitalWrite(Rdirection, Rdirectionvalue);
digitalWrite(Ldirection, Ldirectionvalue);
digitalWrite(Lights, Lightsvalue);
digitalWrite(Highbeams, Highbeamsvalue);
analogWrite(JSAX, JSAXvalue);
analogWrite(JSAY, JSAYvalue);
digitalWrite(JSB, JSBvalue);
digitalWrite(JSAB, JSABvalue);
//----------------------End of actionsModule function----------------------//
}
void receiverModule() { // This module takes in the data from the LoRa module and converts it into useable values for the enableModule and actionsModule
String str = "";
//String str ="1233,4146,7389,1511,21213,14315,16117,1819,2021,2223,2425,23";
while (Serial.available() > 0) {
str += (char)Serial.read();
delay(5);
}
if (str != "") {
int indexArray[12];
indexArray[0]=str.indexOf(",");
for(int i=1;i<=10;i++){
indexArray[i]=str.indexOf(",",(indexArray[i-1] +1));
}
transmissionArray[1]=str.substring(0,indexArray[0]).toInt();
for(int i=2;i<=11;i++){
transmissionArray[i]=str.substring(indexArray[i-2]+1,indexArray[i-1]).toInt();
}
transmissionArray[12]=str.substring(indexArray[10]+1).toInt();
for(int i=1;i<=12;i++){
//Serial.println(transmissionArray[i]);
}
// while(1);
}
//----------------------End of receiverModule function----------------------//
}
| [
"noreply@github.com"
] | noreply@github.com |
e068170d3d755519b65a75c5a78eb29940de0135 | 53635c70f08969fe29da4bda242ffa117a39d850 | /OpenGL_Tuto/gameplay/modes/gamemode_editor.h | e6bc1d3c803476f8d08f8c6b2d766842e5fe59dc | [] | no_license | theDoubi125/OpenGL_Tuto | 161adc246d0e883fbf1fb251a582279336811a88 | 72ad6864fbee2736dc68b91b857cbd147688cbab | refs/heads/master | 2020-04-22T09:21:46.437016 | 2019-07-20T23:32:42 | 2019-07-20T23:32:42 | 170,269,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 61 | h | #pragma once
#include "transform.h"
namespace gamemode
{
} | [
"julien.revel@telecomnancy.net"
] | julien.revel@telecomnancy.net |
144f8ffcc9251672aab82e517bc16719df4c2fac | b7c929c578e3f8bdb3757ecb6585c33c0005a99a | /asg5/code_generator.h | 52b543b3e46b8197989eead7e4144ff44363eb93 | [] | no_license | VisionsOfDrifting/CMPS_104a | 09c19812029cbd8639f4f644d5dee757e18e9988 | 528a73421980d97cc49c001e3fc22697548f1e95 | refs/heads/master | 2021-01-01T20:43:56.464641 | 2017-07-31T19:35:31 | 2017-07-31T19:35:31 | 98,919,067 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 681 | h | //*****************************************************
//* Nicholas Pappas
//* Riley Honbo
//* nhpappas@ucsc.edu
//* rhonbo@ucsc.edu
//* CMPS 104a w/ Mackey
//* Assignment: Project 5
//*****************************************************
#ifndef __CODE_GENERATOR_H__
#define __CODE_GENERATOR_H__
#include <iostream>
#include <bitset>
#include <string>
#include <unordered_map>
#include <vector>
#include "lyutils.h"
#include "auxlib.h"
#include "astree.h"
using namespace std;
extern FILE* oil_output;
const char* give_name(astree* node, string current_name);
void oil_stuff(astree* node, int depth, astree* extra);
void write_oil(astree* root, int depth);
#endif
| [
"nhpappas@ucsc.edu"
] | nhpappas@ucsc.edu |
e10afa012487b023cec7d5a49d1ddbc1da659d15 | 6fee31ef3f6c3707de20a5956b2d96575fdf0aac | /znd/dev/src/gui/hmi/libs/scripttools/debugging/qscriptdebuggeragent_p_p.h | 0b0c4a5b4d377ae8a37bfd81fba99c75c245cbfe | [] | no_license | hilockman/cim2ddl | 605b05e5c67acde1f9b0c93e6b0a227dd27519a6 | 78ec9a3b4136710ac659fa40e3da28c9bb57c10f | refs/heads/master | 2021-01-01T17:50:55.311126 | 2019-01-03T05:35:47 | 2019-01-03T05:35:47 | 98,163,859 | 3 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 1,726 | h | #ifndef QSCRIPTDEBUGGERAGENT_P_P_H
#define QSCRIPTDEBUGGERAGENT_P_P_H
#include <QtScript/qscriptvalue.h>
#include <QtCore/qdatetime.h>
#include <QtCore/qhash.h>
#include <QtCore/qmap.h>
#include <QtCore/qlist.h>
#include "qscriptscriptdata_p.h"
#include "qscriptbreakpointdata_p.h"
QT_BEGIN_NAMESPACE
class QScriptDebuggerAgent;
class QScriptDebuggerAgentPrivate
{
public:
enum State {
NoState,
SteppingIntoState,
SteppedIntoState,
SteppingOverState,
SteppedOverState,
SteppingOutState,
SteppedOutState,
RunningToLocationState,
ReachedLocationState,
InterruptingState,
InterruptedState,
BreakpointState,
ReturningByForceState,
ReturnedByForceState
};
QScriptDebuggerAgentPrivate();
~QScriptDebuggerAgentPrivate();
static QScriptDebuggerAgentPrivate *get(QScriptDebuggerAgent *);
State state;
int stepDepth;
int stepCount;
int targetScriptId;
QString targetFileName;
int targetLineNumber;
QScriptValue stepResult;
int returnCounter;
QScriptValue returnValue;
int nextBreakpointId;
QHash<qint64, QList<int> > resolvedBreakpoints;
QHash<QString, QList<int> > unresolvedBreakpoints;
QScriptBreakpointMap breakpoints;
int hitBreakpointId;
QScriptScriptMap scripts;
QScriptScriptMap checkpointScripts;
QScriptScriptMap previousCheckpointScripts;
QList<QList<qint64> > scriptIdStack;
QList<qint64> contextIdStack;
QList<qint64> checkpointContextIdStack;
qint64 nextContextId;
QTime processEventsTimer;
int statementCounter;
QScriptDebuggerBackendPrivate *backend;
};
QT_END_NAMESPACE
#endif
| [
"43579183@qq.com"
] | 43579183@qq.com |
2529204e38cc2b8b580fbb0b4a77863bc6a6fa24 | ff9cbe1103c9a11d6731c7291f149a9befa30def | /Fursanov/2.1.5/lab2t1.cpp | 4c283aa9afcb60c2ad684d2283a2baf9a01f1473 | [] | no_license | PashaKlybik/prog-053506 | d5ed7f9cfe23883fa660abfc976f8a3146dd74ff | a4b0433aa72bc3acdd26733ef0312cc7426f1668 | refs/heads/main | 2023-06-09T20:13:28.642365 | 2021-06-25T07:07:28 | 2021-06-25T07:07:28 | 345,938,870 | 0 | 41 | null | 2021-06-25T07:07:28 | 2021-03-09T08:42:31 | C | UTF-8 | C++ | false | false | 4,073 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <locale.h>
#include <malloc.h>
void sell(int Veg, float* mas, int* prise, float* cost)
{
if (Veg == 0)
printf("Цена/кг картофеля 500р\n");
if (Veg == 1)
printf("Цена/кг моркови 1000р\n");
if (Veg == 2)
printf("Цена/кг свёклы 700р\n");
if (mas[Veg] == 0)
{
}
mas[Veg] = 0;
printf(" Заказать(кг): ");
while (scanf("%f", &mas[Veg]) <= 0)
{
printf("Некорректный ввод. попробуйте ещё раз \n");
while (getchar() != '\n') {}
printf(" Заказать(кг): ");
}
printf("Заказ принят\n");
printf("\n");
cost[Veg] = mas[Veg] * prise[Veg];
}
void shopping_cart(float* mas, int* prise, float* cost)
{
printf("Корзина\n");
printf("Картофель:\n\tцена: %dруб.\n\tзаказано: %.2fкг.\n\tстоимость: %.0fруб\n", prise[0], mas[0], cost[0]);
printf("Морковь:\n\tцена: %dруб.\n\tзаказано: %.2fкг.\n\tстоимость: %.0fруб\n", prise[1], mas[1], cost[1]);
printf("Свёкла:\n\tцена: %dруб.\n\tзаказано: %.2fкг.\n\tстоимость: %.0fруб\n\n", prise[2], mas[2], cost[2]);
}
void Cost(float* mas, int* prise, float* cost)
{
int discount = 0;
printf("итого:\n");
printf("\tкартофель: %.0fруб.\n",cost[0]);
printf("\tморковь: %.0fруб.\n", cost[1]);
printf("\tсвёкла: %.0fруб.\n", cost[2]);
printf("\tдоставка: 15000 руб.\n");
if (mas[0] + mas[1] + mas[2] > 10)
discount = 10;
if (mas[0] + mas[1] + mas[2] > 25)
discount = 20;
if (mas[0] + mas[1] + mas[2] > 50)
discount = 30;
float finaly = (cost[0] + cost[0] + cost[0] + 15000) * (100 - discount) / 100;
printf("\tскидка %d%%\n",discount);
printf("____________________________________________________________________\n");
printf("(%.0fруб. + %.0fруб. + %.0fруб. + 15000руб.) - %d%% = %.2fруб.\n\n", cost[0], cost[1], cost[2],discount,finaly);
}
void feedback()
{
printf("\tНазвание магазина: eVegetables\n");
printf("\tНомер лицензии: 52426\n");
printf("\tКонтактная информация:\n\t\tТелефон: 8-800-555-35-35\n\t\tМы в Одноклассниках: eVegetables.Ок.by\n\t\tПочта: eVegetables@mail.by\n\n");
}
int main()
{
float* mas = (float*)malloc(3 * sizeof(float));
int* prise = (int*)malloc(3 * sizeof(int));
float* cost = (float*)malloc(3 * sizeof(float));
prise[0] = 500;
prise[1] = 1000;
prise[2] = 700;
mas[0] = 0;
mas[1] = 0;
mas[2] = 0;
cost[0] = 0;
cost[1] = 0;
cost[2] = 0;
setlocale(LC_ALL, "Russian");
printf("Вас приветствует торговое предприятие eVegetables\n");
int button = 1;
while (button)
{
printf("введите нужную цифру чтобы:\n1. Заказать картофель.\n2. Заказать морковь.\n3. Заказать свёклу.\n4. Корзина.\n5. Расчёт стоимости заказа.\n6. Обратная связь.\n7.Выход.\n");
printf("кнопка: ");
while (scanf("%d", &button) <= 0)
{
printf("Некорректный ввод. попробуйте ещё раз \n");
while (getchar() != '\n') {}
printf("кнопка: ");
}
printf("\n");
switch (button)
{
case 1:
sell(button-1, mas, prise, cost);
break;
case 2:
sell(button - 1, mas, prise, cost);
break;
case 3:
sell(button - 1, mas, prise, cost);
break;
case 4:
shopping_cart(mas, prise, cost);
break;
case 5:
Cost(mas, prise, cost);
break;
case 6:
feedback();
break;
case 7:
printf("Благодарим вас за посещение нашего магазина");
button = 0;
break;
default:
printf("такой кнопки нет");
break;
}
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
4c99bbca5f1367f7775541ebf5acfa8251f0737e | c04b8a415b957dc3afae4d911f6ac18285ef03ed | /apex_guest/Client/Client/overlay.h | 6f519f18ecc63b4537d674448c117f5488079491 | [] | no_license | Nandotama14/NandoDev-ApexEepAimBot | 1bdfacc7d519fa6c316a109e9332954e4931174f | 238cd72bd3837d191f472a6e3115a7c1ca7f9553 | refs/heads/main | 2023-04-14T23:55:29.284200 | 2021-04-17T17:01:01 | 2021-04-17T17:01:01 | 358,933,808 | 7 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,543 | h | #pragma once
#include <Windows.h>
#include <WinUser.h>
#include <Dwmapi.h>
#pragma comment(lib, "dwmapi.lib")
#include <stdlib.h>
#include <vector>
#include <chrono>
#include <cwchar>
#include <thread>
#include <string>
#include "XorString.h"
#include "imgui/imgui.h"
#include "imgui/imgui_impl_dx9.h"
#include "imgui/imgui_impl_win32.h"
#include <d3d9.h>
#pragma comment(lib, "d3d9.lib")
#include <d3dx9.h>
#pragma comment(lib, "d3dx9.lib")
#define GREEN ImColor(0, 255, 0)
#define RED ImColor(255, 0, 0)
#define BLUE ImColor(0, 0, 255)
#define ORANGE ImColor(255, 165, 0)
#define WHITE ImColor(255, 255, 255)
typedef struct visuals
{
bool box = true;
bool line = true;
bool distance = true;
bool healthbar = true;
bool shieldbar = true;
bool name = true;
}visuals;
class Overlay
{
public:
void Start();
DWORD CreateOverlay();
void Clear();
int getWidth();
int getHeight();
void RenderInfo();
void RenderMenu();
void RenderEsp();
void ClickThrough(bool v);
void DrawLine(ImVec2 a, ImVec2 b, ImColor color, float width);
void DrawBox(ImColor color, float x, float y, float w, float h);
void Text(ImVec2 pos, ImColor color, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect);
void RectFilled(float x0, float y0, float x1, float y1, ImColor color, float rounding, int rounding_corners_flags);
void ProgressBar(float x, float y, float w, float h, int value, int v_max);
void String(ImVec2 pos, ImColor color, const char* text);
private:
bool running;
HWND overlayHWND;
}; | [
"noreply@github.com"
] | noreply@github.com |
089645ba0a927fde1da46c0bb5d564fa6cd12762 | 01a42b69633daf62a2eb3bb70c5b1b6e2639aa5f | /SCUM_Cal30-06_functions.cpp | f863f84f23d86d3233fc6f17b8b048de74457d75 | [] | no_license | Kehczar/scum_sdk | 45db80e46dac736cc7370912ed671fa77fcb95cf | 8d1770b44321a9d0b277e4029551f39b11f15111 | refs/heads/master | 2022-07-25T10:06:20.892750 | 2020-05-21T11:45:36 | 2020-05-21T11:45:36 | 265,826,541 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,726 | cpp | // Scum 3.79.22573 (UE 4.24)
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function ConZ.AmmunitionItem.SetAmmoCount
// ()
// Parameters:
// int* count (Parm, ZeroConstructor, IsPlainOldData)
// bool* replicateToOwner (Parm, ZeroConstructor, IsPlainOldData)
void ACal30_06_C::SetAmmoCount(int* count, bool* replicateToOwner)
{
static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.SetAmmoCount");
ACal30_06_C_SetAmmoCount_Params params;
params.count = count;
params.replicateToOwner = replicateToOwner;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ConZ.AmmunitionItem.OnRep_AmmoCountOwnerHelper
// ()
void ACal30_06_C::OnRep_AmmoCountOwnerHelper()
{
static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.OnRep_AmmoCountOwnerHelper");
ACal30_06_C_OnRep_AmmoCountOwnerHelper_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ConZ.AmmunitionItem.OnRep_AmmoCount
// ()
void ACal30_06_C::OnRep_AmmoCount()
{
static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.OnRep_AmmoCount");
ACal30_06_C_OnRep_AmmoCount_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ConZ.AmmunitionItem.GetAmmoCount
// ()
// Parameters:
// int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
int ACal30_06_C::GetAmmoCount()
{
static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.GetAmmoCount");
ACal30_06_C_GetAmmoCount_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ConZ.AmmunitionItem.Client_SetAmmoCount
// ()
// Parameters:
// int* count (Parm, ZeroConstructor, IsPlainOldData)
void ACal30_06_C::Client_SetAmmoCount(int* count)
{
static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.Client_SetAmmoCount");
ACal30_06_C_Client_SetAmmoCount_Params params;
params.count = count;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"65712402+Kehczar@users.noreply.github.com"
] | 65712402+Kehczar@users.noreply.github.com |
74c417ddcaacb3cc973b45a886315794b667ed15 | 72742d4ee57fb66cfe3f10290ccb596dcde1e59e | /codeforces/a.cpp | 2a4834122f48e690ab161c0d4fb8997fddcaf5b3 | [] | no_license | mertsaner/Algorithms | cd5cf84548ea10aafb13b4a3df07c67c1a007aef | f7aecb7e8aadff1e9cf49cc279530bc956d54260 | refs/heads/master | 2023-03-18T03:18:26.122361 | 2016-02-14T22:48:31 | 2016-02-14T22:48:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | cpp | #include <iostream>
using namespace std;
int l[10];
int main()
{
int t,c=0,leg;
for(int i=0;i<6;i++)
{
cin >> t;
if(l[t]==0)
c++;
l[t]++;
}
bool legs=false;
for(int i=0;i<10;i++)
if(l[i]>=4)
{
legs=true;
leg=i;
break;
}
if(c>3 || !legs)
cout << "Alien" << endl;
else
{
for(int i=0;i<10;i++)
if(i==leg)
continue;
else if(l[i]>=2)
{
cout << "Elephant" << endl;
return 0;
}
if(l[leg]==6)
cout << "Elephant" << endl;
else
cout << "Bear" << endl;
}
return 0;
}
| [
"kadircetinkaya.06.tr@gmail.com"
] | kadircetinkaya.06.tr@gmail.com |
a34cf153c0f1580f18bceeb93f60eceff7614efc | 6330e1c103730921b6f1ab2e4b6f68714dfaa14d | /series1_handout/fvm_scalar_1d/tests/test_numerical_flux.cpp | 6be5fc11c32f6446118d21d9e34423aefd852cd8 | [] | no_license | ochsnerd/numpde | 6e8b2d86fbb4720d29bcc36d4ced83b76c56996a | ed01111e4ca1f8987b5f7f80bd0c3630b99b9326 | refs/heads/master | 2020-07-28T17:55:41.899177 | 2019-12-08T12:19:36 | 2019-12-08T12:19:36 | 209,485,411 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,084 | cpp | #include <gtest/gtest.h>
#include <ancse/numerical_flux.hpp>
template <class NumericalFlux>
void check_consistency(const NumericalFlux &nf) {
auto model = make_dummy_model();
auto to_check = std::vector<double>{1.0, 2.0, 3.3251, -1.332};
for (auto u : to_check) {
ASSERT_DOUBLE_EQ(model.flux(u), nf(std::make_pair(u,u)));
ASSERT_DOUBLE_EQ(model.flux(u), nf(u, u));
}
}
TEST(TestCentralFlux, consistency) {
auto model = make_dummy_model();
auto central_flux = CentralFlux(model);
check_consistency(central_flux);
}
TEST(TestRusanovFlux, consistency) {
auto rf = RusanovFlux(make_dummy_model());
check_consistency(rf);
}
TEST(TestLaxFriedrichsFlux, consistency) {
auto lff = LaxFriedrichsFlux(make_dummy_model(),
make_dummy_grid(),
std::make_shared<SimulationTime>(make_dummy_simulationtime())); // shared_ptr (┛ಠ_ಠ)┛彡┻━┻
check_consistency(lff);
}
TEST(TestRoeFlux, consistency) {
auto rf = RoeFlux(make_dummy_model());
check_consistency(rf);
}
| [
"ochsnerd@student.ethz.ch"
] | ochsnerd@student.ethz.ch |
534cc647941f062c88697f6a3002e6dc493ca8c4 | ebbffe57767907f6e6fb5c74d4f0d62117f955c2 | /LAB6_P1.cpp | 50b2ba7c57ca2600e0cbc8703cf16c69263e389c | [] | no_license | SuRiTrA/PDSL-2 | c470d22c24c36b48f906043c9b666dcbe08e9a2e | 0d7b3dff1f357552b1df6b97094239c26810eb5e | refs/heads/master | 2021-05-12T12:05:19.866474 | 2018-04-27T03:58:08 | 2018-04-27T03:58:08 | 117,403,284 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,108 | cpp |
#include <iostream>
using namespace std;
//1711140
/*
Implement Binary search function. Include:
1. Function that takes in array, size of array and element to be searched. Returns the index of the array where the element is found or -1 if the element is not found.
2. Function that takes in linked list and element to be searched. Returns the index of the array where the element is found or -1 if the element is not found.
*/
class Node
{
public:
int num;
Node* next;
Node()
{
num=0;
next=NULL;
}
};
class SLL
{
public:
Node* head;
Node* tail;
int size;
SLL()
{
size=0;
head=NULL;
tail=NULL;
}
void insert(int n);
void deleten();
int countItems();
void display();
};
//1711140
//Adds a new element to the end of the linked list.
void SLL::insert(int n)
{
Node *tmp=new Node;
tmp->num=n;
tmp->next=NULL;
if(head==NULL) // Steps to perform when the list is empty.
{
head=tmp;
}
else
{
tail->next=tmp;
}
tail=tmp;
size++;
}
//1711140
//Deletes the element at the end of the list
void SLL::deleten()
{
Node* traverse = head;
//goes to the 2nd last element
int count=0;
while(count<size-2)
{
traverse = traverse->next;
count++;
}
tail = traverse;
traverse->next = NULL;
size--;
}
//1711140
//Returns the number of items in the linked list.
int SLL::countItems()
{
//using size variable
int s=size;
return s;
}
//1711140
//Displays all the elements in the linked list. Format should be followed as “1 -> 2 -> 3 -> 4 -> NULL” for a linked list holding integers in the order 1,2,3,4.
void SLL::display()
{
if(head==NULL)
cout << "\n \nNULL \n \nThe List is empty"; // Steps to perform when the list is empty.
else
{
Node *temp = head;
cout<<"\n \n";
while(temp != NULL)
{
cout << temp->num;
cout<<" --> ";
temp = temp->next;
}
cout<<"NULL \n";
}
}
class array
{
public:
int *arr;
int len;
array()
{
len=1;
arr=new int[len];
}
};
//1711140
//function to search a sorted array via binarysearch
int binarySearch(int *L,int x, int first, int last)
{
if (last >= first) //first > last)
{
int middle = (first + last) / 2;
if (x == L[middle])
return middle;
else if (x < L[middle])
return binarySearch(L, x, first, middle - 1);
else
return binarySearch(L, x, middle + 1, last);
}
return -1; // failed to find key
}
//1711140
//this function implements binaryserch of linked list through array
int binSrcLL(SLL l, int key)
{
array a;
a.len=l.countItems();
Node* n=l.head;
for(int i=0;i<a.len;i++)
{
a.arr[i]=n->num;
n=n->next;
}
int p=binarySearch(a.arr,key,0,a.len-1);
return p;
}
int main()
{
cout<<"\nEnter the number of array elements: ";
int s;
cin>>s;
array A;
A.len=s;
cout<<"\nInput the array in an ascending order: ";
for(int i=0;i<s;i++)
{
cin>>A.arr[i];
}
//sortArray(A.arr);
cout<<"\nEnter the element to be searched: ";
int key;
cin>>key;
int pos=binarySearch(A.arr, key, 0, s-1);
if(pos==-1)
{
cout<<"\nElement not found !";
}
else
{
cout<<"\nElement found at position: "<<pos+1;
}
//TEST CODE FOR LINKED LIST
SLL l1;
l1.insert(12);
l1.insert(34);
l1.insert(43);
l1.insert(51);
l1.insert(62);
l1.insert(70);
l1.insert(97);
//l1.sort()
cout<<"\n \nEXECUTING TEST CODE FOR LINKED LIST";
int pos2=binSrcLL(l1, 51);
if(pos2==-1)
{
cout<<"\nElement not found !";
}
else
{
cout<<"\nElement found at position: "<<pos2+1;
}
//Let the key be 51
return 0;
}
//1711140
| [
"noreply@github.com"
] | noreply@github.com |
c532264b7c052af65cda4b87c74b969449c74ff9 | 47ff8543c73dab22c7854d9571dfc8d5f467ee8c | /BOJ/1010/1010.cpp | b7949feaa482c96242de4760de19db0acaf42ff6 | [] | no_license | eldsg/BOJ | 4bb0c93dc60783da151e685530fa9a511df3a141 | 6bd15e36d69ce1fcf208d193d5e9067de9bb405e | refs/heads/master | 2020-04-16T02:18:55.808362 | 2017-11-28T11:02:37 | 2017-11-28T11:02:37 | 55,879,791 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | #include <iostream>
#include <string>
using namespace std;
int main(){
int testcase;
cin >> testcase;
while (testcase != 0){
int a, b,c,d;
unsigned long long int result1 = 1, result2 = 1 ,result3=1;
cin >> a >> b;
if (a == b){
cout << 1 << endl;
testcase--;
continue;
}
c = b - a;
d = b - c;
if (c > a){
while (b != c){
result1 *= b;
b--;
}
while (a != 0){
result2 *= a;
a--;
}
}
else {
while (b != a){
result1 *= b;
b--;
}
while (c != 0){
result2 *= c;
c--;
}
}
result3 = result1 / result2;
cout << result3 << endl;
testcase--;
}
} | [
"kgm0219@gmail.com"
] | kgm0219@gmail.com |
46484404f9efa9d8a9d39fa7bcc8454401838a19 | d48a833da418be56e9878379705332881e2abd02 | /emaxx/Codeforces/727/A/A.cpp | 218ccb9d817b3d8255de70c61369ad00d938225c | [] | no_license | convict-git/sport_coding | 21a5fc9e0348e44eafaefe822cb749dfa4f7e53b | ae288a9930fac74ceb63dc8cc7250c854e364056 | refs/heads/master | 2021-07-05T21:35:14.348029 | 2021-01-01T17:53:34 | 2021-01-01T17:53:34 | 215,317,175 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cpp | #pragma GCC optimize ("Ofast")
#include <bits/stdc++.h>
#define IOS ios_base::sync_with_stdio(false); cin.tie (nullptr)
#define PREC cout.precision (10); cout << fixed
template<class T> bool nax(T& a, T b){return a < b ? (a = b, 1) : 0;}
template<class T> bool nix(T& a, T b){return a > b ? (a = b, 1) : 0;}
using namespace std;
long long a, b;
const int infi = (int)1e9;
bool ok = false;
vector <long long> Path;
void dfs (long long x) {
if (x > infi) return;
if (x == b) {
Path.push_back(b);
ok = true;
return;
}
if (!ok) dfs(2*x);
if (!ok) dfs(10*x + 1);
if (ok) Path.push_back(x);
}
void solve() {
if (ok) {
printf("YES\n");
reverse(Path.begin(), Path.end());
printf("%i\n", (int)Path.size());
for (auto p : Path) printf("%lld ", p);
printf("\n");
}
else printf("NO\n");
}
int main() {
IOS; PREC;
cin >> a >> b;
dfs(a);
solve();
return EXIT_SUCCESS;
}
| [
"official.mr.convict@gmail.com"
] | official.mr.convict@gmail.com |
f433a459f75f18795e9dd02b7d5c24f32152ab06 | 068ae775a3cb50c7f1847242c1a8e35712d96d80 | /gpsd_client/src/gps_dumper.cpp | 4c2a8fc69a5f6362c3eb30111d41949da3609940 | [] | no_license | swri-robotics/gps_umd | 9a874a41d9ac4b1e7a756685f54d0eb59b22dda5 | 99130b95cda595f776cff20893fe4a7158a96f1b | refs/heads/master | 2023-07-11T14:56:55.026530 | 2023-06-14T15:20:04 | 2023-06-14T15:20:04 | 72,451,421 | 84 | 96 | null | 2023-09-06T13:03:52 | 2016-10-31T15:43:11 | C++ | UTF-8 | C++ | false | false | 521 | cpp | #include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <stdio.h>
void gpsCallback(const nav_msgs::Odometry::ConstPtr& msg)
{
// printf("Got msg!\n");
printf("%lf,%lf,0\n",msg->pose.pose.position.y,msg->pose.pose.position.x,msg->pose.pose.position.z);
//printf(" VEL:[%lf] ANG:[%lf]\n",msg->linear.x,msg->angular.z);
}
int main(int argc, char ** argv)
{
ros::init(argc, argv, "gps_dumper");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("gps_odom", 1, gpsCallback);
ros::spin();
return 0;
}
| [
"ken@tossell.net"
] | ken@tossell.net |
4e3eed8acc00f0660503b88d5a6aa192346d929a | 6e665dcd74541d40647ebb64e30aa60bc71e610c | /800/VPBX/pbx/base/AudioThread.cxx | 163f466ca2391b9ee109e40104c8712c0df30a95 | [] | no_license | jacklee032016/pbx | b27871251a6d49285eaade2d0a9ec02032c3ec62 | 554149c134e50db8ea27de6a092934a51e156eb6 | refs/heads/master | 2020-03-24T21:52:18.653518 | 2018-08-04T20:01:15 | 2018-08-04T20:01:15 | 143,054,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cxx | /*
* $Id: AudioThread.cxx,v 1.1.1.1 2006/11/30 16:26:29 lizhijie Exp $
*/
#include "global.h"
#include "cpLog.h"
#include <cassert>
#include "GatewayMgr.hxx"
#include "AudioThread.hxx"
using namespace Assist;
AudioThread::AudioThread( const Sptr <GatewayMgr> gateway )
{
myGatewayMgr = gateway;
}
AudioThread::~AudioThread()
{
}
void AudioThread::thread()
{
cpLogSetLabelThread (VThread::selfId(), "Audio Thread");
cpLog(LOG_DEBUG, "PID of Audio Thread is %d" ,getpid() );
while ( true )
{
myGatewayMgr->processAudio();
if ( isShutdown() == true)
return;
}
}
| [
"jacklee032016@gmail.com"
] | jacklee032016@gmail.com |
df886b0da44fd6edb385900034639e4da15c56e3 | b8fd41a7061702027866e09748e9c5d0a4876317 | /Week3/maze/src/CoordinateStack.cpp | 4ebed43cb3f1af58417c3c58afcde1a5dd0a588e | [] | no_license | AyaanaPS/ProgrammingMethods | 6b458410325dde470241d5b8984fce4276c281b3 | 0a8fb243dae7f61c11f0442a3d64466401e1065f | refs/heads/master | 2021-01-11T04:18:02.487805 | 2016-10-18T05:47:40 | 2016-10-18T05:47:40 | 71,212,730 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,232 | cpp | /**
* @file CoordinateStack.cpp
* @author Ellen Price <<eprice@caltech.edu>>
* @version 2.0
* @date 2014-2015
* @copyright see License section
*
* @brief Functions for stack class that stores Coordinate objects.
*
* @section License
* Copyright (c) 2014-2015 California Institute of Technology.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of the nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the California Institute of Technology.
*
*/
#include "CoordinateStack.hpp"
#define ANIMATION_DELAY (25)
/**
* @brief Initializes the stack.
*
* @param[in] app Reference to the MazeSolverApp; needed
* to render moves.
*/
#ifndef TESTSUITE
CoordinateStack::CoordinateStack(class MazeSolverApp *app)
{
this->app = app;
init();
}
#else
CoordinateStack::CoordinateStack()
{
init();
}
#endif
/**
* @brief Initializes the stack (student-implemented).
*/
void CoordinateStack::init()
{
/* TODO: Write your initialization here! */
top = NULL;
}
/**
* @brief Deinitializes the stack.
*/
CoordinateStack::~CoordinateStack()
{
deinit();
}
/**
* @brief Deinitializes the stack (student-implemented).
*/
void CoordinateStack::deinit()
{
/* TODO: Write your cleanup code here! */
while(not is_empty())
{
do_pop();
}
}
/** This function iterates through the stack and pushes
* the Coordinates to a vector.
* It then returns the Coordinates.
* This is helpful for the get path function in the Depth Solver. */
vector<Coordinate> CoordinateStack::get_stack()
{
stackitem *iter = top;
vector<Coordinate> ret;
while (iter != NULL)
{
ret.push_back(iter->c);
iter = iter->next;
}
return ret;
}
/**
* @brief Pushes an item onto the stack.
*
* @param[in] c Coordinate to push onto the stack.
*/
void CoordinateStack::push(Coordinate c)
{
/* Do the operation. */
do_push(c);
#ifndef TESTSUITE
/* Update the display. */
SDL_Delay(ANIMATION_DELAY);
this->app->OnRender();
#endif
}
/**
* @brief Do the actual push operation (student-implemented).
*
* @param[in] c Coordinate to push onto the stack.
*/
void CoordinateStack::do_push(Coordinate c)
{
/* TODO: Write your push function here! */
stackitem *pushed = new stackitem();
pushed->c = c;
pushed->next = top;
top = pushed;
}
/**
* @brief Pops an item off the stack.
*
* @return The popped Coordinate.
*/
Coordinate CoordinateStack::pop()
{
/* Do the operation. */
Coordinate c = do_pop();
#ifndef TESTSUITE
/* Update the display. */
SDL_Delay(ANIMATION_DELAY);
this->app->OnRender();
#endif
return c;
}
/**
* @brief Do the actual pop operation (student-implemented).
*
* @return The popped Coordinate.
*/
Coordinate CoordinateStack::do_pop()
{
/* TODO: Write your pop function here! */
if(is_empty() == true)
{
Coordinate error(-1, -1);
return error;
}
Coordinate c = top->c;
stackitem *temp = top;
top = top->next;
delete temp;
return c;
}
/**
* @brief Returns the top item of the stack without removing it.
*
* @return The Coordinate at the top of the stack.
*/
Coordinate CoordinateStack::peek()
{
/* TODO: Write your peek function here! */
if(is_empty() == true)
{
Coordinate error(-1, -1);
return error;
}
return top->c;
}
/**
* @brief Returns true if stack is empty, false otherwise.
*
* @return Boolean indicating whether the stack is empty.
*/
bool CoordinateStack::is_empty()
{
/* TODO: Is the stack empty??? */
if(top == NULL)
{
return true;
}
return false;
}
| [
"noreply@github.com"
] | noreply@github.com |
6060798636c37d8c9d2e39b6e9e762ef87689bb4 | 3665d78b31d27b86207f92944f7984818ec687c6 | /List-question/String/8-Longest_pallindromic_substring-63.cpp | e8e6d2a4ba0c58fd0cc059f9f83c1d0b7e70300a | [] | no_license | Stenardt-9002/CODECHEF-Datastructure-and-algo | 120b0c956e764d7fd10c2256430ce2d0a5975d46 | bca909265b9dca6d9dd93f50d68f86f71c3b6bdc | refs/heads/master | 2023-07-10T08:37:35.099195 | 2023-06-28T02:06:00 | 2023-06-28T02:06:00 | 190,029,392 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,342 | cpp | #include <bits/stdc++.h>
#include<ext/pb_ds/tree_policy.hpp>
#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds ;
typedef long long ll1d;
const int mod1 = (1e9+7);
string longestPalindrome(string S)
{
int n = S.length();
int start_indx=0,length_max=1;
vector<vector<bool>>dp1(n,vector<bool>(n,false));
for (int i1 = 0; i1 < n; i1++)
dp1[i1][i1]=true;
for (int i1 = 0; i1 < n-1; i1++)
if(S[i1]==S[i1+1])
{
dp1[i1][i1+1]=true;
if(length_max<2 )
{
start_indx = i1 ;
length_max = 2 ;
}
}
for (int len = 2; len < n; len++)
{
for (int star = 0; star < n-len; star++)
{
int j1 = star+len;
if(dp1[star+1][j1-1]&&(S[star]==S[j1]))
{
dp1[star][j1]=true ;
if(len+1>length_max)
{
length_max = len+1;
start_indx = star;
}
}
}
}
if(start_indx==INT_MAX)
return S.substr(0,1);
return S.substr(start_indx,length_max);
// code here
}
int main(int argc, char const *argv[])
{
string str = "qrqdwfca";
cout << "\nLength is: "<<longestPalindrome(str);
return 0;
}
| [
"esd17i014@iiitdm.ac.in"
] | esd17i014@iiitdm.ac.in |
d0c2b9b25d02704a48befb3e272d771ed832079f | 3a73ec62701adfd8596f1d36de19850bf202a064 | /src/source/shader/PhotonMapProjectionTextureShader.cpp | e7f1c19eb473ef34337bfa9cfd49207bb4ff88fc | [
"MIT"
] | permissive | rodrigobmg/3D-Graphics-Engine | 3df237d06019d3ddcc5faf5e6458559db32c77d2 | c8a2c98f3f9b810df18c49956e723a2df9b27a40 | refs/heads/master | 2020-06-01T20:21:53.571366 | 2018-03-23T22:00:35 | 2018-03-23T22:00:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,467 | cpp | #include "shader/PhotonMapProjectionTextureShader.h"
PhotonMapProjectionTextureShader::PhotonMapProjectionTextureShader()
{
shaderType = SHADER_TYPE_PHOTON_MAP_PROJECTION_TEXTURE;
addMain(SHADER_SOURCE_PHOTON_MAP_PROJECTION_TEXTURE_VERT, __shaderLinesVert);
include(SHADER_MATERIAL_UTILS, __shaderLinesVert);
include(SHADER_MATRIX_UTILS, __shaderLinesVert);
include(SHADER_BRDF_UTILS, __shaderLinesVert);
include(SHADER_ENVIRONMENT_MAP_UTILS, __shaderLinesVert);
addMain(SHADER_SOURCE_PHOTON_MAP_PROJECTION_TEXTURE_GEOM, __shaderLinesGeom);
include(SHADER_MATRIX_UTILS, __shaderLinesGeom);
addMain(SHADER_SOURCE_PHOTON_MAP_PROJECTION_TEXTURE_FRAG, __shaderLinesFrag);
include(SHADER_MATRIX_UTILS, __shaderLinesFrag);
include(SHADER_GEOMETRY_UTILS, __shaderLinesFrag);
include(SHADER_MATERIAL_UTILS, __shaderLinesFrag);
include(SHADER_SHADOW_MAP_UTILS, __shaderLinesFrag);
include(SHADER_LIGHT_UTILS, __shaderLinesFrag);
include(SHADER_RANDOM_UTILS, __shaderLinesFrag);
include(SHADER_BRDF_UTILS, __shaderLinesFrag);
//include(SHADER_KDTREE_UTILS, __shaderLinesFrag);
include(SHADER_PHOTON_MAP_UTILS, __shaderLinesFrag);
constructShader();
GLchar** attributes = new GLchar*[8];
attributes[0] = "position";
attributes[1] = "color";
attributes[2] = "normal";
attributes[3] = "materialIndex";
attributes[4] = "textureCoord";
attributes[5] = "basisX";
attributes[6] = "basisZ";
attributes[7] = "vertIndex";
addAttributes(attributes, 8);
linkProgram();
setPrimitiveType(GL_TRIANGLES);
}
PhotonMapProjectionTextureShader::~PhotonMapProjectionTextureShader()
{
}
void PhotonMapProjectionTextureShader::render()
{
renderFlushPrimitive();
}
PhotonMapTransmittanceProjectionTextureShader::PhotonMapTransmittanceProjectionTextureShader()
{
shaderType = SHADER_TYPE_PHOTON_MAP_TRANSMITTANCE_PROJECTION_TEXTURE;
addMain(SHADER_SOURCE_PHOTON_MAP_PROJECTION_TEXTURE_VERT, __shaderLinesVert);
include(SHADER_MATERIAL_UTILS, __shaderLinesVert);
include(SHADER_MATRIX_UTILS, __shaderLinesVert);
include(SHADER_BRDF_UTILS, __shaderLinesVert);
include(SHADER_ENVIRONMENT_MAP_UTILS, __shaderLinesVert);
addMain(SHADER_SOURCE_PHOTON_MAP_PROJECTION_TEXTURE_GEOM, __shaderLinesGeom);
include(SHADER_MATRIX_UTILS, __shaderLinesGeom);
addMain(SHADER_SOURCE_PHOTON_MAP_PROJECTION_TEXTURE_FRAG, __shaderLinesFrag);
include(SHADER_MATRIX_UTILS, __shaderLinesFrag);
include(SHADER_GEOMETRY_UTILS, __shaderLinesFrag);
include(SHADER_MATERIAL_UTILS, __shaderLinesFrag);
include(SHADER_SHADOW_MAP_UTILS, __shaderLinesFrag);
include(SHADER_LIGHT_UTILS, __shaderLinesFrag);
include(SHADER_RANDOM_UTILS, __shaderLinesFrag);
include(SHADER_BRDF_UTILS, __shaderLinesFrag);
//include(SHADER_KDTREE_UTILS, __shaderLinesFrag);
include(SHADER_PHOTON_MAP_UTILS, __shaderLinesFrag);
constructShader();
GLchar** attributes = new GLchar*[8];
attributes[0] = "position";
attributes[1] = "color";
attributes[2] = "normal";
attributes[3] = "materialIndex";
attributes[4] = "textureCoord";
attributes[5] = "basisX";
attributes[6] = "basisZ";
attributes[7] = "vertIndex";
addAttributes(attributes, 8);
linkProgram();
setPrimitiveType(GL_TRIANGLES);
}
PhotonMapTransmittanceProjectionTextureShader::~PhotonMapTransmittanceProjectionTextureShader()
{
}
void PhotonMapTransmittanceProjectionTextureShader::render()
{
renderFlushPrimitive();
}
| [
"gregjksmith@gmail.com"
] | gregjksmith@gmail.com |
7d11d657599f52dd41539d9a900d2b3549d492f4 | ab7cc19ae7fe52b533bd49d694be9358d19ef4c5 | /stdafx.cpp | 26e6c7b7676b5d49db614a8196bdfdbec0cd82e4 | [
"MIT"
] | permissive | berk-canc/CLT | 283bf764fad1652562ced6df2261e09e1fda8b23 | 8f5802e9593ba9bebb436d58fdd2d7d4dcb00220 | refs/heads/master | 2021-01-18T18:09:08.436839 | 2016-10-06T16:00:28 | 2016-10-06T16:00:28 | 70,168,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | // stdafx.cpp : source file that includes just the standard includes
// CentralLimit.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"noreply@github.com"
] | noreply@github.com |
7eff388a800a70e91a99e7d2ec73440914d01c75 | 24bc4990e9d0bef6a42a6f86dc783785b10dbd42 | /third_party/blink/renderer/core/html/fenced_frame/fence_test.cc | fedb080d1516a59ea81e063da51f9ec8dad48de1 | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] | permissive | nwjs/chromium.src | 7736ce86a9a0b810449a3b80a4af15de9ef9115d | 454f26d09b2f6204c096b47f778705eab1e3ba46 | refs/heads/nw75 | 2023-08-31T08:01:39.796085 | 2023-04-19T17:25:53 | 2023-04-19T17:25:53 | 50,512,158 | 161 | 201 | BSD-3-Clause | 2023-05-08T03:19:09 | 2016-01-27T14:17:03 | null | UTF-8 | C++ | false | false | 2,563 | cc | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/html/fenced_frame/fence.h"
#include "base/test/scoped_feature_list.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
namespace blink {
class FenceTest : private ScopedFencedFramesForTest,
private ScopedPrivateAggregationApiFledgeExtensionsForTest,
public SimTest {
public:
FenceTest()
: ScopedFencedFramesForTest(true),
ScopedPrivateAggregationApiFledgeExtensionsForTest(true) {
scoped_feature_list_.InitWithFeatures(
{blink::features::kFencedFrames,
blink::features::kPrivateAggregationApiFledgeExtensions},
/*disabled_features=*/{});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
TEST_F(FenceTest, ReportPrivateAggregationEvent) {
const KURL base_url("https://www.example.com/");
V8TestingScope scope(base_url);
Fence* fence =
MakeGarbageCollected<Fence>(*(GetDocument().GetFrame()->DomWindow()));
fence->reportPrivateAggregationEvent(scope.GetScriptState(), "event",
scope.GetExceptionState());
// We expect this to make it past all the other checks, except for the
// reporting metadata check. Since this is loaded in a vacuum and not the
// result of an ad auction, we expect it to output the reporting metadata
// error.
EXPECT_EQ(ConsoleMessages().size(), 1u);
EXPECT_EQ(ConsoleMessages().front(),
"This frame did not register reporting metadata.");
}
TEST_F(FenceTest, ReportPrivateAggregationReservedEvent) {
const KURL base_url("https://www.example.com/");
V8TestingScope scope(base_url);
Fence* fence =
MakeGarbageCollected<Fence>(*(GetDocument().GetFrame()->DomWindow()));
fence->reportPrivateAggregationEvent(scope.GetScriptState(), "reserved.event",
scope.GetExceptionState());
// There should be a "Reserved events cannot be triggered manually." console
// warning.
EXPECT_EQ(ConsoleMessages().size(), 1u);
EXPECT_EQ(ConsoleMessages().front(),
"Reserved events cannot be triggered manually.");
}
} // namespace blink
| [
"roger@nwjs.io"
] | roger@nwjs.io |
ef4cbedc6731d4e153b99195ce6a026c828ab13f | 79406addafa8d09ffdd209aa3b64d97b0f2483a8 | /src/main.cpp | 145f570a51dcd938aa7109058c325991e2e0bd1e | [
"MIT"
] | permissive | citrixrep/Pylon-Segwit | faa9e46e9ba7251a174440d83ef8215c4c1cb76b | 395e71d5be0fde8a1cf6e2b49b1ff75f5d19f75f | refs/heads/master | 2020-03-22T22:17:28.691076 | 2018-07-17T13:38:35 | 2018-07-17T13:38:35 | 140,743,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300,571 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <blockfactory.h>
#include "main.h"
#include "addrman.h"
#include "alert.h"
#include "arith_uint256.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "checkqueue.h"
#include "consensus/consensus.h"
#include "consensus/merkle.h"
#include "consensus/validation.h"
#include "hash.h"
#include "init.h"
#include "merkleblock.h"
#include "net.h"
#include "policy/policy.h"
#include "poc.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sigcache.h"
#include "script/standard.h"
#include "tinyformat.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "undo.h"
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include "validationinterface.h"
#include "wallet/wallet.h"
#include "core_io.h"
#include <sstream>
#include <atomic>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/math/distributions/poisson.hpp>
#include <boost/thread.hpp>
using namespace std;
#if defined(NDEBUG)
# error "PylonCoin cannot be compiled without assertions."
#endif
/**
* Global state
*/
CCriticalSection cs_main;
BlockMap mapBlockIndex;
CChain chainActive;
CBlockIndex *pindexBestHeader = NULL;
int64_t nTimeBestReceived = 0;
CWaitableCriticalSection csBestBlock;
CConditionVariable cvBlockChange;
int nScriptCheckThreads = 0;
bool fImporting = false;
bool fReindex = false;
bool fTxIndex = false;
bool fHavePruned = false;
bool fPruneMode = false;
bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
bool fRequireStandard = true;
bool fCheckBlockIndex = false;
bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
size_t nCoinCacheUsage = 5000 * 300;
uint64_t nPruneTarget = 0;
bool fAlerts = DEFAULT_ALERTS;
bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
/** Fees smaller than this (in satoshi) are considered zero fee (for relaying, mining and transaction creation) */
CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
CTxMemPool mempool(::minRelayTxFee);
std::map<uint256, CTransaction> mapRelay;
std::deque<std::pair<int64_t, uint256> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<uint256, CNoncePool> mapRelayNonces;
deque<pair<int64_t, uint256> > vRelayExpirationNonces;
CCriticalSection cs_mapRelayNonces;
map<uint256, CCvnPartialSignature> mapRelaySigs;
deque<pair<int64_t, uint256> > vRelayExpirationSigs;
CCriticalSection cs_mapRelaySigs;
map<uint256, CChainDataMsg> mapRelayChainData;
deque<pair<int64_t, uint256> > vRelayExpirationChainData;
CCriticalSection cs_mapRelayChainData;
map<uint256, CAdminNonce> mapRelayAdminNonces;
deque<pair<int64_t, uint256> > vRelayExpirationAdminNonces;
CCriticalSection cs_mapRelayAdminNonces;
map<uint256, CAdminPartialSignature> mapRelayAdminSigs;
deque<pair<int64_t, uint256> > vRelayExpirationAdminSigs;
CCriticalSection cs_mapRelayAdminSigs;
struct IteratorComparator
{
template<typename I>
bool operator()(const I& a, const I& b)
{
return &(*a) < &(*b);
}
};
struct COrphanTx {
// When modifying, adapt the copy of this definition in tests/DoS_tests.
CTransactionRef tx;
NodeId fromPeer;
int64_t nTimeExpire;
};
std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);
std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(cs_main);
void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
*/
static void CheckBlockIndex(const Consensus::Params& consensusParams);
/** Constant stuff for coinbase transactions we create: */
CScript COINBASE_FLAGS;
const string strMessageMagic = "Pyloncoin Signed Message:\n";
static size_t vExtraTxnForCompactIt = 0;
static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(cs_main);
// Internal stuff
namespace {
struct CBlockIndexWorkComparator
{
bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
// First sort by most total work, ...
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
// ... then by earliest time received, ...
if (pa->nSequenceId < pb->nSequenceId) return false;
if (pa->nSequenceId > pb->nSequenceId) return true;
// Use pointer address as tie breaker (should only happen with blocks
// loaded from disk, as those all have id 0).
if (pa < pb) return false;
if (pa > pb) return true;
// Identical blocks.
return false;
}
};
CBlockIndex *pindexBestInvalid;
/**
* The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
* as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
* missing the data for the block.
*/
set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
/** Number of nodes with fSyncStarted. */
int nSyncStarted = 0;
/** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
* Pruned nodes may have entries where B is missing data.
*/
multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
CCriticalSection cs_LastBlockFile;
std::vector<CBlockFileInfo> vinfoBlockFile;
int nLastBlockFile = 0;
/** Global flag to indicate we should check to see if there are
* block/undo files that should be deleted. Set on startup
* or if we allocate more file space when we're in prune mode
*/
bool fCheckForPruning = false;
/**
* Every received block is assigned a unique and increasing identifier, so we
* know which one to give priority in case of a fork.
*/
CCriticalSection cs_nBlockSequenceId;
/** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
uint32_t nBlockSequenceId = 1;
/**
* Sources of received blocks, saved to be able to send them reject
* messages or ban them when processing happens afterwards. Protected by
* cs_main.
*/
map<uint256, NodeId> mapBlockSource;
/**
* Filter for transactions that were recently rejected by
* AcceptToMemoryPool. These are not rerequested until the chain tip
* changes, at which point the entire filter is reset. Protected by
* cs_main.
*
* Without this filter we'd be re-requesting txs from each of our peers,
* increasing bandwidth consumption considerably. For instance, with 100
* peers, half of which relay a tx we don't accept, that might be a 50x
* bandwidth increase. A flooding attacker attempting to roll-over the
* filter using minimum-sized, 60byte, transactions might manage to send
* 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
* two minute window to send invs to us.
*
* Decreasing the false positive rate is fairly cheap, so we pick one in a
* million to make it highly unlikely for users to have issues with this
* filter.
*
* Memory used: 1.7MB
*/
boost::scoped_ptr<CRollingBloomFilter> recentRejects;
uint256 hashRecentRejectsChainTip;
/** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
struct QueuedBlock {
uint256 hash;
CBlockIndex* pindex; //!< Optional.
bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
};
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
/** Number of preferable block download peers. */
int nPreferredDownload = 0;
/** Dirty block index entries. */
set<CBlockIndex*> setDirtyBlockIndex;
/** Dirty block file entries. */
set<int> setDirtyFileInfo;
/** Number of peers from which we're downloading blocks. */
int nPeersWithValidatedDownloads = 0;
} // anon namespace
enum FlushStateMode {
FLUSH_STATE_NONE,
FLUSH_STATE_IF_NEEDED,
FLUSH_STATE_PERIODIC,
FLUSH_STATE_ALWAYS
};
// See definition for documentation
bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
bool IsWitnessEnabled(const CBlockIndex* pindexPrev)
{
//Always enabled
return true;
}
// Compute at which vout of the block's coinbase transaction the witness
// commitment occurs, or -1 if not found.
static int GetWitnessCommitmentIndex(const CBlock& block)
{
int commitpos = -1;
if (!block.vtx.empty()) {
for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
if (block.vtx[0]->vout[o].scriptPubKey.size() >= 38 && block.vtx[0]->vout[o].scriptPubKey[0] == OP_RETURN && block.vtx[0]->vout[o].scriptPubKey[1] == 0x24 && block.vtx[0]->vout[o].scriptPubKey[2] == 0xaa && block.vtx[0]->vout[o].scriptPubKey[3] == 0x21 && block.vtx[0]->vout[o].scriptPubKey[4] == 0xa9 && block.vtx[0]->vout[o].scriptPubKey[5] == 0xed) {
commitpos = o;
}
}
}
return commitpos;
}
//////////////////////////////////////////////////////////////////////////////
//
// Registration of network node signals.
//
namespace {
struct CBlockReject {
unsigned char chRejectCode;
string strRejectReason;
uint256 hashBlock;
};
/**
* Maintain validation-specific state about nodes, protected by cs_main, instead
* by CNode's own locks. This simplifies asynchronous operation, where
* processing of incoming data is done after the ProcessMessage call returns,
* and we're no longer holding the node's locks.
*/
struct CNodeState {
//! The peer's address
CService address;
//! Whether we have a fully established connection.
bool fCurrentlyConnected;
//! Accumulated misbehaviour score for this peer.
int nMisbehavior;
//! Whether this peer should be disconnected and banned (unless whitelisted).
bool fShouldBan;
//! String name of this peer (debugging/logging purposes).
std::string name;
//! List of asynchronously-determined block rejections to notify this peer about.
std::vector<CBlockReject> rejects;
//! The best known block we know this peer has announced.
CBlockIndex *pindexBestKnownBlock;
//! The hash of the last unknown block this peer has announced.
uint256 hashLastUnknownBlock;
//! The last full block we both have.
CBlockIndex *pindexLastCommonBlock;
//! The best header we have sent our peer.
CBlockIndex *pindexBestHeaderSent;
//! Whether we've started headers synchronization with this peer.
bool fSyncStarted;
//! Since when we're stalling block download progress (in microseconds), or 0.
int64_t nStallingSince;
list<QueuedBlock> vBlocksInFlight;
//! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
int64_t nDownloadingSince;
int nBlocksInFlight;
int nBlocksInFlightValidHeaders;
//! Whether we consider this a preferred download peer.
bool fPreferredDownload;
//! Whether this peer wants invs or headers (when possible) for block announcements.
bool fPreferHeaders;
//! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
bool fPreferHeaderAndIDs;
/**
* Whether this peer will send us cmpctblocks if we request them.
* This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
* but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
*/
bool fProvidesHeaderAndIDs;
//! Whether this peer can give us witnesses
bool fHaveWitness;
//! Whether this peer wants witnesses in cmpctblocks/blocktxns
bool fWantsCmpctWitness;
/**
* If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
* otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
*/
bool fSupportsDesiredCmpctVersion;
CNodeState() {
fCurrentlyConnected = false;
nMisbehavior = 0;
fShouldBan = false;
pindexBestKnownBlock = NULL;
hashLastUnknownBlock.SetNull();
pindexLastCommonBlock = NULL;
pindexBestHeaderSent = NULL;
fSyncStarted = false;
nStallingSince = 0;
nDownloadingSince = 0;
nBlocksInFlight = 0;
nBlocksInFlightValidHeaders = 0;
fPreferredDownload = false;
fPreferHeaders = false;
fProvidesHeaderAndIDs = false;
fHaveWitness = false;
fWantsCmpctWitness = false;
fSupportsDesiredCmpctVersion = false;
}
};
/** Map maintaining per-node state. Requires cs_main. */
map<NodeId, CNodeState> mapNodeState;
// Requires cs_main.
CNodeState *State(NodeId pnode) {
map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end())
return NULL;
return &it->second;
}
int GetHeight()
{
LOCK(cs_main);
return chainActive.Height();
}
void UpdatePreferredDownload(CNode* node, CNodeState* state)
{
nPreferredDownload -= state->fPreferredDownload;
// Whether this node should be marked as a preferred download node.
state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
nPreferredDownload += state->fPreferredDownload;
}
void InitializeNode(NodeId nodeid, const CNode *pnode) {
LOCK(cs_main);
CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
state.name = pnode->addrName;
state.address = pnode->addr;
}
void FinalizeNode(NodeId nodeid) {
LOCK(cs_main);
CNodeState *state = State(nodeid);
if (state->fSyncStarted)
nSyncStarted--;
if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
AddressCurrentlyConnected(state->address);
}
BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) {
mapBlocksInFlight.erase(entry.hash);
}
EraseOrphansFor(nodeid);
nPreferredDownload -= state->fPreferredDownload;
nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
assert(nPeersWithValidatedDownloads >= 0);
mapNodeState.erase(nodeid);
if (mapNodeState.empty()) {
// Do a consistency check after the last peer is removed.
assert(mapBlocksInFlight.empty());
assert(nPreferredDownload == 0);
assert(nPeersWithValidatedDownloads == 0);
}
}
// Requires cs_main.
// Returns a bool indicating whether we requested this block.
bool MarkBlockAsReceived(const uint256& hash) {
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end()) {
CNodeState *state = State(itInFlight->second.first);
state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
// Last validated block on the queue was received.
nPeersWithValidatedDownloads--;
}
if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
// First block on the queue was received, update the start download time for the next one
state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
}
state->vBlocksInFlight.erase(itInFlight->second.second);
state->nBlocksInFlight--;
state->nStallingSince = 0;
mapBlocksInFlight.erase(itInFlight);
return true;
}
return false;
}
// Requires cs_main.
void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
CNodeState *state = State(nodeid);
assert(state != NULL);
// Make sure it's not listed somewhere already.
MarkBlockAsReceived(hash);
QueuedBlock newentry = {hash, pindex, pindex != NULL};
list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
state->nBlocksInFlight++;
state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
if (state->nBlocksInFlight == 1) {
// We're starting a block download (batch) from this peer.
state->nDownloadingSince = GetTimeMicros();
}
if (state->nBlocksInFlightValidHeaders == 1 && pindex != NULL) {
nPeersWithValidatedDownloads++;
}
mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
}
/** Check whether the last unknown block a peer advertised is not yet known. */
void ProcessBlockAvailability(NodeId nodeid) {
CNodeState *state = State(nodeid);
assert(state != NULL);
if (!state->hashLastUnknownBlock.IsNull()) {
BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = itOld->second;
state->hashLastUnknownBlock.SetNull();
}
}
}
/** Update tracking information about which blocks a peer is assumed to have. */
void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
CNodeState *state = State(nodeid);
assert(state != NULL);
ProcessBlockAvailability(nodeid);
BlockMap::iterator it = mapBlockIndex.find(hash);
if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
// An actually better block was announced.
if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = it->second;
} else {
// An unknown block was announced; just assume that the latest one is the best one.
state->hashLastUnknownBlock = hash;
}
}
// Requires cs_main
bool CanDirectFetch(const Consensus::Params &consensusParams)
{
return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - dynParams.nBlockSpacing * 20;
}
// Requires cs_main
bool PeerHasHeader(CNodeState *state, CBlockIndex *pindex)
{
if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
return true;
if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
return true;
return false;
}
/** Find the last common ancestor two blocks have.
* Both pa and pb must be non-NULL. */
CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
if (pa->nHeight > pb->nHeight) {
pa = pa->GetAncestor(pb->nHeight);
} else if (pb->nHeight > pa->nHeight) {
pb = pb->GetAncestor(pa->nHeight);
}
while (pa != pb && pa && pb) {
pa = pa->pprev;
pb = pb->pprev;
}
// Eventually all chain branches meet at the genesis block.
assert(pa == pb);
return pa;
}
/** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
* at most count entries. */
void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
if (count == 0)
return;
vBlocks.reserve(vBlocks.size() + count);
CNodeState *state = State(nodeid);
assert(state != NULL);
// Make sure pindexBestKnownBlock is up to date, we'll need it.
ProcessBlockAvailability(nodeid);
if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
// This peer has nothing interesting.
return;
}
if (state->pindexLastCommonBlock == NULL) {
// Bootstrap quickly by guessing a parent of our best tip is the forking point.
// Guessing wrong in either direction is not a problem.
state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
}
// If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
// of its current tip anymore. Go back enough to fix that.
state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
return;
std::vector<CBlockIndex*> vToFetch;
CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
// Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
// linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
// download that next block if the window were 1 larger.
int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
NodeId waitingfor = -1;
while (pindexWalk->nHeight < nMaxHeight) {
// Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
// pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
// as iterating over ~100 CBlockIndex* entries anyway.
int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
vToFetch.resize(nToFetch);
pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
vToFetch[nToFetch - 1] = pindexWalk;
for (unsigned int i = nToFetch - 1; i > 0; i--) {
vToFetch[i - 1] = vToFetch[i]->pprev;
}
// Iterate over those blocks in vToFetch (in forward direction), adding the ones that
// are not yet downloaded and not in flight to vBlocks. In the mean time, update
// pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
// already part of our chain (and therefore don't need it even if pruned).
BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
if (!pindex->IsValid(BLOCK_VALID_TREE)) {
// We consider the chain that this peer is on invalid.
return;
}
if ((pindex->nStatus & BLOCK_HAVE_DATA) || chainActive.Contains(pindex)) {
if (pindex->nChainTx)
state->pindexLastCommonBlock = pindex;
} else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
// The block is not already downloaded, and not yet in flight.
if (pindex->nHeight > nWindowEnd) {
// We reached the end of the window.
if (vBlocks.size() == 0 && waitingfor != nodeid) {
// We aren't able to fetch anything, but we would be if the download window was one larger.
nodeStaller = waitingfor;
}
return;
}
vBlocks.push_back(pindex);
if (vBlocks.size() == count) {
return;
}
} else if (waitingfor == -1) {
// This is the first already-in-flight block.
waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
}
}
}
}
} // anon namespace
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
LOCK(cs_main);
CNodeState *state = State(nodeid);
if (state == NULL)
return false;
stats.nMisbehavior = state->nMisbehavior;
stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
if (queue.pindex)
stats.vHeightInFlight.push_back(queue.pindex->nHeight);
}
return true;
}
void RegisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.connect(&GetHeight);
nodeSignals.ProcessMessages.connect(&ProcessMessages);
nodeSignals.SendMessages.connect(&SendMessages);
nodeSignals.InitializeNode.connect(&InitializeNode);
nodeSignals.FinalizeNode.connect(&FinalizeNode);
}
void UnregisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.disconnect(&GetHeight);
nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
nodeSignals.SendMessages.disconnect(&SendMessages);
nodeSignals.InitializeNode.disconnect(&InitializeNode);
nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
}
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, locator.vHave) {
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (chain.Contains(pindex))
return pindex;
}
}
return chain.Genesis();
}
CCoinsViewCache *pcoinsTip = NULL;
CBlockTreeDB *pblocktree = NULL;
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
void AddToCompactExtraTransactions(const CTransactionRef& tx)
{
size_t max_extra_txn = GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
if (max_extra_txn <= 0)
return;
if (!vExtraTxnForCompact.size())
vExtraTxnForCompact.resize(max_extra_txn);
vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
}
bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
const uint256& hash = tx->GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 100 orphans, each of which is at most 99,999 bytes big is
// at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
unsigned int sz = GetTransactionWeight(*tx);
if (sz >= MAX_STANDARD_TX_WEIGHT)
{
LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
return false;
}
auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
assert(ret.second);
BOOST_FOREACH(const CTxIn& txin, tx->vin) {
mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
}
AddToCompactExtraTransactions(tx);
LogPrint("mempool", "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
return true;
}
int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
if (it == mapOrphanTransactions.end())
return 0;
BOOST_FOREACH(const CTxIn& txin, it->second.tx->vin)
{
auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
if (itPrev == mapOrphanTransactionsByPrev.end())
continue;
itPrev->second.erase(it);
if (itPrev->second.empty())
mapOrphanTransactionsByPrev.erase(itPrev);
}
mapOrphanTransactions.erase(it);
return 1;
}
void EraseOrphansFor(NodeId peer)
{
int nErased = 0;
std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
while (iter != mapOrphanTransactions.end())
{
std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
if (maybeErase->second.fromPeer == peer)
{
nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
}
}
if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer=%d\n", nErased, peer);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
{
if (tx.nLockTime == 0)
return true;
if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
if (!txin.IsFinal())
return false;
return true;
}
bool CheckFinalTx(const CTransaction &tx, int flags)
{
AssertLockHeld(cs_main);
// By convention a negative value for flags indicates that the
// current network-enforced consensus rules should be used. In
// a future soft-fork scenario that would mean checking which
// rules would be enforced for the next block and setting the
// appropriate flags. At the present time no soft-forks are
// scheduled, so no flags are set.
flags = std::max(flags, 0);
// CheckFinalTx() uses chainActive.Height()+1 to evaluate
// nLockTime because when IsFinalTx() is called within
// CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a
// transaction can be part of the *next* block, we need to call
// IsFinalTx() with one more than chainActive.Height().
const int nBlockHeight = chainActive.Height() + 1;
// BIP113 will require that time-locked transactions have nLockTime set to
// less than the median time of the previous block they're contained in.
// When the next block is created its previous block will be the current
// chain tip, so we use that to calculate the median time passed to
// IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
? chainActive.Tip()->GetMedianTimePast()
: GetAdjustedTime();
return IsFinalTx(tx, nBlockHeight, nBlockTime);
}
unsigned int GetLegacySigOpCount(const CTransaction& tx)
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
{
if (tx.IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
}
return nSigOps;
}
int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)
{
int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
if (tx.IsCoinBase())
return nSigOps;
if (flags & SCRIPT_VERIFY_P2SH) {
nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
}
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
}
return nSigOps;
}
bool CheckTransaction(const CTransaction& tx, CValidationState &state)
{
// Basic checks that don't depend on any context
if (tx.vin.empty())
return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
if (tx.vout.empty())
return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
// Size limits
if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > dynParams.nMaxBlockSize)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
// Check for negative or overflow output values
CAmount nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
if (txout.nValue < 0)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
if (txout.nValue > MAX_MONEY)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (vInOutPoints.count(txin.prevout))
return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
vInOutPoints.insert(txin.prevout);
}
if (tx.IsCoinBase())
{
if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
}
else
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
if (txin.prevout.IsNull())
return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
}
return true;
}
void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
int expired = pool.Expire(GetTime() - age);
if (expired != 0)
LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
std::vector<uint256> vNoSpendsRemaining;
pool.TrimToSize(limit, &vNoSpendsRemaining);
BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
pcoinsTip->Uncache(removed);
}
/** Convert CValidationState to a human-readable message for logging */
std::string FormatStateMessage(const CValidationState &state)
{
return strprintf("%s%s (code %i)",
state.GetRejectReason(),
state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
state.GetRejectCode());
}
static bool IsCurrentForFeeEstimation()
{
AssertLockHeld(cs_main);
if (IsInitialBlockDownload())
return false;
if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
return false;
if (chainActive.Height() < pindexBestHeader->nHeight - 1)
return false;
return true;
}
bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<uint256>& vHashTxnToUncache)
{
const CTransaction& tx = *ptx;
const uint256 hash = tx.GetHash();
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
if (!CheckTransaction(tx, state))
return false; // state filled in by CheckTransaction
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return state.DoS(100, false, REJECT_INVALID, "coinbase");
// Reject transactions with witness before segregated witness activates (override with -prematurewitness)
bool witnessEnabled = IsWitnessEnabled(chainActive.Tip());
if (!GetBoolArg("-prematurewitness",false) && tx.HasWitness() && !witnessEnabled) {
return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
}
// Rather not work on nonstandard transactions (unless -testnet/-regtest)
std::string reason;
if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
return state.DoS(0, false, REJECT_NONSTANDARD, reason);
// Only accept nLockTime-using transactions that can be mined in the next
// block; we don't want our mempool filled up with transactions that can't
// be mined yet.
if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
// is it already in the memory pool?
if (pool.exists(hash))
return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
// Check for conflicts with in-memory transactions
std::set<uint256> setConflicts;
{
LOCK(pool.cs); // protect pool.mapNextTx
BOOST_FOREACH(const CTxIn &txin, tx.vin)
{
auto itConflicting = pool.mapNextTx.find(txin.prevout);
if (itConflicting != pool.mapNextTx.end())
{
const CTransaction *ptxConflicting = itConflicting->second;
if (!setConflicts.count(ptxConflicting->GetHash()))
{
// Allow opt-out of transaction replacement by setting
// nSequence >= maxint-1 on all inputs.
//
// maxint-1 is picked to still allow use of nLockTime by
// non-replaceable transactions. All inputs rather than just one
// is for the sake of multi-party protocols, where we don't
// want a single party to be able to disable replacement.
//
// The opt-out ignores descendants as anyone relying on
// first-seen mempool behavior should be checking all
// unconfirmed ancestors anyway; doing otherwise is hopelessly
// insecure.
bool fReplacementOptOut = true;
if (fEnableReplacement)
{
BOOST_FOREACH(const CTxIn &_txin, ptxConflicting->vin)
{
if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
{
fReplacementOptOut = false;
break;
}
}
}
if (fReplacementOptOut)
return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
setConflicts.insert(ptxConflicting->GetHash());
}
}
}
}
{
CCoinsView dummy;
CCoinsViewCache view(&dummy);
CAmount nValueIn = 0;
LockPoints lp;
{
LOCK(pool.cs);
CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
view.SetBackend(viewMemPool);
// do we already have it?
bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash);
if (view.HaveCoins(hash)) {
if (!fHadTxInCache)
vHashTxnToUncache.push_back(hash);
return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
}
// do all inputs exist?
// Note that this does not check for the presence of actual outputs (see the next check for that),
// and only helps with filling in pfMissingInputs (to determine missing vs spent).
BOOST_FOREACH(const CTxIn txin, tx.vin) {
if (!pcoinsTip->HaveCoinsInCache(txin.prevout.hash))
vHashTxnToUncache.push_back(txin.prevout.hash);
if (!view.HaveCoins(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
}
}
// are the actual inputs available?
if (!view.HaveInputs(tx))
return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
// Bring the best block into scope
view.GetBestBlock();
nValueIn = view.GetValueIn(tx);
// we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
view.SetBackend(dummy);
// Only accept BIP68 sequence locked transactions that can be mined in the next
// block; we don't want our mempool filled up with transactions that can't
// be mined yet.
// Must keep pool.cs for this unless we change CheckSequenceLocks to take a
// CoinsViewCache instead of create its own
if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
}
// Check for non-standard pay-to-script-hash in inputs
if (fRequireStandard && !AreInputsStandard(tx, view))
return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
// Check for non-standard witness in P2WSH
if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
CAmount nValueOut = tx.GetValueOut();
CAmount nFees = nValueIn-nValueOut;
// nModifiedFees includes any fee deltas from PrioritiseTransaction
CAmount nModifiedFees = nFees;
double nPriorityDummy = 0;
pool.ApplyDeltas(hash, nPriorityDummy, nModifiedFees);
CAmount inChainInputValue;
double dPriority = view.GetPriority(tx, chainActive.Height(), inChainInputValue);
// Keep track of transactions that spend a coinbase, which we re-scan
// during reorgs to ensure COINBASE_MATURITY is still met.
bool fSpendsCoinbase = false;
BOOST_FOREACH(const CTxIn &txin, tx.vin) {
const CCoins *coins = view.AccessCoins(txin.prevout.hash);
if (coins->IsCoinBase()) {
fSpendsCoinbase = true;
break;
}
}
CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, dPriority, chainActive.Height(),
inChainInputValue, fSpendsCoinbase, nSigOpsCost, lp);
unsigned int nSize = entry.GetTxSize();
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
strprintf("%d", nSigOpsCost));
CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
} else if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY) && nModifiedFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(entry.GetPriority(chainActive.Height() + 1))) {
// Require that free transactions have sufficient priority to be mined in the next block.
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
}
// Continuously rate-limit free (really, very-low-fee) transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize))
{
static CCriticalSection csFreeLimiter;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
LOCK(csFreeLimiter);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount + nSize >= GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY) * 10 * 1000)
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
if (nAbsurdFee && nFees > nAbsurdFee)
return state.Invalid(false,
REJECT_HIGHFEE, "absurdly-high-fee",
strprintf("%d > %d", nFees, nAbsurdFee));
// Calculate in-mempool ancestors, up to a limit.
CTxMemPool::setEntries setAncestors;
size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
std::string errString;
if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
}
// A transaction that spends outputs that would be replaced by it is invalid. Now
// that we have the set of all ancestors we can detect this
// pathological case by making sure setConflicts and setAncestors don't
// intersect.
BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
{
const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
if (setConflicts.count(hashAncestor))
{
return state.DoS(10, false,
REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
strprintf("%s spends conflicting transaction %s",
hash.ToString(),
hashAncestor.ToString()));
}
}
// Check if it's economically rational to mine this transaction rather
// than the ones it replaces.
CAmount nConflictingFees = 0;
size_t nConflictingSize = 0;
uint64_t nConflictingCount = 0;
CTxMemPool::setEntries allConflicting;
// If we don't hold the lock allConflicting might be incomplete; the
// subsequent RemoveStaged() and addUnchecked() calls don't guarantee
// mempool consistency for us.
LOCK(pool.cs);
const bool fReplacementTransaction = setConflicts.size();
if (fReplacementTransaction)
{
CFeeRate newFeeRate(nModifiedFees, nSize);
std::set<uint256> setConflictsParents;
const int maxDescendantsToVisit = 100;
CTxMemPool::setEntries setIterConflicting;
BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
{
CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
if (mi == pool.mapTx.end())
continue;
// Save these to avoid repeated lookups
setIterConflicting.insert(mi);
// Don't allow the replacement to reduce the feerate of the
// mempool.
//
// We usually don't want to accept replacements with lower
// feerates than what they replaced as that would lower the
// feerate of the next block. Requiring that the feerate always
// be increased is also an easy-to-reason about way to prevent
// DoS attacks via replacements.
//
// The mining code doesn't (currently) take children into
// account (CPFP) so we only consider the feerates of
// transactions being directly replaced, not their indirect
// descendants. While that does mean high feerate children are
// ignored when deciding whether or not to replace, we do
// require the replacement to pay more overall fees too,
// mitigating most cases.
CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
if (newFeeRate <= oldFeeRate)
{
return state.DoS(0, false,
REJECT_INSUFFICIENTFEE, "insufficient fee", false,
strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
hash.ToString(),
newFeeRate.ToString(),
oldFeeRate.ToString()));
}
BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
{
setConflictsParents.insert(txin.prevout.hash);
}
nConflictingCount += mi->GetCountWithDescendants();
}
// This potentially overestimates the number of actual descendants
// but we just want to be conservative to avoid doing too much
// work.
if (nConflictingCount <= maxDescendantsToVisit) {
// If not too many to replace, then calculate the set of
// transactions that would have to be evicted
BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
pool.CalculateDescendants(it, allConflicting);
}
BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
nConflictingFees += it->GetModifiedFee();
nConflictingSize += it->GetTxSize();
}
} else {
return state.DoS(0, false,
REJECT_NONSTANDARD, "too many potential replacements", false,
strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
hash.ToString(),
nConflictingCount,
maxDescendantsToVisit));
}
for (unsigned int j = 0; j < tx.vin.size(); j++)
{
// We don't want to accept replacements that require low
// feerate junk to be mined first. Ideally we'd keep track of
// the ancestor feerates and make the decision based on that,
// but for now requiring all new inputs to be confirmed works.
if (!setConflictsParents.count(tx.vin[j].prevout.hash))
{
// Rather than check the UTXO set - potentially expensive -
// it's cheaper to just check if the new input refers to a
// tx that's in the mempool.
if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
return state.DoS(0, false,
REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
strprintf("replacement %s adds unconfirmed input, idx %d",
hash.ToString(), j));
}
}
// The replacement must pay greater fees than the transactions it
// replaces - if we did the bandwidth used by those conflicting
// transactions would not be paid for.
if (nModifiedFees < nConflictingFees)
{
return state.DoS(0, false,
REJECT_INSUFFICIENTFEE, "insufficient fee", false,
strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
}
// Finally in addition to paying more fees than the conflicts the
// new transaction must pay for its own bandwidth.
CAmount nDeltaFees = nModifiedFees - nConflictingFees;
if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
{
return state.DoS(0, false,
REJECT_INSUFFICIENTFEE, "insufficient fee", false,
strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
hash.ToString(),
FormatMoney(nDeltaFees),
FormatMoney(::incrementalRelayFee.GetFee(nSize))));
}
}
unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
if (!Params().RequireStandard()) {
scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
PrecomputedTransactionData txdata(tx);
if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, txdata)) {
// SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
// need to turn both off, and compare against just turning off CLEANSTACK
// to see if the failure is specifically due to witness validation.
CValidationState stateDummy; // Want reported failures to be from first CheckInputs
if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, txdata) &&
!CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, txdata)) {
// Only the witness is missing, so the transaction itself may be fine.
state.SetCorruptionPossible();
}
return false; // state filled in by CheckInputs
}
// Check again against just the consensus-critical mandatory script
// verification flags, in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks, however allowing such transactions into the mempool
// can be exploited as a DoS attack.
if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata))
{
return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
__func__, hash.ToString(), FormatStateMessage(state));
}
// Remove conflicting transactions from the mempool
BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
{
LogPrint("mempool", "replacing tx %s with %s for %s CREA additional fees, %d delta bytes\n",
it->GetTx().GetHash().ToString(),
hash.ToString(),
FormatMoney(nModifiedFees - nConflictingFees),
(int)nSize - (int)nConflictingSize);
if (plTxnReplaced)
plTxnReplaced->push_back(it->GetSharedTx());
}
pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
// This transaction should only count for fee estimation if it isn't a
// BIP 125 replacement transaction (may not be widely supported), the
// node is not behind, and the transaction is not dependent on any other
// transactions in the mempool.
bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
// Store transaction in memory
pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
// trim mempool and check if tx was trimmed
if (!fOverrideMempoolLimit) {
LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
if (!pool.exists(hash))
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
}
}
GetMainSignals().SyncTransaction(tx, NULL, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK);
return true;
}
bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
{
std::vector<uint256> vHashTxToUncache;
bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, vHashTxToUncache);
if (!res) {
BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache)
pcoinsTip->Uncache(hashTx);
}
// After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
CValidationState stateDummy;
FlushStateToDisk(stateDummy, FLUSH_STATE_PERIODIC);
return res;
}
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
{
return AcceptToMemoryPoolWithTime(pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
}
/** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
{
CBlockIndex *pindexSlow = NULL;
LOCK(cs_main);
CTransactionRef ptx = mempool.get(hash);
if (ptx)
{
txOut = ptx;
return true;
}
if (fTxIndex) {
CDiskTxPos postx;
if (pblocktree->ReadTxIndex(hash, postx)) {
CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
if (file.IsNull())
return error("%s: OpenBlockFile failed", __func__);
CBlockHeader header;
try {
file >> header;
fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
file >> txOut;
} catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
hashBlock = header.GetHash();
if (txOut->GetHash() != hash)
return error("%s: txid mismatch", __func__);
return true;
}
}
if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
int nHeight = -1;
{
const CCoinsViewCache& view = *pcoinsTip;
const CCoins* coins = view.AccessCoins(hash);
if (coins)
nHeight = coins->nHeight;
}
if (nHeight > 0)
pindexSlow = chainActive[nHeight];
}
if (pindexSlow) {
CBlock block;
if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
for (const auto& tx : block.vtx) {
if (tx->GetHash() == hash) {
txOut = tx;
hashBlock = pindexSlow->GetBlockHash();
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
{
// Open history file to append
CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("WriteBlockToDisk: OpenBlockFile failed");
// Write index header
unsigned int nSize = GetSerializeSize(fileout, block);
fileout << FLATDATA(messageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("WriteBlockToDisk: ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << block;
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
{
block.SetNull();
// Open history file to read
CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
// Read block
try {
filein >> block;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
}
// Check the header
//TODO: put CVN check here
// if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
// return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
return false;
if (block.GetHash() != pindex->GetBlockHash())
return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
pindex->ToString(), pindex->GetBlockPos().ToString());
return true;
}
CAmount GetBlockSubsidy(int nHeight)
{
CAmount nSubsidy = 0 * COIN;
// RAII cleanup
CURL *curl;
CURLcode responseCode;
std::string readBuffer;
curl = curl_easy_init();
char *url = "https://api.pylon-network.org/reward?nHeight=";
char *params = (char*)malloc(300* sizeof(char));
char *blocks = (char*)nHeight;
//Setup Params. Use %s for text, %d for integer, %f for decimal, %x for hex
sprintf(params, "param1=%s¶m2=%s", "valueParam1", "valueParam2");
curl_easy_setopt(curl, CURLOPT_URL, strcat(url,blocks));
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
//Setup headers
struct curl_slist *chunk = NULL;
chunk = curl_slist_append(chunk, "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, params);
//Calling
responseCode = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (responseCode == CURLE_OK) {
int energy = std::stoi(readBuffer);
nSubsidy = energy * COIN;
}
return nSubsidy;
}
bool IsInitialBlockDownload()
{
const CChainParams& chainParams = Params();
// Once this function has returned false, it must remain false.
static std::atomic<bool> latchToFalse{false};
// Optimization: pre-test latch before taking the lock.
if (latchToFalse.load(std::memory_order_relaxed))
return false;
LOCK(cs_main);
if (latchToFalse.load(std::memory_order_relaxed))
return false;
if (chainActive.Tip() == NULL)
return true;
if (fImporting || fReindex)
return true;
if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
return true;
if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
return true;
LogPrintf("Initial blockchain download completed.\n");
latchToFalse.store(true, std::memory_order_relaxed);
return false;
}
arith_uint256 GetBlockProof(const CBlockIndex& block)
{
uint32_t nSigs = GetNumChainSigs(&block);
arith_uint256 bnSignatures(nSigs);
return bnSignatures;
}
int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip)
{
arith_uint256 r;
int sign = 1;
if (to.nChainWork > from.nChainWork) {
r = to.nChainWork - from.nChainWork;
} else {
r = from.nChainWork - to.nChainWork;
sign = -1;
}
r = r * arith_uint256(dynParams.nBlockSpacing) / GetBlockProof(tip);
if (r.bits() > 63) {
return sign * std::numeric_limits<int64_t>::max();
}
return sign * r.GetLow64();
}
bool fLargeWorkForkFound = false;
bool fLargeWorkInvalidChainFound = false;
CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
void CheckForkWarningConditions()
{
AssertLockHeld(cs_main);
// Before we get past initial download, we cannot reliably alert about forks
// (we assume we don't get stuck on a fork before the last checkpoint)
if (IsInitialBlockDownload())
return;
// If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
// of our head, drop it
if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
pindexBestForkTip = NULL;
if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
{
if (!fLargeWorkForkFound && pindexBestForkBase)
{
std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
pindexBestForkBase->phashBlock->ToString() + std::string("'");
CAlert::Notify(warning, true);
}
if (pindexBestForkTip && pindexBestForkBase)
{
LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__,
pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
fLargeWorkForkFound = true;
}
else
{
LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
fLargeWorkInvalidChainFound = true;
}
}
else
{
fLargeWorkForkFound = false;
fLargeWorkInvalidChainFound = false;
}
}
void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
{
AssertLockHeld(cs_main);
// If we are on a fork that is sufficiently large, set a warning flag
CBlockIndex* pfork = pindexNewForkTip;
CBlockIndex* plonger = chainActive.Tip();
while (pfork && pfork != plonger)
{
while (plonger && plonger->nHeight > pfork->nHeight)
plonger = plonger->pprev;
if (pfork == plonger)
break;
pfork = pfork->pprev;
}
// We define a condition where we should warn the user about as a fork of at least 7 blocks
// with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
// We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
// hash rate operating on the fork.
// or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
// We define it this way because it allows us to only store the highest fork tip (+ base) which meets
// the 7-block condition and from this always have the most-likely-to-cause-warning fork
if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
chainActive.Height() - pindexNewForkTip->nHeight < 72)
{
pindexBestForkTip = pindexNewForkTip;
pindexBestForkBase = pfork;
}
CheckForkWarningConditions();
}
// Requires cs_main.
void Misbehaving(NodeId pnode, int howmuch)
{
if (howmuch == 0)
return;
CNodeState *state = State(pnode);
if (state == NULL)
return;
state->nMisbehavior += howmuch;
int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
{
LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
state->fShouldBan = true;
} else
LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
pindexBestInvalid = pindexNew;
LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
pindexNew->GetBlockTime()));
CBlockIndex *tip = chainActive.Tip();
assert (tip);
LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
CheckForkWarningConditions();
}
void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
int nDoS = 0;
if (state.IsInvalid(nDoS)) {
std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
if (it != mapBlockSource.end() && State(it->second)) {
assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
State(it->second)->rejects.push_back(reject);
if (nDoS > 0)
Misbehaving(it->second, nDoS);
}
}
if (!state.CorruptionPossible()) {
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
InvalidChainFound(pindex);
}
}
void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
{
// mark inputs spent
if (!tx.IsCoinBase()) {
txundo.vprevout.reserve(tx.vin.size());
BOOST_FOREACH(const CTxIn &txin, tx.vin) {
CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
unsigned nPos = txin.prevout.n;
if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
assert(false);
// mark an outpoint spent, and construct undo information
txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
coins->Spend(nPos);
if (coins->vout.size() == 0) {
CTxInUndo& undo = txundo.vprevout.back();
undo.nHeight = coins->nHeight;
undo.fCoinBase = coins->fCoinBase;
undo.nVersion = coins->nVersion;
}
}
}
// add outputs
inputs.ModifyNewCoins(tx.GetHash(), tx.IsCoinBase())->FromTx(tx, nHeight);
}
void UpdateCoins(const CTransaction& tx, CCoinsViewCache &inputs, int nHeight)
{
CTxUndo txundo;
UpdateCoins(tx, inputs, txundo, nHeight);
}
bool CScriptCheck::operator()() {
const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
if (!VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error)) {
return false;
}
return true;
}
int GetSpendHeight(const CCoinsViewCache& inputs)
{
LOCK(cs_main);
CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
return pindexPrev->nHeight + 1;
}
namespace Consensus {
bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
{
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!inputs.HaveInputs(tx))
return state.Invalid(false, 0, "", "Inputs unavailable");
CAmount nValueIn = 0;
CAmount nFees = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins *coins = inputs.AccessCoins(prevout.hash);
assert(coins);
// If prev is coinbase, check that it's matured
if (coins->IsCoinBase()) {
if (nSpendHeight - coins->nHeight < (int)COINBASE_MATURITY)
return state.Invalid(false,
REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
}
// Check for negative or overflow input values
nValueIn += coins->vout[prevout.n].nValue;
if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
}
if (nValueIn < tx.GetValueOut())
return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
// Tally transaction fees
CAmount nTxFee = nValueIn - tx.GetValueOut();
if (nTxFee < 0)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
nFees += nTxFee;
if (!MoneyRange(nFees))
return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
return true;
}
}// namespace Consensus
bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
{
if (!tx.IsCoinBase())
{
if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
return false;
if (pvChecks)
pvChecks->reserve(tx.vin.size());
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
// Skip script verification when connecting blocks under the
// assumedvalid block. Assuming the assumedvalid block is valid this
// is safe because block merkle hashes are still computed and checked,
// Of course, if an assumed valid block is invalid due to false scriptSigs
// this optimization would allow an invalid chain to be accepted.
if (fScriptChecks) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins* coins = inputs.AccessCoins(prevout.hash);
assert(coins);
// Verify signature
CScriptCheck check(*coins, tx, i, flags, cacheStore, &txdata);
if (pvChecks) {
pvChecks->push_back(CScriptCheck());
check.swap(pvChecks->back());
} else if (!check()) {
if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
// Check whether the failure was caused by a
// non-mandatory script verification check, such as
// non-standard DER encodings or non-null dummy
// arguments; if so, don't trigger DoS protection to
// avoid splitting the network between upgraded and
// non-upgraded nodes.
CScriptCheck check2(*coins, tx, i,
flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
if (check2())
return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
}
// Failures of other flags indicate a transaction that is
// invalid in new blocks, e.g. a invalid P2SH. We DoS ban
// such nodes as they are not following the protocol. That
// said during an upgrade careful thought should be taken
// as to the correct behavior - we may want to continue
// peering with non-upgraded nodes even after soft-fork
// super-majority signaling has occurred.
return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
}
}
}
}
return true;
}
namespace {
bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
{
// Open history file to append
CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s: OpenUndoFile failed", __func__);
// Write index header
unsigned int nSize = GetSerializeSize(fileout, blockundo);
fileout << FLATDATA(messageStart) << nSize;
// Write undo data
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("%s: ftell failed", __func__);
pos.nPos = (unsigned int)fileOutPos;
fileout << blockundo;
// calculate & write checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << blockundo;
fileout << hasher.GetHash();
return true;
}
bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
{
// Open history file to read
CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s: OpenBlockFile failed", __func__);
// Read block
uint256 hashChecksum;
try {
filein >> blockundo;
filein >> hashChecksum;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
// Verify checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << blockundo;
if (hashChecksum != hasher.GetHash())
return error("%s: Checksum mismatch", __func__);
return true;
}
/** Abort with a message */
bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
{
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(
userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
}
bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
{
AbortNode(strMessage, userMessage);
return state.Error(strMessage);
}
} // anon namespace
/**
* Apply the undo operation of a CTxInUndo to the given chain state.
* @param undo The undo object.
* @param view The coins view to which to apply the changes.
* @param out The out point that corresponds to the tx input.
* @return True on success.
*/
static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
{
bool fClean = true;
CCoinsModifier coins = view.ModifyCoins(out.hash);
if (undo.nHeight != 0) {
// undo data contains height: this is the last output of the prevout tx being spent
if (!coins->IsPruned())
fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
coins->Clear();
coins->fCoinBase = undo.fCoinBase;
coins->nHeight = undo.nHeight;
coins->nVersion = undo.nVersion;
} else {
if (coins->IsPruned())
fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
}
if (coins->IsAvailable(out.n))
fClean = fClean && error("%s: undo data overwriting existing output", __func__);
if (coins->vout.size() < out.n+1)
coins->vout.resize(out.n+1);
coins->vout[out.n] = undo.txout;
return fClean;
}
bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
{
assert(pindex->GetBlockHash() == view.GetBestBlock());
if (pfClean)
*pfClean = false;
bool fClean = true;
CBlockUndo blockUndo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (pos.IsNull())
return error("DisconnectBlock(): no undo data available");
if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
return error("DisconnectBlock(): failure reading undo data");
if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
return error("DisconnectBlock(): block and undo data inconsistent");
// undo transactions in reverse order
for (int i = block.vtx.size() - 1; i >= 0; i--) {
const CTransaction &tx = *(block.vtx[i]);
uint256 hash = tx.GetHash();
// Check that all outputs are available and match the outputs in the block itself
// exactly.
{
CCoinsModifier outs = view.ModifyCoins(hash);
outs->ClearUnspendable();
CCoins outsBlock(tx, pindex->nHeight);
// The CCoins serialization does not serialize negative numbers.
// No network rules currently depend on the version here, so an inconsistency is harmless
// but it must be corrected before txout nversion ever influences a network rule.
if (outsBlock.nVersion < 0)
outs->nVersion = outsBlock.nVersion;
if (*outs != outsBlock)
fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
// remove outputs
outs->Clear();
}
// restore inputs
if (i > 0) { // not coinbases
const CTxUndo &txundo = blockUndo.vtxundo[i-1];
if (txundo.vprevout.size() != tx.vin.size())
return error("DisconnectBlock(): transaction and undo data inconsistent");
for (unsigned int j = tx.vin.size(); j-- > 0;) {
const COutPoint &out = tx.vin[j].prevout;
const CTxInUndo &undo = txundo.vprevout[j];
if (!ApplyTxInUndo(undo, view, out))
fClean = false;
}
}
}
// move best block pointer to prevout block
view.SetBestBlock(pindex->pprev->GetBlockHash());
if (pfClean) {
*pfClean = fClean;
return true;
}
return fClean;
}
void static FlushBlockFile(bool fFinalize = false)
{
LOCK(cs_LastBlockFile);
CDiskBlockPos posOld(nLastBlockFile, 0);
FILE *fileOld = OpenBlockFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
FileCommit(fileOld);
fclose(fileOld);
}
fileOld = OpenUndoFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
FileCommit(fileOld);
fclose(fileOld);
}
}
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
void ThreadScriptCheck() {
RenameThread("pyloncoin-scriptch");
scriptcheckqueue.Thread();
}
static int64_t nTimeCheck = 0;
static int64_t nTimeForks = 0;
static int64_t nTimeVerify = 0;
static int64_t nTimeConnect = 0;
static int64_t nTimeIndex = 0;
static int64_t nTimeCallbacks = 0;
static int64_t nTimeTotal = 0;
bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
{
const CChainParams& chainparams = Params();
AssertLockHeld(cs_main);
int64_t nTimeStart = GetTimeMicros();
// Check it again in case a previous version let a bad block in
if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
return false;
// verify that the view's current state corresponds to the previous block
uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
assert(hashPrevBlock == view.GetBestBlock());
bool fScriptChecks = true;
if (fCheckpointsEnabled) {
CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
// This block is an ancestor of a checkpoint: disable script checks
fScriptChecks = false;
}
}
int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
if (block.HasTx()) {
for (const auto& tx : block.vtx) {
const CCoins* coins = view.AccessCoins(tx->GetHash());
if (coins && !coins->IsPruned())
return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
REJECT_INVALID, "bad-txns-BIP30");
}
}
unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
//Check if Segregate Witness is enbaled
if (IsWitnessEnabled(pindex->pprev)) {
flags |= SCRIPT_VERIFY_WITNESS;
flags |= SCRIPT_VERIFY_NULLDUMMY;
}
int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
CBlockUndo blockundo;
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
CAmount nFees = 0;
int nInputs = 0;
unsigned int nSigOps = 0;
CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
std::vector<std::pair<uint256, CDiskTxPos> > vPos;
vPos.reserve(block.vtx.size());
blockundo.vtxundo.reserve(block.vtx.size() - 1);
std::vector<PrecomputedTransactionData> txdata;
txdata.reserve(block.vtx.size() - 1); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
for (unsigned int i = 0; i < block.vtx.size(); i++)
{
const CTransaction &tx = *(block.vtx[i]);
nInputs += tx.vin.size();
nSigOps += GetLegacySigOpCount(tx);
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("ConnectBlock(): too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
txdata.emplace_back(tx);
if (!tx.IsCoinBase())
{
if (!view.HaveInputs(tx))
return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
REJECT_INVALID, "bad-txns-inputs-missingorspent");
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue cvn" from creating
// an incredibly-expensive-to-validate block.
nSigOps += GetP2SHSigOpCount(tx, view);
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("ConnectBlock(): too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
nFees += view.GetValueIn(tx)-tx.GetValueOut();
std::vector<CScriptCheck> vChecks;
bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, txdata[i],nScriptCheckThreads ? &vChecks : NULL))
return error("ConnectBlock(): CheckInputs on %s failed with %s",
tx.GetHash().ToString(), FormatStateMessage(state));
control.Add(vChecks);
}
CTxUndo undoDummy;
if (i > 0) {
blockundo.vtxundo.push_back(CTxUndo());
}
UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
vPos.push_back(std::make_pair(tx.GetHash(), pos));
pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
}
int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
if (block.HasCoinSupplyPayload()) {
if (block.vtx[0]->vout.size() != 2)
return state.DoS(100, error("ConnectBlock(): invalid coinbase transaction for new supply. Not enough outputs"),
REJECT_INVALID, "bad-cs-size");
if (block.vtx[0]->vout[1].nValue != block.coinSupply.nValue)
return state.DoS(100,
error("ConnectBlock(): invalid amount in coinbase transaction for new supply. (actual=%d vs expected=%d)",
block.vtx[0]->vout[1].nValue, block.coinSupply.nValue),
REJECT_INVALID, "bad-cs-amount");
if (block.vtx[0]->vout[1].scriptPubKey != block.coinSupply.scriptDestination)
return state.DoS(100,
error("ConnectBlock(): invalid amount in coinbase script for new supply. (actual=%s vs expected=%s)",
ScriptToAsmStr(block.vtx[0]->vout[1].scriptPubKey), ScriptToAsmStr(block.coinSupply.scriptDestination)),
REJECT_INVALID, "bad-cs-script");
if (block.vAdminIds.empty())
return state.DoS(100,
error("ConnectBlock(): no admin signatures available"),
REJECT_INVALID, "bad-cs-nosig");
if (block.vAdminIds.size() != mapChainAdmins.size())
return state.DoS(100,
error("ConnectBlock(): not all admins signed the coins supply message"),
REJECT_INVALID, "bad-cs-nosigall");
if (!MoneyRange(block.coinSupply.nValue)) {
return state.DoS(100,
error("ConnectBlock(): amount of coin supply out of range: %u",
block.coinSupply.nValue),
REJECT_INVALID, "bad-cs-amountoutofrange");
}
if (fCoinSupplyFinal)
return state.DoS(100, error("ConnectBlock(): coin supply is already final"),
REJECT_INVALID, "coins-supply-final");
nFees += block.coinSupply.nValue;
}
CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight);
if (block.vtx[0].GetValueOut() > blockReward)
return state.DoS(100,
error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
block.vtx[0].GetValueOut(), blockReward),
REJECT_INVALID, "bad-cb-amount");
if (!control.Wait())
return state.DoS(100, false);
uint64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
if (fJustCheck)
return true;
// Write undo information to disk
if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
{
if (pindex->GetUndoPos().IsNull()) {
CDiskBlockPos pos;
if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
return error("ConnectBlock(): FindUndoPos failed");
if (!UndoWriteToDisk(blockundo, pos,
block.GetHash() == chainparams.GetConsensus().hashGenesisBlock ? uint256() : pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
return AbortNode(state, "Failed to write undo data");
// update nUndoPos in block index
pindex->nUndoPos = pos.nPos;
pindex->nStatus |= BLOCK_HAVE_UNDO;
}
pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
setDirtyBlockIndex.insert(pindex);
}
if (fTxIndex)
if (!pblocktree->WriteTxIndex(vPos))
return AbortNode(state, "Failed to write transaction index");
// add this block to the view's block chain
view.SetBestBlock(pindex->GetBlockHash());
int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
if (block.HasTx()) {
// Watch for changes to the previous coinbase transaction.
static uint256 hashPrevBestCoinBase;
GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = block.vtx[0]->GetHash();
}
int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
return true;
}
/**
* Update the on-disk chain state.
* The caches and indexes are flushed depending on the mode we're called with
* if they're too large, if it's been a while since the last write,
* or always and in all cases if we're in prune mode and are deleting files.
*/
bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
const CChainParams& chainparams = Params();
LOCK2(cs_main, cs_LastBlockFile);
static int64_t nLastWrite = 0;
static int64_t nLastFlush = 0;
static int64_t nLastSetChain = 0;
std::set<int> setFilesToPrune;
bool fFlushForPrune = false;
try {
if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
if (nManualPruneHeight > 0) {
FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
} else {
FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
fCheckForPruning = false;
}
if (!setFilesToPrune.empty()) {
fFlushForPrune = true;
if (!fHavePruned) {
pblocktree->WriteFlag("prunedblockfiles", true);
fHavePruned = true;
}
}
}
int64_t nNow = GetTimeMicros();
// Avoid writing/flushing immediately after startup.
if (nLastWrite == 0) {
nLastWrite = nNow;
}
if (nLastFlush == 0) {
nLastFlush = nNow;
}
if (nLastSetChain == 0) {
nLastSetChain = nNow;
}
int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
int64_t cacheSize = pcoinsTip->DynamicMemoryUsage() * DB_PEAK_USAGE_FACTOR;
int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
// The cache is large and we're within 10% and 200 MiB or 50% and 50MiB of the limit, but we have time now (not in the middle of a block processing).
bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::min(std::max(nTotalSpace / 2, nTotalSpace - MIN_BLOCK_COINSDB_USAGE * 1024 * 1024),
std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024));
// The cache is over the limit, we have to write now.
bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
// It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
// It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
// Combine all conditions that result in a full cache flush.
bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
// Write blocks and block index to disk.
if (fDoFullFlush || fPeriodicWrite) {
// Depend on nMinDiskSpace to ensure we can write block index
if (!CheckDiskSpace(0))
return state.Error("out of disk space");
// First make sure all block and undo data is flushed to disk.
FlushBlockFile();
// Then update all block file information (which may refer to block and undo files).
{
std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
vFiles.reserve(setDirtyFileInfo.size());
for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
setDirtyFileInfo.erase(it++);
}
std::vector<const CBlockIndex*> vBlocks;
vBlocks.reserve(setDirtyBlockIndex.size());
for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
vBlocks.push_back(*it);
setDirtyBlockIndex.erase(it++);
}
if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
return AbortNode(state, "Failed to write to block index database");
}
}
// Finally remove any pruned files
if (fFlushForPrune)
UnlinkPrunedFiles(setFilesToPrune);
nLastWrite = nNow;
}
// Flush best chain related state. This can only be done if the blocks / block index write was also done.
if (fDoFullFlush) {
// Typical CCoins structures on disk are around 128 bytes in size.
// Pushing a new one to the database can cause it to be written
// twice (once in the log, and once in the tables). This is already
// an overestimation, as most will delete an existing entry or
// overwrite one. Still, use a conservative safety factor of 2.
if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
return state.Error("out of disk space");
// Flush the chainstate (which may refer to block index entries).
if (!pcoinsTip->Flush())
return AbortNode(state, "Failed to write to coin database");
nLastFlush = nNow;
}
if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
// Update best block in wallet (so we can detect restored wallets).
GetMainSignals().SetBestChain(chainActive.GetLocator());
nLastSetChain = nNow;
}
} catch (const std::runtime_error& e) {
return AbortNode(state, std::string("System error while flushing: ") + e.what());
}
return true;
}
void FlushStateToDisk() {
CValidationState state;
FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
}
void PruneAndFlush() {
CValidationState state;
fCheckForPruning = true;
FlushStateToDisk(state, FLUSH_STATE_NONE);
}
/** Update chainActive and related internal data structures. */
void static UpdateTip(CBlockIndex *pindexNew)
{
const CChainParams& chainParams = Params();
chainActive.SetTip(pindexNew);
// New best block
nTimeBestReceived = GetTime();
mempool.AddTransactionsUpdated(1);
LogPrintf("%s: new best=%s height=%d creator=%08x pl=%s work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), pindexNew->nCreatorId, pindexNew->GetPayloadString(),
log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->nTime),
Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)),
pcoinsTip->GetCacheSize());
cvBlockChange.notify_all();
// Check the version of the last 100 blocks to see if we need to upgrade:
static bool fWarned = false;
if (!IsInitialBlockDownload())
{
if (!fWarned) {
int nUpgraded = 0;
const CBlockIndex* pindex = chainActive.Tip();
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if ((pindex->nVersion & ~CBlock::PAYLOAD_MASK) > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)(CBlock::CURRENT_VERSION & ~CBlock::PAYLOAD_MASK));
if (nUpgraded > 100/2)
{
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
CAlert::Notify(strMiscWarning, true);
fWarned = true;
}
}
}
}
/** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
bool static DisconnectTip(CValidationState& state, const Consensus::Params& consensusParams)
{
CBlockIndex *pindexDelete = chainActive.Tip();
assert(pindexDelete);
// Read block from disk.
CBlock block;
if (!ReadBlockFromDisk(block, pindexDelete, consensusParams))
return AbortNode(state, "Failed to read block");
// Apply the block atomically to the chain state.
int64_t nStart = GetTimeMicros();
{
CCoinsViewCache view(pcoinsTip);
if (!DisconnectBlock(block, state, pindexDelete, view))
return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
assert(view.Flush());
}
LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
return false;
// Resurrect mempool transactions from the disconnected block.
std::vector<uint256> vHashUpdate;
for (const auto& it : block.vtx) {
// ignore validation errors in resurrected transactions
const CTransaction& tx = *it;
list<CTransaction> removed;
CValidationState stateDummy;
if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, it, false, NULL, NULL, true)) {
mempool.removeRecursive(tx, MemPoolRemovalReason::REORG);
} else if (mempool.exists(tx.GetHash())) {
vHashUpdate.push_back(tx.GetHash());
}
}
// AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
// no in-mempool children, which is generally not true when adding
// previously-confirmed transactions back to the mempool.
// UpdateTransactionsFromBlock finds descendants of any transactions in this
// block that were added back and cleans up the mempool state.
mempool.UpdateTransactionsFromBlock(vHashUpdate);
// Update chainActive and related variables.
UpdateTip(pindexDelete->pprev);
// Let wallets know transactions went from 1-confirmed to
// 0-confirmed or conflicted:
for (const auto& tx : block.vtx) {
GetMainSignals().SyncTransaction(*tx, pindexDelete->pprev, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK);
}
return true;
}
static int64_t nTimeReadFromDisk = 0;
static int64_t nTimeConnectTotal = 0;
static int64_t nTimeFlush = 0;
static int64_t nTimeChainState = 0;
static int64_t nTimePostConnect = 0;
/**
* Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
* corresponding to pindexNew, to bypass loading it again from disk.
*/
bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const CBlock* pblock)
{
assert(pindexNew->pprev == chainActive.Tip());
// Read block from disk.
int64_t nTime1 = GetTimeMicros();
CBlock block;
if (!pblock) {
if (!ReadBlockFromDisk(block, pindexNew, chainparams.GetConsensus()))
return AbortNode(state, "Failed to read block");
pblock = █
}
// Apply the block atomically to the chain state.
int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
int64_t nTime3;
LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
{
CCoinsViewCache view(pcoinsTip);
bool rv = ConnectBlock(*pblock, state, pindexNew, view);
GetMainSignals().BlockChecked(*pblock, state);
if (!rv) {
if (state.IsInvalid())
InvalidBlockFound(pindexNew, state);
return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
}
mapBlockSource.erase(pindexNew->GetBlockHash());
nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
assert(view.Flush());
}
int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
return false;
int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
// Remove conflicting transactions from the mempool.
list<CTransaction> txConflicted;
mempool.removeForBlock(pblock->vtx, pindexNew->nHeight);
// Update chainActive & related variables.
UpdateTip(pindexNew);
int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
if (pblock->HasCvnInfo())
UpdateCvnInfo(pblock, pindexNew->nHeight);
if (pblock->HasChainParameters())
UpdateChainParameters(pblock);
if (pblock->HasChainAdmins())
UpdateChainAdmins(pblock);
if (pblock->HasCoinSupplyPayload()) {
SetCoinSupplyStatus(pblock);
}
if (!IsInitialBlockDownload()) {
const uint32_t nNextCreator = CheckNextBlockCreator(pindexNew, block.nTime + 1);
// if two successive blocks are created by the same CVN ID (during bootstrap)
// the sigHolder needs to be cleared completely
if (nNextCreator == pblock->nCreatorId) {
sigHolder.SetNull();
} else {
sigHolder.clear(nNextCreator);
}
CheckNoncePools(pindexNew);
ExpireChainAdminData();
}
return true;
}
/**
* Return the tip of the chain with the most work in it, that isn't
* known to be invalid (it's however far from certain to be valid).
*/
static CBlockIndex* FindMostWorkChain()
{
do {
CBlockIndex *pindexNew = NULL;
// Find the best candidate header.
{
std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
if (it == setBlockIndexCandidates.rend())
return NULL;
pindexNew = *it;
}
// Check whether all blocks on the path between the currently active chain and the candidate are valid.
// Just going until the active chain is an optimization, as we know all blocks in it are valid already.
CBlockIndex *pindexTest = pindexNew;
bool fInvalidAncestor = false;
while (pindexTest && !chainActive.Contains(pindexTest)) {
assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
// Pruned nodes may have entries in setBlockIndexCandidates for
// which block files have been deleted. Remove those as candidates
// for the most work chain if we come across them; we can't switch
// to a chain unless we have all the non-active-chain parent blocks.
bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
if (fFailedChain || fMissingData) {
// Candidate chain is not usable (either invalid or missing data)
if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindexNew;
CBlockIndex *pindexFailed = pindexNew;
// Remove the entire chain from the set.
while (pindexTest != pindexFailed) {
if (fFailedChain) {
pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
} else if (fMissingData) {
// If we're missing data, then add back to mapBlocksUnlinked,
// so that if the block arrives in the future we can try adding
// to setBlockIndexCandidates again.
mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
}
setBlockIndexCandidates.erase(pindexFailed);
pindexFailed = pindexFailed->pprev;
}
setBlockIndexCandidates.erase(pindexTest);
fInvalidAncestor = true;
break;
}
pindexTest = pindexTest->pprev;
}
if (!fInvalidAncestor)
return pindexNew;
} while(true);
}
/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
static void PruneBlockIndexCandidates() {
// Note that we can't delete the current block itself, as we may need to return to it later in case a
// reorganization to a better block fails.
std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
setBlockIndexCandidates.erase(it++);
}
// Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
assert(!setBlockIndexCandidates.empty());
}
/**
* Try to make some progress towards making pindexMostWork the active block.
* pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
*/
static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const CBlock* pblock)
{
AssertLockHeld(cs_main);
bool fInvalidFound = false;
const CBlockIndex *pindexOldTip = chainActive.Tip();
const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
// Disconnect active blocks which are no longer in the best chain.
bool fBlocksDisconnected = false;
while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
if (!DisconnectTip(state, chainparams.GetConsensus()))
return false;
fBlocksDisconnected = true;
}
// Build list of new blocks to connect.
std::vector<CBlockIndex*> vpindexToConnect;
bool fContinue = true;
int nHeight = pindexFork ? pindexFork->nHeight : -1;
while (fContinue && nHeight != pindexMostWork->nHeight) {
// Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
// a few blocks along the way.
int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
vpindexToConnect.clear();
vpindexToConnect.reserve(nTargetHeight - nHeight);
CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
while (pindexIter && pindexIter->nHeight != nHeight) {
vpindexToConnect.push_back(pindexIter);
pindexIter = pindexIter->pprev;
}
nHeight = nTargetHeight;
// Connect new blocks.
BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
if (state.IsInvalid()) {
// The block violates a consensus rule.
if (!state.CorruptionPossible())
InvalidChainFound(vpindexToConnect.back());
state = CValidationState();
fInvalidFound = true;
fContinue = false;
break;
} else {
// A system error occurred (disk space, database error, ...).
return false;
}
} else {
PruneBlockIndexCandidates();
if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
// We're in a better position than we were. Return temporarily to release the lock.
fContinue = false;
break;
}
}
}
}
if (fBlocksDisconnected) {
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
}
mempool.check(pcoinsTip);
// Callbacks/notifications for a new best chain.
if (fInvalidFound)
CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
else
CheckForkWarningConditions();
return true;
}
/**
* Make the best chain active, in multiple steps. The result is either failure
* or an activated best chain. pblock is either NULL or a pointer to a block
* that is already loaded (to avoid loading it again from disk).
*/
bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, const CBlock *pblock)
{
CBlockIndex *pindexMostWork = NULL;
do {
boost::this_thread::interruption_point();
if (ShutdownRequested())
break;
CBlockIndex *pindexNewTip = NULL;
const CBlockIndex *pindexFork;
bool fInitialDownload;
{
LOCK(cs_main);
CBlockIndex *pindexOldTip = chainActive.Tip();
pindexMostWork = FindMostWorkChain();
// Whether we have anything to do at all.
if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
return true;
if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
return false;
pindexNewTip = chainActive.Tip();
pindexFork = chainActive.FindFork(pindexOldTip);
fInitialDownload = IsInitialBlockDownload();
}
// When we reach this point, we switched to a new tip (stored in pindexNewTip).
// Notifications/callbacks that can run without cs_main
// Always notify the UI if a new block tip was connected
if (pindexFork != pindexNewTip) {
uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
if (!fInitialDownload) {
// Find the hashes of all blocks that weren't previously in the best chain.
std::vector<uint256> vHashes;
CBlockIndex *pindexToAnnounce = pindexNewTip;
while (pindexToAnnounce != pindexFork) {
vHashes.push_back(pindexToAnnounce->GetBlockHash());
pindexToAnnounce = pindexToAnnounce->pprev;
if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
// Limit announcements in case of a huge reorganization.
// Rely on the peer's synchronization mechanism in that case.
break;
}
}
// Relay inventory, but don't relay old inventory during initial block download.
int nBlockEstimate = 0;
if (fCheckpointsEnabled)
nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints());
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) {
BOOST_REVERSE_FOREACH(const uint256& hash, vHashes) {
pnode->PushBlockHash(hash);
}
}
}
}
// Notify external listeners about the new tip.
if (!vHashes.empty()) {
GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
}
}
}
} while(pindexMostWork != chainActive.Tip());
CheckBlockIndex(chainparams.GetConsensus());
// Write changes periodically to disk, after relay.
if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
return false;
}
return true;
}
bool InvalidateBlock(CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex *pindex)
{
AssertLockHeld(cs_main);
// Mark the block itself as invalid.
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
while (chainActive.Contains(pindex)) {
CBlockIndex *pindexWalk = chainActive.Tip();
pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(pindexWalk);
setBlockIndexCandidates.erase(pindexWalk);
// ActivateBestChain considers blocks already in chainActive
// unconditionally valid already, so force disconnect away from it.
if (!DisconnectTip(state, consensusParams)) {
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
return false;
}
}
LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
// The resulting new best tip may not be in setBlockIndexCandidates anymore, so
// add it again.
BlockMap::iterator it = mapBlockIndex.begin();
while (it != mapBlockIndex.end()) {
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
setBlockIndexCandidates.insert(it->second);
}
it++;
}
InvalidChainFound(pindex);
mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
return true;
}
bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
AssertLockHeld(cs_main);
int nHeight = pindex->nHeight;
// Remove the invalidity flag from this block and all its descendants.
BlockMap::iterator it = mapBlockIndex.begin();
while (it != mapBlockIndex.end()) {
if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
it->second->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(it->second);
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
setBlockIndexCandidates.insert(it->second);
}
if (it->second == pindexBestInvalid) {
// Reset invalid block marker if it was pointing to one of those.
pindexBestInvalid = NULL;
}
}
it++;
}
// Remove the invalidity flag from all ancestors too.
while (pindex != NULL) {
if (pindex->nStatus & BLOCK_FAILED_MASK) {
pindex->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(pindex);
}
pindex = pindex->pprev;
}
return true;
}
CBlockIndex* AddToBlockIndex(const CBlockHeader& block, const vector<uint32_t>* vMissingSignerIds)
{
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator it = mapBlockIndex.find(hash);
if (it != mapBlockIndex.end())
return it->second;
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(block, vMissingSignerIds);
assert(pindexNew);
// We assign the sequence id to blocks only when the full data is available,
// to avoid miners withholding blocks but broadcasting headers, to get a
// competitive advantage.
pindexNew->nSequenceId = 0;
BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
pindexNew->BuildSkip();
}
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 1) + GetBlockProof(*pindexNew);
pindexNew->RaiseValidity(BLOCK_VALID_TREE);
if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
pindexBestHeader = pindexNew;
setDirtyBlockIndex.insert(pindexNew);
return pindexNew;
}
/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
{
pindexNew->nTx = block.HasTx() ? block.vtx.size() : 1; // CVN blocks and chain params blocks count 1 tx
pindexNew->nChainTx = 0;
pindexNew->nFile = pos.nFile;
pindexNew->nDataPos = pos.nPos;
pindexNew->nUndoPos = 0;
pindexNew->nStatus |= BLOCK_HAVE_DATA;
pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
setDirtyBlockIndex.insert(pindexNew);
if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
// If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
deque<CBlockIndex*> queue;
queue.push_back(pindexNew);
// Recursively process any descendant blocks that now may be eligible to be connected.
while (!queue.empty()) {
CBlockIndex *pindex = queue.front();
queue.pop_front();
pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
{
LOCK(cs_nBlockSequenceId);
pindex->nSequenceId = nBlockSequenceId++;
}
if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
setBlockIndexCandidates.insert(pindex);
}
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
while (range.first != range.second) {
std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
queue.push_back(it->second);
range.first++;
mapBlocksUnlinked.erase(it);
}
}
} else {
if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
}
}
return true;
}
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
{
LOCK(cs_LastBlockFile);
unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
if (!fKnown) {
while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
nFile++;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
}
pos.nFile = nFile;
pos.nPos = vinfoBlockFile[nFile].nSize;
}
if ((int)nFile != nLastBlockFile) {
if (!fKnown) {
LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
}
FlushBlockFile(!fKnown);
nLastBlockFile = nFile;
}
vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
if (fKnown)
vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
else
vinfoBlockFile[nFile].nSize += nAddSize;
if (!fKnown) {
unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (fPruneMode)
fCheckForPruning = true;
if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenBlockFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
}
else
return state.Error("out of disk space");
}
}
setDirtyFileInfo.insert(nFile);
return true;
}
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
{
pos.nFile = nFile;
LOCK(cs_LastBlockFile);
unsigned int nNewSize;
pos.nPos = vinfoBlockFile[nFile].nUndoSize;
nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
setDirtyFileInfo.insert(nFile);
unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (fPruneMode)
fCheckForPruning = true;
if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenUndoFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
}
else
return state.Error("out of disk space");
}
return true;
}
bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOC)
{
// Check if at least one of TX, CVN or CHAIN_PARAMS bits are set
if (!(block.nVersion & CBlock::PAYLOAD_MASK))
return state.DoS(50, error("CheckBlockHeader(): invalid block version. No block type defined"),
REJECT_INVALID, "no-blk-type", true);
if (mapBannedCVNs.count(block.nCreatorId)) {
if (mapBannedCVNs[block.nCreatorId] > (uint32_t)chainActive.Tip()->nHeight)
return state.DoS(50, error("CheckBlockHeader(): received block created by a banned CVN"),
REJECT_INVALID, "banned-cvn", true);
}
// Check timestamp
if (block.GetBlockTime() > GetAdjustedTime() + dynParams.nBlockSpacing + 30)
return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
REJECT_INVALID, "time-too-new");
return true;
}
bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOC, bool fCheckMerkleRoot)
{
// These are checks that are independent of context.
if (block.fChecked)
return true;
// Check that the header is valid. This is mostly
// redundant with the call in AcceptBlockHeader.
if (!CheckBlockHeader(block, state, fCheckPOC))
return false;
if (fCheckPOC) {
// check for correct signature of the block hash by the creator
if (!CheckProofOfCooperation(block, Params().GetConsensus()))
return state.DoS(2, error("CheckBlock(): poc failed"),
REJECT_INVALID, "poc-failed", true);;
if (block.HasAdminPayload()) {
if (!CheckForDuplicateAdminSigs(block))
return state.DoS(100, error("CheckBlock(): invalid number of chain admin signatures"),
REJECT_INVALID, "bad-admin-sig", true);
if (!CheckAdminSignature(block.vAdminIds, block.GetPayloadHash(true), block.adminMultiSig, block.HasCoinSupplyPayload()))
return state.DoS(100, error("CheckBlock(): invalid chain admin signature"),
REJECT_INVALID, "bad-admin-sig", true);
}
if (block.hashPayload != block.GetPayloadHash())
return state.DoS(100, error("CheckBlock(): hashPayload mismatch"),
REJECT_INVALID, "bad-payload-hash", true);
}
// Check the merkle root.
if (fCheckMerkleRoot) {
bool mutated;
uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
if (block.hashMerkleRoot != hashMerkleRoot2)
return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
REJECT_INVALID, "bad-txnmrklroot", true);
// Check for merkle tree malleability (CVE-2012-2459): repeating sequences
// of transactions in a block without affecting the merkle root of a block,
// while still invalidating it.
if (mutated)
return state.DoS(100, error("CheckBlock(): duplicate transaction"),
REJECT_INVALID, "bad-txns-duplicate", true);
}
// All potential-corruption validation must be done before we do any
// transaction validation, as otherwise we may mark the header as invalid
// because we receive the wrong transactions for it.
if (block.HasCvnInfo()) {
if (block.vCvns.empty() || block.vCvns.size() > MAX_NUMBER_OF_CVNS)
return state.DoS(100, error("CheckBlock(): CvnInfos size limits exceeded"),
REJECT_INVALID, "bad-blk-length-cvn");
if (!CheckForDuplicateCvns(block))
return state.DoS(100, error("CheckBlock(): duplicate entries in CVN payload"),
REJECT_INVALID, "bad-dupl-cvn");
if (!CheckForSufficientNumberOfCvns(block, Params().GetConsensus()))
return state.DoS(20, error("CheckBlock(): insufficient number of CVN entries in payload"),
REJECT_INVALID, "too-few-cvns");
}
if (block.HasChainAdmins()) {
if (block.vChainAdmins.empty() || block.vChainAdmins.size() > MAX_NUMBER_OF_CHAIN_ADMINS)
return state.DoS(100, error("CheckBlock(): ChainAdmins size limits exceeded"),
REJECT_INVALID, "bad-blk-length-adm");
if (!CheckForDuplicateChainAdmins(block))
return state.DoS(100, error("CheckBlock(): duplicate entries in chain admins payload"),
REJECT_INVALID, "bad-dupl-adm");
}
if (block.HasChainParameters() && !CheckDynamicChainParameters(block.dynamicChainParams))
return state.DoS(100, error("CheckBlock(): dynamicChainParams checks failed"),
REJECT_INVALID, "bad-dyn-params");
if (block.HasTx()) {
// Size limits
if (block.vtx.empty() || block.vtx.size() > MAX_TX_PER_BLOCK || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > dynParams.nMaxBlockSize) {
return state.DoS(100, error("CheckBlock(): size limits failed"),
REJECT_INVALID, "bad-blk-length");
}
// First transaction must be coinbase, the rest must not be
if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
REJECT_INVALID, "bad-cb-missing");
for (unsigned int i = 1; i < block.vtx.size(); i++)
if (block.vtx[i]->IsCoinBase())
return state.DoS(100, error("CheckBlock(): more than one coinbase"),
REJECT_INVALID, "bad-cb-multiple");
// Check transactions
for(const auto& tx : block.vtx)
if (!CheckTransaction(*tx, state))
return error("CheckBlock(): CheckTransaction of %s failed with %s",
tx->GetHash().ToString(),
FormatStateMessage(state));
unsigned int nSigOps = 0;
for (const auto& tx : block.vtx)
{
nSigOps += GetLegacySigOpCount(*tx);
}
if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
REJECT_INVALID, "bad-blk-sigops");
}
if (fCheckPOC && fCheckMerkleRoot)
block.fChecked = true;
return true;
}
static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
{
if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
return true;
int nHeight = pindexPrev->nHeight+1;
// Don't accept any forks from the main chain prior to last checkpoint
CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
if (pcheckpoint && nHeight < pcheckpoint->nHeight)
return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
return true;
}
bool HasEnoughSignatures(CBlockIndex * const pindexPrev, const uint32_t nSignaturesToCheck)
{
CBlockIndex *pindex = pindexPrev;
size_t nSignatures = 0;
uint32_t nBlocks = 0;
// calculate the mean of the number of the signatures from
// the last dynParams.nBlocksToConsiderForSigCheck blocks
while (nBlocks < dynParams.nBlocksToConsiderForSigCheck && pindex != NULL) {
nSignatures += GetNumChainSigs(pindex);
pindex = pindex->pprev;
nBlocks++;
}
float nSignaturesMean = nBlocks ? (float) nSignatures / (float) nBlocks : 0.0f;
return (float) nSignaturesToCheck > nSignaturesMean * ((float)dynParams.nPercentageOfSignaturesMean / 100.0f);
}
bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev, bool fCheckSignatures)
{
// Check timestamp against prev
if (block.GetBlockTime() <= pindexPrev->GetBlockTime())
return state.Invalid(error("%s: block's timestamp is too early", __func__),
REJECT_INVALID, "time-too-old");
return true;
}
bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
{
const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
//const Consensus::Params& consensusParams = Params().GetConsensus();
if (block.HasTx()) {
// Check that all transactions are finalized
for(const auto& tx : block.vtx) {
int nLockTimeFlags = 0;
int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
? pindexPrev->GetMedianTimePast()
: block.GetBlockTime();
if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
}
}
}
// Coinbase must starts with serialized block height
CScript expect = CScript() << nHeight;
if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
!std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
}
bool fHaveWitness = false;
if (IsWitnessEnabled(pindexPrev)) {
int commitpos = GetWitnessCommitmentIndex(block);
if (commitpos != -1) {
bool malleated = false;
uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
// The malleation check is ignored; as the transaction tree itself
// already does not permit it, it is impossible to trigger in the
// witness tree.
if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
}
CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
}
fHaveWitness = true;
}
}
// No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
if (!fHaveWitness) {
for (size_t i = 0; i < block.vtx.size(); i++) {
if (block.vtx[i]->HasWitness()) {
return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
}
}
}
// After the coinbase witness nonce and commitment are verified,
// we can check if the block weight passes (before we've checked the
// coinbase witness, it would be possible for the weight to be too
// large by filling up the coinbase witness, which doesn't change
// the block hash, so we couldn't mark the block as permanently
// failed).
if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
}
return true;
}
static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, const vector<uint32_t>* vMissingSignerIds=NULL)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator miSelf = mapBlockIndex.find(hash);
CBlockIndex *pindex = NULL;
if (hash != chainparams.GetConsensus().hashGenesisBlock) {
if (miSelf != mapBlockIndex.end()) {
// Block header is already known.
pindex = miSelf->second;
if (ppindex)
*ppindex = pindex;
if (pindex->nStatus & BLOCK_FAILED_MASK)
return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
// if we have received the header first vMissingSignerIds was not set
if (vMissingSignerIds && !vMissingSignerIds->empty())
pindex->vMissingSignerIds = *vMissingSignerIds;
return true;
}
// when we receive headers only from a peer (in NetMsgType::HEADERS) during
// chain download we do not have all important information to do reliable PoC
// validation, therefore the fCheckPoC is disabled here
if (!CheckBlockHeader(block, state, false))
return false;
// Get prev block index
CBlockIndex* pindexPrev = NULL;
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi == mapBlockIndex.end())
return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
pindexPrev = (*mi).second;
if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
assert(pindexPrev);
if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
if (!ContextualCheckBlockHeader(block, state, pindexPrev))
return false;
}
if (pindex == NULL)
pindex = AddToBlockIndex(block, vMissingSignerIds);
if (ppindex)
*ppindex = pindex;
return true;
}
/** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
static bool AcceptBlock(const CBlock& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
{
AssertLockHeld(cs_main);
CBlockIndex *&pindex = *ppindex;
if (!AcceptBlockHeader(block, state, chainparams, &pindex, &block.vMissingSignerIds))
return false;
// Try to process all requested blocks that we don't have, but only
// process an unrequested block if it's new and has enough work to
// advance our tip, and isn't too many blocks ahead.
bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
// Blocks that are too out-of-order needlessly limit the effectiveness of
// pruning, because pruning will not delete block files that contain any
// blocks which are too close in height to the tip. Apply this test
// regardless of whether pruning is enabled; it should generally be safe to
// not process unrequested blocks.
bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
// TODO: deal better with return value and error conditions for duplicate
// and unrequested blocks.
if (fAlreadyHave) return true;
if (!fRequested) { // If we didn't ask for it:
if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
if (!fHasMoreWork) return true; // Don't process less-work chains
if (fTooFarAhead) return true; // Block height is too high
}
if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
if (state.IsInvalid() && !state.CorruptionPossible()) {
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
}
return false;
}
int nHeight = pindex->nHeight;
// Write block to history file
try {
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
if (dbp != NULL)
blockPos = *dbp;
if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
return error("AcceptBlock(): FindBlockPos failed");
if (dbp == NULL)
if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
AbortNode(state, "Failed to write block");
if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
return error("AcceptBlock(): ReceivedBlockTransactions failed");
} catch (const std::runtime_error& e) {
return AbortNode(state, std::string("System error: ") + e.what());
}
if (fCheckForPruning)
FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
return true;
}
bool CheckDuplicateBlock(CValidationState &state, const CChainParams& chainparams, const CBlock *pblock, const CBlockIndex *pindex, const CNode* pfrom)
{
BlockIndexByPrevHashType::iterator it = mapBlockIndexByPrevHash.find(pblock->hashPrevBlock);
if (it != mapBlockIndexByPrevHash.end()) {
if (it->second->nCreatorId == pblock->nCreatorId && it->second->GetBlockHash() != pblock->GetHash()) {
CBlock formerBlock;
if (!ReadBlockFromDisk(formerBlock, it->second, chainparams.GetConsensus()))
return AbortNode(state, "Failed to read block");
LogPrintf("CheckDuplicateBlock : ======>>>>> FATAL! Possibly malicious CVN detected <<<<<======\n");
LogPrintf("CheckDuplicateBlock : CVN 0x%08x created more than one block for the same parent hash\nreceived FIRST:\n%s\n\nreceived SECOND:\n%s\n",
pblock->nCreatorId, formerBlock.ToString(), pblock->ToString());
LogPrintf("CheckDuplicateBlock : CVN 0x%08x is now banned and should be removed by the chain administrators immediately.\n", pblock->nCreatorId);
{
LOCK(cs_mapBannedCVNs);
if (!mapBannedCVNs.count(pblock->nCreatorId))
mapBannedCVNs[pblock->nCreatorId] = chainActive.Tip()->nHeight;
}
uiInterface.NotifyCVNBanned(pblock->nCreatorId);
// tell all connected nodes about what happened
// they will also ban that CVN
CInv inv(MSG_BLOCK, pblock->GetHash());
CInv formerBlockInv(MSG_BLOCK, formerBlock.GetHash());
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (pfrom && pfrom->GetId() != pnode->GetId())
continue;
pnode->PushInventory(formerBlockInv);
pnode->PushInventory(inv);
}
return false;
}
} else {
LOCK(cs_mapBlockIndexByPrevHash);
mapBlockIndexByPrevHash[pblock->hashPrevBlock] = pindex;
}
return true;
}
bool ProcessNewBlock(CValidationState& state, const CChainParams& chainparams, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos* dbp)
{
// Preliminary checks
bool checked = CheckBlock(*pblock, state);
CBlockIndex *pindex = NULL;
{
LOCK(cs_main);
bool fRequested = MarkBlockAsReceived(pblock->GetHash());
fRequested |= fForceProcessing;
if (!checked) {
return error("%s: CheckBlock FAILED", __func__);
}
// Store to disk
bool ret = AcceptBlock(*pblock, state, chainparams, &pindex, fRequested, dbp);
if (pindex && pfrom) {
mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
}
CheckBlockIndex(chainparams.GetConsensus());
if (!ret)
return error("%s: AcceptBlock FAILED", __func__);
}
if (!CheckDuplicateBlock(state, chainparams, pblock, pindex, pfrom))
return error("%s: Bad block from peer %s", __func__, pfrom ? pfrom->addr.ToString() : "localhost");
if (!ActivateBestChain(state, chainparams, pblock))
return error("%s: ActivateBestChain failed", __func__);
return true;
}
bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev)
{
AssertLockHeld(cs_main);
assert(pindexPrev && pindexPrev == chainActive.Tip());
if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
CCoinsViewCache viewNew(pcoinsTip);
CBlockIndex indexDummy(block, &block.vMissingSignerIds);
indexDummy.pprev = pindexPrev;
indexDummy.nHeight = pindexPrev->nHeight + 1;
// NOTE: CheckBlockHeader is called by CheckBlock
if (!ContextualCheckBlockHeader(block, state, pindexPrev, true))
return false;
if (!CheckBlock(block, state, true, true))
return false;
if (!ContextualCheckBlock(block, state, pindexPrev))
return false;
if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
return false;
assert(state.IsValid());
return true;
}
/**
* BLOCK PRUNING CODE
*/
/* Calculate the amount of disk space the block & undo files currently use */
uint64_t CalculateCurrentUsage()
{
uint64_t retval = 0;
BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
retval += file.nSize + file.nUndoSize;
}
return retval;
}
/* Prune a block file (modify associated database entries)*/
void PruneOneBlockFile(const int fileNumber)
{
for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
CBlockIndex* pindex = it->second;
if (pindex->nFile == fileNumber) {
pindex->nStatus &= ~BLOCK_HAVE_DATA;
pindex->nStatus &= ~BLOCK_HAVE_UNDO;
pindex->nFile = 0;
pindex->nDataPos = 0;
pindex->nUndoPos = 0;
setDirtyBlockIndex.insert(pindex);
// Prune from mapBlocksUnlinked -- any block we prune would have
// to be downloaded again in order to consider its chain, at which
// point it would be considered as a candidate for
// mapBlocksUnlinked or setBlockIndexCandidates.
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
while (range.first != range.second) {
std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
range.first++;
if (it->second == pindex) {
mapBlocksUnlinked.erase(it);
}
}
}
}
vinfoBlockFile[fileNumber].SetNull();
setDirtyFileInfo.insert(fileNumber);
}
void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
{
for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
CDiskBlockPos pos(*it, 0);
boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
}
}
/* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
{
assert(fPruneMode && nManualPruneHeight > 0);
LOCK2(cs_main, cs_LastBlockFile);
if (chainActive.Tip() == NULL)
return;
// last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
int count=0;
for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
continue;
PruneOneBlockFile(fileNumber);
setFilesToPrune.insert(fileNumber);
count++;
}
LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
}
/* Calculate the block/rev files that should be deleted to remain under target*/
void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
{
LOCK2(cs_main, cs_LastBlockFile);
if (chainActive.Tip() == NULL || nPruneTarget == 0) {
return;
}
if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
return;
}
unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
uint64_t nCurrentUsage = CalculateCurrentUsage();
// We don't check to prune until after we've allocated new space for files
// So we should leave a buffer under our target to account for another allocation
// before the next pruning.
uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
uint64_t nBytesToPrune;
int count=0;
if (nCurrentUsage + nBuffer >= nPruneTarget) {
for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
if (vinfoBlockFile[fileNumber].nSize == 0)
continue;
if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
break;
// don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
continue;
PruneOneBlockFile(fileNumber);
// Queue up the files for removal
setFilesToPrune.insert(fileNumber);
nCurrentUsage -= nBytesToPrune;
count++;
}
}
LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
nLastBlockWeCanPrune, count);
}
bool CheckDiskSpace(uint64_t nAdditionalBytes)
{
uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
return true;
}
FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
{
if (pos.IsNull())
return NULL;
boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
boost::filesystem::create_directories(path.parent_path());
FILE* file = fopen(path.string().c_str(), "rb+");
if (!file && !fReadOnly)
file = fopen(path.string().c_str(), "wb+");
if (!file) {
LogPrintf("Unable to open file %s\n", path.string());
return NULL;
}
if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) {
LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
fclose(file);
return NULL;
}
}
return file;
}
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "blk", fReadOnly);
}
FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "rev", fReadOnly);
}
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
{
return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
}
CBlockIndex * InsertBlockIndex(uint256 hash)
{
if (hash.IsNull())
return NULL;
// Return existing
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew)
throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool static LoadBlockIndexDB()
{
const CChainParams& chainparams = Params();
if (!pblocktree->LoadBlockIndexGuts())
return false;
boost::this_thread::interruption_point();
// Calculate nChainWork
vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
{
CBlockIndex* pindex = item.second;
if ((pindex->nVersion & CBlock::CVN_PAYLOAD) && pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
CachedCvnType::iterator it = mapChachedCVNInfoBlocks.find(pindex->GetBlockHash());
if (it == mapChachedCVNInfoBlocks.end()) {
CBlock block;
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus())) {
LogPrintf("FATAL: Failed to read block %s\n", pindex->GetBlockHash().ToString());
return false;
}
mapChachedCVNInfoBlocks[pindex->GetBlockHash()] = block.vCvns;
if (!AddToCvnInfoCache(&block, pindex->nHeight))
return false;
}
}
pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
#if 0
LogPrintf("LoadBlockIndexDB : nVersion: 0x%08x, nHeight: %u, nChainwork: %s, nStatus: %u, blockHash: %s, sigs: %u\n",
pindex->nVersion, pindex->nHeight, pindex->nChainWork.ToString(), pindex->nStatus, pindex->GetBlockHash().ToString(),
GetNumChainSigs(pindex));
#endif
// We can link the chain of blocks for which we've received transactions at some point.
// Pruned nodes may have deleted the block.
if (pindex->nTx > 0) {
if (pindex->pprev) {
if (pindex->pprev->nChainTx) {
pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
} else {
pindex->nChainTx = 0;
mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
}
} else {
pindex->nChainTx = pindex->nTx;
}
}
if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
setBlockIndexCandidates.insert(pindex);
if ((pindex->nStatus & BLOCK_FAILED_MASK) && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindex;
if (pindex->pprev)
pindex->BuildSkip();
if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
pindexBestHeader = pindex;
}
// Load block file info
pblocktree->ReadLastBlockFile(nLastBlockFile);
vinfoBlockFile.resize(nLastBlockFile + 1);
LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
}
LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
for (int nFile = nLastBlockFile + 1; true; nFile++) {
CBlockFileInfo info;
if (pblocktree->ReadBlockFileInfo(nFile, info)) {
vinfoBlockFile.push_back(info);
} else {
break;
}
}
// Check presence of blk files
LogPrintf("Checking all blk files are present...\n");
set<int> setBlkDataFiles;
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
if (pindex->nStatus & BLOCK_HAVE_DATA) {
setBlkDataFiles.insert(pindex->nFile);
}
}
for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
{
CDiskBlockPos pos(*it, 0);
if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
return false;
}
}
// Check whether we have ever pruned block & undo files
pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
if (fHavePruned)
LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
// Check whether we need to continue reindexing
bool fReindexing = false;
pblocktree->ReadReindexing(fReindexing);
fReindex |= fReindexing;
// Check whether we have a transaction index
pblocktree->ReadFlag("txindex", fTxIndex);
LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
// Load pointer to end of best chain
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
if (it == mapBlockIndex.end())
return true;
chainActive.SetTip(it->second);
PruneBlockIndexCandidates();
LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
return true;
}
CVerifyDB::CVerifyDB()
{
uiInterface.ShowProgress(_("Verifying blocks..."), 0);
}
CVerifyDB::~CVerifyDB()
{
uiInterface.ShowProgress("", 100);
}
bool CVerifyDB::SetMostRecentCVNData(const CChainParams& chainparams, CBlockIndex* pindexStart)
{
bool fFoundCvnInfoPayload = false, fFoundDynamicChainParamsPayload = false, fFoundChainAdminsPayload = false;
for (CBlockIndex* pindex = pindexStart; pindex; pindex = pindex->pprev) {
if (pindex->nVersion & (CBlock::CVN_PAYLOAD | CBlock::CHAIN_PARAMETERS_PAYLOAD | CBlock::CHAIN_ADMINS_PAYLOAD)) {
CBlock block;
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
return error("SetMostrecentCVNData(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
if (!fFoundCvnInfoPayload && block.HasCvnInfo()) {
UpdateCvnInfo(&block, pindex->nHeight);
fFoundCvnInfoPayload = true;
}
if (!fFoundDynamicChainParamsPayload && block.HasChainParameters()) {
UpdateChainParameters(&block);
fFoundDynamicChainParamsPayload = true;
}
if (!fFoundChainAdminsPayload && block.HasChainAdmins()) {
UpdateChainAdmins(&block);
fFoundChainAdminsPayload = true;
}
}
if (fFoundCvnInfoPayload && fFoundDynamicChainParamsPayload && fFoundChainAdminsPayload)
break;
}
if (!fFoundCvnInfoPayload)
LogPrintf("SetMostRecentCVNData(): *** could not find a block with CvnInfo. Can not continue.\n");
if (!fFoundDynamicChainParamsPayload)
LogPrintf("SetMostRecentCVNData(): *** could not find a block with chain params payload. Can not continue.\n");
if (!fFoundChainAdminsPayload)
LogPrintf("SetMostRecentCVNData(): *** could not find a block with chain admins payload. Can not continue.\n");
for (CBlockIndex* pindex = pindexStart; pindex; pindex = pindex->pprev) {
if (pindex->nVersion & CBlock::COIN_SUPPLY_PAYLOAD) {
CBlock block;
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
return error("SetMostrecentCVNData(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
SetCoinSupplyStatus(&block);
}
}
return (fFoundCvnInfoPayload && fFoundDynamicChainParamsPayload && fFoundChainAdminsPayload);
}
bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
{
LOCK(cs_main);
if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
return true;
// Verify blocks in the best chain
if (nCheckDepth <= 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > chainActive.Height())
nCheckDepth = chainActive.Height();
nCheckLevel = std::max(0, std::min(4, nCheckLevel));
LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CCoinsViewCache coins(coinsview);
CBlockIndex* pindexState = chainActive.Tip();
CBlockIndex* pindexFailure = NULL;
int nGoodTransactions = 0;
CValidationState state;
if (!SetMostRecentCVNData(chainparams, chainActive.Tip()))
return error("VerifyDB(): *** initial SetMostRecentCVNData failed at %d, hash=%s", pindexState->nHeight, pindexState->GetBlockHash().ToString());
for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
{
boost::this_thread::interruption_point();
uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
if (pindex->nHeight < chainActive.Height()-nCheckDepth)
break;
CBlock block;
// check level 0: read from disk
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
// find the most recent CVN, chain admins, and ChainParams block
if (pindex->pprev && block.HasAdminPayload()) {
if (block.HasCoinSupplyPayload()) {
if (block.coinSupply.fFinalCoinsSupply)
fCoinSupplyFinal = false;
} else {
if (!SetMostRecentCVNData(chainparams, pindex->pprev))
return error("VerifyDB(): *** SetMostRecentCVNData failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
// check level 1: verify block validity
if (nCheckLevel >= 1 && !CheckBlock(block, state))
return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 2: verify undo validity
if (nCheckLevel >= 2 && pindex) {
CBlockUndo undo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (!pos.IsNull()) {
if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
// check level 3: check for inconsistencies during memory-only disconnect of tip blocks
if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
bool fClean = true;
if (!DisconnectBlock(block, state, pindex, coins, &fClean))
return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
pindexState = pindex->pprev;
if (!fClean) {
nGoodTransactions = 0;
pindexFailure = pindex;
} else
nGoodTransactions += block.vtx.size();
}
if (ShutdownRequested())
return true;
}
if (pindexFailure)
return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
// check level 4: try reconnecting blocks
if (nCheckLevel >= 4) {
CBlockIndex *pindex = pindexState;
if (!SetMostRecentCVNData(chainparams, pindex))
return error("VerifyDB(): *** SetMostRecentCVNData@reconnect failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
while (pindex != chainActive.Tip()) {
boost::this_thread::interruption_point();
uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
pindex = chainActive.Next(pindex);
CBlock block;
if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
if (!ConnectBlock(block, state, pindex, coins))
return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
if (block.HasCvnInfo())
UpdateCvnInfo(&block, pindex->nHeight);
if (block.HasChainParameters())
UpdateChainParameters(&block);
if (block.HasChainAdmins())
UpdateChainAdmins(&block);
if (block.HasCoinSupplyPayload())
SetCoinSupplyStatus(&block);
}
}
// finally set up the current chain environment
if (!SetMostRecentCVNData(chainparams, chainActive.Tip()))
return error("VerifyDB(): *** final SetMostRecentCVNData failed at %d, hash=%s", chainActive.Tip()->nHeight, chainActive.Tip()->GetBlockHash().ToString());
LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
return true;
}
void UnloadBlockIndex()
{
LOCK(cs_main);
setBlockIndexCandidates.clear();
chainActive.SetTip(NULL);
pindexBestInvalid = NULL;
pindexBestHeader = NULL;
mempool.clear();
mapOrphanTransactions.clear();
mapOrphanTransactionsByPrev.clear();
nSyncStarted = 0;
mapBlocksUnlinked.clear();
vinfoBlockFile.clear();
nLastBlockFile = 0;
nBlockSequenceId = 1;
mapBlockSource.clear();
mapBlocksInFlight.clear();
nPreferredDownload = 0;
setDirtyBlockIndex.clear();
setDirtyFileInfo.clear();
mapNodeState.clear();
recentRejects.reset(NULL);
BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
delete entry.second;
}
mapBlockIndex.clear();
fHavePruned = false;
}
bool LoadBlockIndex()
{
// Load block index from databases
if (!fReindex && !LoadBlockIndexDB())
return false;
return true;
}
bool InitBlockIndex(const CChainParams& chainparams)
{
LOCK(cs_main);
// Initialize global variables that cannot be constructed at startup.
recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
// Check whether we're already initialized
if (chainActive.Genesis() != NULL)
return true;
// Use the provided setting for -txindex in the new database
fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
pblocktree->WriteFlag("txindex", fTxIndex);
LogPrintf("Initializing databases...\n");
// Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
if (!fReindex) {
try {
CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
// Start new block file
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
CValidationState state;
if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
return error("LoadBlockIndex(): FindBlockPos failed");
if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
return error("LoadBlockIndex(): writing genesis block to disk failed");
CBlockIndex *pindex = AddToBlockIndex(block, &block.vMissingSignerIds);
if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
return error("LoadBlockIndex(): genesis block not accepted");
if (!ActivateBestChain(state, chainparams, &block))
return error("LoadBlockIndex(): genesis block cannot be activated");
// Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
} catch (const std::runtime_error& e) {
return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
}
}
return true;
}
bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
{
// Map of disk positions for blocks with unknown parent (only used for reindex)
static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
int64_t nStart = GetTimeMillis();
int nLoaded = 0;
try {
// This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
CBufferedFile blkdat(fileIn, 2*MAX_SIZE_OF_BLOCK, MAX_SIZE_OF_BLOCK+8, SER_DISK, CLIENT_VERSION);
uint64_t nRewind = blkdat.GetPos();
while (!blkdat.eof()) {
boost::this_thread::interruption_point();
blkdat.SetPos(nRewind);
nRewind++; // start one byte further next time, in case of failure
blkdat.SetLimit(); // remove former limit
unsigned int nSize = 0;
try {
// locate a header
unsigned char buf[MESSAGE_START_SIZE];
blkdat.FindByte(chainparams.MessageStart()[0]);
nRewind = blkdat.GetPos()+1;
blkdat >> FLATDATA(buf);
if (memcmp(buf, chainparams.MessageStart(), MESSAGE_START_SIZE))
continue;
// read size
blkdat >> nSize;
if (nSize < 76 || nSize > MAX_SIZE_OF_BLOCK)
continue;
} catch (const std::exception&) {
// no valid block header found; don't complain
break;
}
try {
// read block
uint64_t nBlockPos = blkdat.GetPos();
if (dbp)
dbp->nPos = nBlockPos;
blkdat.SetLimit(nBlockPos + nSize);
blkdat.SetPos(nBlockPos);
CBlock block;
blkdat >> block;
nRewind = blkdat.GetPos();
// detect out of order blocks, and store them for later
uint256 hash = block.GetHash();
if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
block.hashPrevBlock.ToString());
if (dbp)
mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
continue;
}
// process in case the block isn't known yet
if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
CValidationState state;
if (ProcessNewBlock(state, chainparams, NULL, &block, true, dbp))
nLoaded++;
if (state.IsError())
break;
} else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
}
// Recursively process earlier encountered successors of this block
deque<uint256> queue;
queue.push_back(hash);
while (!queue.empty()) {
uint256 head = queue.front();
queue.pop_front();
std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
while (range.first != range.second) {
std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
if (ReadBlockFromDisk(block, it->second, chainparams.GetConsensus()))
{
LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
head.ToString());
CValidationState dummy;
if (ProcessNewBlock(dummy, chainparams, NULL, &block, true, &it->second))
{
nLoaded++;
queue.push_back(block.GetHash());
}
}
range.first++;
mapBlocksUnknownParent.erase(it);
}
}
} catch (const std::exception& e) {
LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
}
}
} catch (const std::runtime_error& e) {
AbortNode(std::string("System error: ") + e.what());
}
if (nLoaded > 0)
LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
void static CheckBlockIndex(const Consensus::Params& consensusParams)
{
if (!fCheckBlockIndex) {
return;
}
LOCK(cs_main);
// During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
// so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
// iterating the block tree require that chainActive has been initialized.)
if (chainActive.Height() < 0) {
assert(mapBlockIndex.size() <= 1);
return;
}
// Build forward-pointing map of the entire block tree.
std::multimap<CBlockIndex*,CBlockIndex*> forward;
for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
forward.insert(std::make_pair(it->second->pprev, it->second));
}
assert(forward.size() == mapBlockIndex.size());
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
CBlockIndex *pindex = rangeGenesis.first->second;
rangeGenesis.first++;
assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
// Iterate over the entire block tree, using depth-first search.
// Along the way, remember whether there are blocks on the path from genesis
// block being explored which are the first to have certain properties.
size_t nNodes = 0;
int nHeight = 0;
CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
while (pindex != NULL) {
nNodes++;
if (pindexFirstInvalid == NULL && (pindex->nStatus & BLOCK_FAILED_VALID)) pindexFirstInvalid = pindex;
if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
// Begin: actual consistency checks.
if (pindex->pprev == NULL) {
// Genesis block checks.
assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
}
if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
// VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
// HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
if (!fHavePruned) {
// If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
assert(pindexFirstMissing == pindexFirstNeverProcessed);
} else {
// If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
}
if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
// All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
assert(pindex->nHeight == nHeight); // nHeight must be consistent.
assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
if (pindexFirstInvalid == NULL) {
// Checks for not-invalid blocks.
assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
}
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
if (pindexFirstInvalid == NULL) {
// If this block sorts at least as good as the current tip and
// is valid and we have all data for its parents, it must be in
// setBlockIndexCandidates. chainActive.Tip() must also be there
// even if some data has been pruned.
if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
assert(setBlockIndexCandidates.count(pindex));
}
// If some parent is missing, then it could be that this block was in
// setBlockIndexCandidates but had to be removed because of the missing data.
// In this case it must be in mapBlocksUnlinked -- see test below.
}
} else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
assert(setBlockIndexCandidates.count(pindex) == 0);
}
// Check whether this block is in mapBlocksUnlinked.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
bool foundInUnlinked = false;
while (rangeUnlinked.first != rangeUnlinked.second) {
assert(rangeUnlinked.first->first == pindex->pprev);
if (rangeUnlinked.first->second == pindex) {
foundInUnlinked = true;
break;
}
rangeUnlinked.first++;
}
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
// If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
assert(foundInUnlinked);
}
if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
// We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
assert(fHavePruned); // We must have pruned.
// This block may have entered mapBlocksUnlinked if:
// - it has a descendant that at some point had more work than the
// tip, and
// - we tried switching to that descendant but were missing
// data for some intermediate block between chainActive and the
// tip.
// So if this block is itself better than chainActive.Tip() and it wasn't in
// setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
if (pindexFirstInvalid == NULL) {
assert(foundInUnlinked);
}
}
}
// assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
// End: actual consistency checks.
// Try descending into the first subnode.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
if (range.first != range.second) {
// A subnode was found.
pindex = range.first->second;
nHeight++;
continue;
}
// This is a leaf node.
// Move upwards until we reach a node of which we have not yet visited the last child.
while (pindex) {
// We are going to either move to a parent or a sibling of pindex.
// If pindex was the first with a certain property, unset the corresponding variable.
if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
// Find our parent.
CBlockIndex* pindexPar = pindex->pprev;
// Find which child we just visited.
std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
while (rangePar.first->second != pindex) {
assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
rangePar.first++;
}
// Proceed to the next one.
rangePar.first++;
if (rangePar.first != rangePar.second) {
// Move to the sibling.
pindex = rangePar.first->second;
break;
} else {
// Move up further.
pindex = pindexPar;
nHeight--;
continue;
}
}
}
// Check that we actually traversed the entire map.
assert(nNodes == forward.size());
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
std::string GetWarnings(const std::string& strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
string strGUI;
if (!CLIENT_VERSION_IS_RELEASE) {
strStatusBar = "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications";
strGUI = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
}
if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE))
strStatusBar = strRPC = strGUI = "testsafemode enabled";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strGUI = strMiscWarning;
}
if (fLargeWorkForkFound)
{
nPriority = 2000;
strStatusBar = strRPC = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
strGUI = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
}
else if (fLargeWorkInvalidChainFound)
{
nPriority = 2000;
strStatusBar = strRPC = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.";
strGUI = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = strGUI = alert.strStatusBar;
}
}
}
if (strFor == "gui")
return strGUI;
else if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings(): invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
switch (inv.type)
{
case MSG_TX:
{
assert(recentRejects);
if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
{
// If the chain tip has changed previously rejected transactions
// might be now valid, e.g. due to a nLockTime'd tx becoming valid,
// or a double-spend. Reset the rejects filter and give those
// txs a second chance.
hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
recentRejects->reset();
}
return recentRejects->contains(inv.hash) ||
mempool.exists(inv.hash) ||
mapOrphanTransactions.count(inv.hash) ||
pcoinsTip->HaveCoins(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash);
case MSG_CVN_PUB_NONCE_POOL:
return mapRelayNonces.count(inv.hash);
case MSG_CVN_SIGNATURE:
return mapRelaySigs.count(inv.hash);
case MSG_CHAIN_ADMIN_NONCE:
return mapRelayAdminNonces.count(inv.hash);
case MSG_CHAIN_ADMIN_SIGNATURE:
return mapRelayAdminSigs.count(inv.hash);
case MSG_POC_CHAIN_DATA:
return mapRelayChainData.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
void static AdvertiseNoncesAndSigs(CNode *pfrom)
{
CBlockIndex *tip = chainActive.Tip();
{
LOCK(cs_mapNoncePool);
BOOST_FOREACH(const CNoncePoolType::value_type &p, mapNoncePool) {
if (GetPoolAge(p.second, tip) < 0) {
LogPrintf("AdvertiseSigsAndNonces : not sending expired nonce pool from height %d of CVN 0x%08x\n", p.second.nHeightAdded, p.second.nCvnId);
continue;
}
pfrom->PushInventory(CInv(MSG_CVN_PUB_NONCE_POOL, p.second.GetHash()));
}
}
const uint256 hashPrevBlock = tip->GetBlockHash();
const uint32_t nNextCreator = CheckNextBlockCreator(tip, GetAdjustedTime());
vector<CCvnPartialSignature> sigs;
if (sigHolder.GetSignatures(sigs)) {
BOOST_FOREACH(const CCvnPartialSignature &s, sigs) {
if (s.hashPrevBlock != hashPrevBlock || s.nCreatorId != nNextCreator) {
LogPrintf("AdvertiseSigsAndNonces : not sending outdated signature: 0x%08x vs 0x%08x, %s vs %s\n", s.nCreatorId, nNextCreator, s.hashPrevBlock.ToString(), hashPrevBlock.ToString());
continue;
}
pfrom->PushInventory(CInv(MSG_CVN_SIGNATURE, s.GetHash()));
}
}
}
void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams)
{
std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
vector<CInv> vNotFound;
LOCK(cs_main);
while (it != pfrom->vRecvGetData.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
const CInv &inv = *it;
{
boost::this_thread::interruption_point();
it++;
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
{
bool send = false;
BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
if (chainActive.Contains(mi->second)) {
send = true;
} else {
static const int nOneMonth = 30 * 24 * 60 * 60;
// To prevent fingerprinting attacks, only send blocks outside of the active
// chain if they are valid, and no more than a month older (both in time, and in
// best equivalent proof of work) than the best header chain we know about.
send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
(pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
(GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader) < nOneMonth);
// we also send bad blocks if the creating CVN is banned
send |= mapBannedCVNs.count(mi->second->nCreatorId) > 0;
if (!send) {
LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
}
}
}
// disconnect node in case we have reached the outbound limit for serving historical blocks
// never disconnect whitelisted nodes
static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
if (send && CNode::OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
{
LogPrint("net", "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
//disconnect node
pfrom->fDisconnect = true;
send = false;
}
uint64_t nPreviousTimeSinceLastBlockSent = pfrom->nTimeSinceLastBlockSent;
// Pruned nodes may have deleted the block, so check whether
// it's available before trying to send.
if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
{
// Send block from disk
CBlock block;
if (!ReadBlockFromDisk(block, (*mi).second, consensusParams))
assert(!"cannot load block from disk");
if (inv.type == MSG_BLOCK) {
pfrom->PushMessage(NetMsgType::BLOCK, block);
pfrom->nTimeSinceLastBlockSent = GetTime();
}
else // MSG_FILTERED_BLOCK)
{
nPreviousTimeSinceLastBlockSent = 0;
LOCK(pfrom->cs_filter);
if (pfrom->pfilter)
{
CMerkleBlock merkleBlock(block, *pfrom->pfilter);
pfrom->PushMessage(NetMsgType::MERKLEBLOCK, merkleBlock);
// CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
// This avoids hurting performance by pointlessly requiring a round-trip
// Note that there is currently no way for a node to request any single transactions we didn't send here -
// they must either disconnect and retry or request the full block.
// Thus, the protocol spec specified allows for us to provide duplicate txn here,
// however we MUST always provide at least what the remote peer needs
typedef std::pair<unsigned int, uint256> PairType;
BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
pfrom->PushMessage(NetMsgType::TX, block.vtx[pair.first]);
}
// else
// no response
}
// Trigger the peer node to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
pfrom->PushMessage(NetMsgType::INV, vInv);
pfrom->hashContinue.SetNull();
}
}
// if a peer requested our chain tip and it was downloading earlier blocks just before
// we advertise our nonce pool and our chain signatures
if (send && pfrom->fRelayPoCMessages
&& chainActive.Tip()->GetBlockHash() == inv.hash
&& nPreviousTimeSinceLastBlockSent > (uint64_t) (GetTime() - dynParams.nBlockSpacing + dynParams.nBlockPropagationWaitTime)) {
LogPrint("cvnsig", "peer %d requested chain tip, sending nonce pools and chain signatures\n", pfrom->id);
AdvertiseNoncesAndSigs(pfrom);
}
}
else if (inv.type == MSG_CVN_PUB_NONCE_POOL) {
CNoncePool *noncePool = NULL;
{
LOCK(cs_mapRelayNonces);
map<uint256, CNoncePool>::iterator mi = mapRelayNonces.find(inv.hash);
if (mi != mapRelayNonces.end())
noncePool = &(*mi).second;
}
if (noncePool)
pfrom->PushMessage(NetMsgType::NONCEPOOL, *noncePool);
else
vNotFound.push_back(inv);
}
else if (inv.type == MSG_CVN_SIGNATURE) {
CCvnPartialSignature *sig = NULL;
{
LOCK(cs_mapRelaySigs);
map<uint256, CCvnPartialSignature>::iterator mi = mapRelaySigs.find(inv.hash);
if (mi != mapRelaySigs.end())
sig = &(*mi).second;
}
if (sig)
pfrom->PushMessage(NetMsgType::SIG, *sig);
else
vNotFound.push_back(inv);
}
else if (inv.type == MSG_CHAIN_ADMIN_NONCE) {
CAdminNonce *nonce = NULL;
{
LOCK(cs_mapRelayAdminNonces);
map<uint256, CAdminNonce>::iterator mi = mapRelayAdminNonces.find(inv.hash);
if (mi != mapRelayAdminNonces.end())
nonce = &(*mi).second;
}
if (nonce)
pfrom->PushMessage(NetMsgType::NONCEADMIN, *nonce);
else
vNotFound.push_back(inv);
}
else if (inv.type == MSG_CHAIN_ADMIN_SIGNATURE) {
CAdminPartialSignature *sig = NULL;
{
LOCK(cs_mapRelayAdminSigs);
map<uint256, CAdminPartialSignature>::iterator mi = mapRelayAdminSigs.find(inv.hash);
if (mi != mapRelayAdminSigs.end())
sig = &(*mi).second;
}
if (sig)
pfrom->PushMessage(NetMsgType::SIGADMIN, *sig);
else
vNotFound.push_back(inv);
}
else if (inv.type == MSG_POC_CHAIN_DATA) {
CChainDataMsg *chainData = NULL;
{
LOCK(cs_mapRelayChainData);
map<uint256, CChainDataMsg>::iterator mi = mapRelayChainData.find(inv.hash);
if (mi != mapRelayChainData.end()) {
chainData = &(*mi).second;
}
}
if (chainData)
pfrom->PushMessage(NetMsgType::CHAINDATA, *chainData);
else
vNotFound.push_back(inv);
}
else if (inv.IsKnownType())
{
CTransaction tx;
// Send stream from relay memory
bool push = false;
{
LOCK(cs_mapRelay);
map<uint256, CTransaction>::iterator mi = mapRelay.find(inv.hash);
if (mi != mapRelay.end()) {
tx = (*mi).second;
push = true;
}
}
if (!push && inv.type == MSG_TX) {
if (mempool.lookup(inv.hash, tx)) {
push = true;
}
}
if (push) {
pfrom->PushMessage(inv.GetCommand(), tx);
} else {
vNotFound.push_back(inv);
}
}
// Track requests for our stuff.
GetMainSignals().Inventory(inv.hash);
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
break;
}
}
pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
if (!vNotFound.empty()) {
// Let the peer know that we didn't find what it asked for, so it doesn't
// have to wait around forever. Currently only SPV clients actually care
// about this message: it's needed when they are recursively walking the
// dependencies of relevant unconfirmed transactions. SPV clients want to
// do that because they want to know about (and store and rebroadcast and
// risk analyze) the dependencies of transactions relevant to them, without
// having to download the entire memory pool.
pfrom->PushMessage(NetMsgType::NOTFOUND, vNotFound);
}
}
uint32_t GetFetchFlags(CNode* pfrom, const CBlockIndex* pprev) {
uint32_t nFetchFlags = 0;
if ((pfrom->nServices & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
nFetchFlags |= MSG_WITNESS_FLAG;
}
return nFetchFlags;
}
/**
* Calculates the block height and previous block's median time past at
* which the transaction will be considered final in the context of BIP 68.
* Also removes from the vector of input heights any entries which did not
* correspond to sequence locked inputs as they do not affect the calculation.
*/
static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
{
assert(prevHeights->size() == tx.vin.size());
// Will be set to the equivalent height- and time-based nLockTime
// values that would be necessary to satisfy all relative lock-
// time constraints given our view of block chain history.
// The semantics of nLockTime are the last invalid height/time, so
// use -1 to have the effect of any height or time being valid.
int nMinHeight = -1;
int64_t nMinTime = -1;
// tx.nVersion is signed integer so requires cast to unsigned otherwise
// we would be doing a signed comparison and half the range of nVersion
// wouldn't support BIP 68.
bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
&& flags & LOCKTIME_VERIFY_SEQUENCE;
// Do not enforce sequence numbers as a relative lock time
// unless we have been instructed to
if (!fEnforceBIP68) {
return std::make_pair(nMinHeight, nMinTime);
}
for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
const CTxIn& txin = tx.vin[txinIndex];
// Sequence numbers with the most significant bit set are not
// treated as relative lock-times, nor are they given any
// consensus-enforced meaning at this point.
if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
// The height of this input is not relevant for sequence locks
(*prevHeights)[txinIndex] = 0;
continue;
}
int nCoinHeight = (*prevHeights)[txinIndex];
if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
// NOTE: Subtract 1 to maintain nLockTime semantics
// BIP 68 relative lock times have the semantics of calculating
// the first block or time at which the transaction would be
// valid. When calculating the effective block time or height
// for the entire transaction, we switch to using the
// semantics of nLockTime which is the last invalid block
// time or height. Thus we subtract 1 from the calculated
// time or height.
// Time-based relative lock-times are measured from the
// smallest allowed timestamp of the block containing the
// txout being spent, which is the median time past of the
// block prior.
nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
} else {
nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
}
}
return std::make_pair(nMinHeight, nMinTime);
}
static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
{
assert(block.pprev);
int64_t nBlockTime = block.pprev->GetMedianTimePast();
if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
return false;
return true;
}
bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
{
return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
}
bool TestLockPointValidity(const LockPoints* lp)
{
AssertLockHeld(cs_main);
assert(lp);
// If there are relative lock times then the maxInputBlock will be set
// If there are no relative lock times, the LockPoints don't depend on the chain
if (lp->maxInputBlock) {
// Check whether chainActive is an extension of the block at which the LockPoints
// calculation was valid. If not LockPoints are no longer valid
if (!chainActive.Contains(lp->maxInputBlock)) {
return false;
}
}
// LockPoints still valid
return true;
}
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
{
AssertLockHeld(cs_main);
AssertLockHeld(mempool.cs);
CBlockIndex* tip = chainActive.Tip();
CBlockIndex index;
index.pprev = tip;
// CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
// height based locks because when SequenceLocks() is called within
// ConnectBlock(), the height of the block *being*
// evaluated is what is used.
// Thus if we want to know if a transaction can be part of the
// *next* block, we need to use one more than chainActive.Height()
index.nHeight = tip->nHeight + 1;
std::pair<int, int64_t> lockPair;
if (useExistingLockPoints) {
assert(lp);
lockPair.first = lp->height;
lockPair.second = lp->time;
}
else {
// pcoinsTip contains the UTXO set for chainActive.Tip()
CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
std::vector<int> prevheights;
prevheights.resize(tx.vin.size());
for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
const CTxIn& txin = tx.vin[txinIndex];
CCoins coins;
if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
return error("%s: Missing input", __func__);
}
if (coins.nHeight == MEMPOOL_HEIGHT) {
// Assume all mempool transaction confirm in the next block
prevheights[txinIndex] = tip->nHeight + 1;
} else {
prevheights[txinIndex] = coins.nHeight;
}
}
lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
if (lp) {
lp->height = lockPair.first;
lp->time = lockPair.second;
// Also store the hash of the block with the highest height of
// all the blocks which have sequence locked prevouts.
// This hash needs to still be on the chain
// for these LockPoint calculations to be valid
// Note: It is impossible to correctly calculate a maxInputBlock
// if any of the sequence locked inputs depend on unconfirmed txs,
// except in the special case where the relative lock time/height
// is 0, which is equivalent to no sequence lock. Since we assume
// input height of tip+1 for mempool txs and test the resulting
// lockPair from CalculateSequenceLocks against tip+1. We know
// EvaluateSequenceLocks will fail if there was a non-zero sequence
// lock on a mempool input, so we can use the return value of
// CheckSequenceLocks to indicate the LockPoints validity
int maxInputHeight = 0;
BOOST_FOREACH(int height, prevheights) {
// Can ignore mempool inputs since we'll fail if they had non-zero locks
if (height != tip->nHeight+1) {
maxInputHeight = std::max(maxInputHeight, height);
}
}
lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
}
}
return EvaluateSequenceLocks(index, lockPair);
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams)
{
LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (!(nLocalServices & NODE_BLOOM) &&
(strCommand == NetMsgType::FILTERLOAD ||
strCommand == NetMsgType::FILTERADD ||
strCommand == NetMsgType::FILTERCLEAR))
{
Misbehaving(pfrom->GetId(), 100);
return false;
}
if (strCommand == NetMsgType::VERSION)
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
Misbehaving(pfrom->GetId(), 1);
return false;
}
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
{
// disconnect from peers older than this proto version
LogPrintf("peer=%d (%s) using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion, fLogIPs ? pfrom->addr.ToString() : "-");
pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
pfrom->fDisconnect = true;
return false;
}
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty()) {
vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
}
if (!vRecv.empty()) {
vRecv >> pfrom->nStartingHeight;
}
{
LOCK(pfrom->cs_filter);
if (!vRecv.empty())
vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
else
pfrom->fRelayTxes = true;
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
pfrom->fDisconnect = true;
return true;
}
pfrom->addrLocal = addrMe;
if (pfrom->fInbound && addrMe.IsRoutable())
{
SeenLocal(addrMe);
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
pfrom->fRelayPoCMessages = (pfrom->nServices & NODE_POC_DATA);
// Potentially mark this peer as a preferred download peer.
UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
// Change version
pfrom->PushMessage(NetMsgType::VERACK);
pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (fListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
{
LogPrint("net", "ProcessMessages: advertising address %s\n", addr.ToString());
pfrom->PushAddress(addr);
} else if (IsPeerAddrLocalGood(pfrom)) {
addr.SetIP(pfrom->addrLocal);
LogPrint("net", "ProcessMessages: advertising address %s\n", addr.ToString());
pfrom->PushAddress(addr);
}
}
// Get recent addresses
pfrom->PushMessage(NetMsgType::GETADDR);
pfrom->fGetAddr = true;
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
string remoteAddr;
if (fLogIPs)
remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
pfrom->cleanSubVer, pfrom->nVersion,
pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
remoteAddr);
int64_t nTimeOffset = nTime - GetTime();
pfrom->nTimeOffset = nTimeOffset;
AddTimeData(pfrom->addr, nTimeOffset);
pfrom->nTimeSinceLastBlockSent = 0;
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
Misbehaving(pfrom->GetId(), 1);
return false;
}
else if (strCommand == NetMsgType::VERACK)
{
pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
// Mark this node as currently connected, so we update its timestamp later.
if (pfrom->fNetworkNode) {
LOCK(cs_main);
State(pfrom->GetId())->fCurrentlyConnected = true;
}
// Tell our peer we prefer to receive headers rather than inv's
// We send this to non-NODE NETWORK peers as well, because even
// non-NODE NETWORK peers can announce blocks (such as pruning
// nodes)
pfrom->PushMessage(NetMsgType::SENDHEADERS);
// Advertise the chain signatures and public nonces we've got
if (pfrom->fRelayPoCMessages && pfrom->nStartingHeight == chainActive.Height())
AdvertiseNoncesAndSigs(pfrom);
}
else if (strCommand == NetMsgType::ADDR)
{
vector<CAddress> vAddr;
vRecv >> vAddr;
if (vAddr.size() > 1000)
{
Misbehaving(pfrom->GetId(), 20);
return error("message addr size() = %u", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
boost::this_thread::interruption_point();
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the addrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt.IsNull())
hashSalt = GetRandHash();
uint64_t hashAddr = addr.GetHash();
uint256 hashRand = ArithToUint256((arith_uint256)(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60))));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = ArithToUint256((arith_uint256)(UintToArith256(hashRand) ^ nPointer));
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == NetMsgType::SENDHEADERS)
{
LOCK(cs_main);
State(pfrom->GetId())->fPreferHeaders = true;
}
else if (strCommand == NetMsgType::INV)
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
Misbehaving(pfrom->GetId(), 20);
return error("message inv size() = %u", vInv.size());
}
bool fBlocksOnly = GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
// Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
fBlocksOnly = false;
LOCK(cs_main);
std::vector<CInv> vToFetch;
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
boost::this_thread::interruption_point();
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(inv);
LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
if (inv.type == MSG_BLOCK) {
UpdateBlockAvailability(pfrom->GetId(), inv.hash);
if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
// First request the headers preceding the announced block. In the normal fully-synced
// case where a new block is announced that succeeds the current tip (no reorganization),
// there are no such headers.
// Secondly, and only when we are close to being synced, we request the announced block directly,
// to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
// time the block arrives, the header chain leading up to it is already validated. Not
// doing this will result in the received block being rejected as an orphan in case it is
// not a direct successor.
pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash);
CNodeState *nodestate = State(pfrom->GetId());
if (CanDirectFetch(chainparams.GetConsensus()) &&
nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
vToFetch.push_back(inv);
// Mark block as in flight already, even though the actual "getdata" message only goes out
// later (within the same cs_main lock, though).
MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
}
LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
}
}
else if (!IsInitialBlockDownload() &&
(inv.type == MSG_CVN_PUB_NONCE_POOL || inv.type == MSG_CVN_SIGNATURE ||
inv.type == MSG_CHAIN_ADMIN_NONCE || inv.type == MSG_CHAIN_ADMIN_SIGNATURE || inv.type == MSG_POC_CHAIN_DATA)) {
if (!fAlreadyHave && !fImporting && !fReindex)
pfrom->AskFor(inv);
}
else
{
if (fBlocksOnly)
LogPrint("net", "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->id);
else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload())
pfrom->AskFor(inv);
}
// Track requests for our stuff
GetMainSignals().Inventory(inv.hash);
if (pfrom->nSendSize > (SendBufferSize() * 2)) {
Misbehaving(pfrom->GetId(), 50);
return error("send buffer size() = %u", pfrom->nSendSize);
}
}
if (!vToFetch.empty())
pfrom->PushMessage(NetMsgType::GETDATA, vToFetch);
}
else if (strCommand == NetMsgType::GETDATA)
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
Misbehaving(pfrom->GetId(), 20);
return error("message getdata size() = %u", vInv.size());
}
if (fDebug || (vInv.size() != 1))
LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
ProcessGetData(pfrom, chainparams.GetConsensus());
}
else if (strCommand == NetMsgType::GETBLOCKS)
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
// Find the last block the caller has in the main chain
CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
// Send the rest of the chain
if (pindex)
pindex = chainActive.Next(pindex);
int nLimit = 500;
LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex))
{
if (pindex->GetBlockHash() == hashStop)
{
LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
// If pruning, don't inv blocks unless we have on disk and are likely to still have
// for some reasonable time window (1 hour) that block relay might require.
const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / dynParams.nBlockSpacing;
if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
{
LogPrint("net", " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll
// trigger the peer to getblocks the next batch of inventory.
LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == NetMsgType::GETHEADERS)
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
LogPrint("net", "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->id);
return true;
}
CNodeState *nodestate = State(pfrom->GetId());
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
BlockMap::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = FindForkInGlobalIndex(chainActive, locator);
if (pindex)
pindex = chainActive.Next(pindex);
}
vector<CBlockHeader> vHeaders;
int nLimit = MAX_HEADERS_RESULTS;
LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex))
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
// pindex can be NULL either if we sent chainActive.Tip() OR
// if our peer has chainActive.Tip() (and thus we are sending an empty
// headers message). In both cases it's safe to update
// pindexBestHeaderSent to be our tip.
nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
pfrom->PushMessage(NetMsgType::HEADERS, vHeaders);
}
else if (strCommand == NetMsgType::CHAINDATA)
{
CChainDataMsg msg;
vRecv >> msg;
uint256 hashData = msg.GetHash();
CInv inv(MSG_POC_CHAIN_DATA, hashData);
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
pfrom->setAskFor.erase(inv.hash);
mapAlreadyAskedFor.erase(inv.hash);
if (!AlreadyHave(inv)) {
if (msg.hashPrevBlock != chainActive.Tip()->GetBlockHash()) {
LogPrintf("received outdated chain data for tip %s: %s\n", msg.hashPrevBlock.ToString(), msg.ToString());
} else if (AddChainData(msg)) {
RelayChainData(msg);
} else {
LogPrintf("received invalid chain data %s\n", msg.ToString());
Misbehaving(pfrom->GetId(), 50);
}
} else {
LogPrint("net", "AlreadyHave chain data %s\n", hashData.ToString());
}
}
else if (strCommand == NetMsgType::NONCEPOOL)
{
CNoncePool msg;
vRecv >> msg;
CInv inv(MSG_CVN_PUB_NONCE_POOL, msg.GetHash());
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
pfrom->setAskFor.erase(inv.hash);
mapAlreadyAskedFor.erase(inv.hash);
if (!AlreadyHave(inv)) {
if (!mapBannedCVNs.count(msg.nCvnId)) {
LogPrint("net", "received nonce pool %s for CvnID 0x%08x\n", msg.GetHash().ToString(), msg.nCvnId);
if (AddNoncePool(msg)) {
RelayNoncePool(msg);
} else {
LogPrintf("received invalid nonce pool %s\n", msg.ToString());
Misbehaving(pfrom->GetId(), 50);
}
} else {
LogPrintf("Ignoring nonce pool of banned CvnID 0x%08x\n", msg.nCvnId);
Misbehaving(pfrom->GetId(), 20);
}
} else {
LogPrint("net", "AlreadyHave nonce pool for CvnID 0x%08x\n", msg.nCvnId);
}
}
else if (strCommand == NetMsgType::SIG)
{
CCvnPartialSignature msg;
vRecv >> msg;
CInv inv(MSG_CVN_SIGNATURE, msg.GetHash());
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
pfrom->setAskFor.erase(inv.hash);
mapAlreadyAskedFor.erase(inv.hash);
if (!AlreadyHave(inv)) {
if (!mapBannedCVNs.count(msg.nSignerId)) {
if (msg.hashPrevBlock != chainActive.Tip()->GetBlockHash()) {
LogPrintf("received outdated chain signature for 0x%08x from peer %d for tip %s signed by 0x%08x\n", msg.nCreatorId, pfrom->id, msg.hashPrevBlock.ToString(), msg.nSignerId);
} else {
LogPrint("net", "received chain signature %s for tip %s\n", msg.GetHash().ToString(), msg.hashPrevBlock.ToString());
if (AddCvnSignature(msg)) {
RelayCvnSignature(msg);
} else {
LogPrintf("received invalid signature data %s\n", msg.ToString());
}
}
} else {
LogPrintf("Ignoring chain signature of banned CvnID 0x%08x\n", msg.nSignerId);
Misbehaving(pfrom->GetId(), 20);
}
} else {
LogPrint("net", "AlreadyHave sig %s\n", msg.hashPrevBlock.ToString());
}
}
else if (strCommand == NetMsgType::NONCEADMIN)
{
CAdminNonce msg;
vRecv >> msg;
CInv inv(MSG_CHAIN_ADMIN_NONCE, msg.GetHash());
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
pfrom->setAskFor.erase(inv.hash);
mapAlreadyAskedFor.erase(inv.hash);
if (!AlreadyHave(inv)) {
if (msg.hashRootBlock != chainActive.Tip()->GetBlockHash()) {
LogPrintf("received outdated admin nonce from peer %d for tip %s signed by 0x%08x\n", pfrom->id, msg.hashRootBlock.ToString(), msg.nAdminId);
} else {
LogPrint("net", "received admin nonce %s for admin ID 0x%08x\n", msg.GetHash().ToString(), msg.nAdminId);
if (AddNonceAdmin(msg)) {
RelayNonceAdmin(msg);
} else {
LogPrintf("received invalid admin nonce %s\n", msg.ToString());
Misbehaving(pfrom->GetId(), 50);
}
}
} else {
LogPrint("net", "AlreadyHave admin nonce for admin ID 0x%08x\n", msg.nAdminId);
}
}
else if (strCommand == NetMsgType::SIGADMIN)
{
CAdminPartialSignature msg;
vRecv >> msg;
CInv inv(MSG_CHAIN_ADMIN_SIGNATURE, msg.GetHash());
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
pfrom->setAskFor.erase(inv.hash);
mapAlreadyAskedFor.erase(inv.hash);
if (!AlreadyHave(inv)) {
if (msg.hashRootBlock != chainActive.Tip()->GetBlockHash()) {
LogPrintf("received outdated admin signature from peer %d for tip %s signed by 0x%08x\n", pfrom->id, msg.hashRootBlock.ToString(), msg.nAdminId);
} else {
LogPrint("net", "received admin signature %s for tip %s\n", msg.GetHash().ToString(), msg.hashRootBlock.ToString());
if (AddAdminSignature(msg)) {
RelayAdminSignature(msg);
} else {
LogPrintf("received invalid admin signature data %s\n", msg.ToString());
}
}
} else {
LogPrint("net", "AlreadyHave admin sig %s\n", msg.hashRootBlock.ToString());
}
}
else if (strCommand == NetMsgType::TX)
{
// Stop processing the transaction early if
// We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
if (!fRelayTxes && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
{
LogPrint("net", "transaction sent in violation of protocol peer=%d\n", pfrom->id);
return true;
}
std::deque<COutPoint> vWorkQueue;
std::vector<uint256> vEraseQueue;
CTransactionRef ptx;
vRecv >> ptx;
const CTransaction& tx = *ptx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
bool fMissingInputs = false;
CValidationState state;
pfrom->setAskFor.erase(inv.hash);
mapAlreadyAskedFor.erase(inv.hash);
std::list<CTransactionRef> lRemovedTxn;
if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, ptx, true, &fMissingInputs, &lRemovedTxn)) {
mempool.check(pcoinsTip);
RelayTransaction(tx);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
vWorkQueue.emplace_back(inv.hash, i);
}
pfrom->nLastTXTime = GetTime();
LogPrint("mempool", "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
pfrom->id,
tx.GetHash().ToString(),
mempool.size(), mempool.DynamicMemoryUsage() / 1000);
// Recursively process any orphan transactions that depended on this one
std::set<NodeId> setMisbehaving;
while (!vWorkQueue.empty()) {
auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
vWorkQueue.pop_front();
if (itByPrev == mapOrphanTransactionsByPrev.end())
continue;
for (auto mi = itByPrev->second.begin();
mi != itByPrev->second.end();
++mi)
{
const CTransactionRef& porphanTx = (*mi)->second.tx;
const CTransaction& orphanTx = *porphanTx;
const uint256& orphanHash = orphanTx.GetHash();
NodeId fromPeer = (*mi)->second.fromPeer;
bool fMissingInputs2 = false;
// Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
// resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
// anyone relaying LegitTxX banned)
CValidationState stateDummy;
if (setMisbehaving.count(fromPeer))
continue;
if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, true, &fMissingInputs2, &lRemovedTxn)) {
LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
RelayTransaction(orphanTx);
for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
vWorkQueue.emplace_back(orphanHash, i);
}
vEraseQueue.push_back(orphanHash);
}
else if (!fMissingInputs2)
{
int nDos = 0;
if (stateDummy.IsInvalid(nDos) && nDos > 0)
{
// Punish peer that gave us an invalid orphan tx
Misbehaving(fromPeer, nDos);
setMisbehaving.insert(fromPeer);
LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
}
// Has inputs but not accepted to mempool
// Probably non-standard or insufficient fee/priority
LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
vEraseQueue.push_back(orphanHash);
if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
// Do not use rejection cache for witness transactions or
// witness-stripped transactions, as they can have been malleated.
// See https://github.com/bitcoin/bitcoin/issues/8279 for details.
assert(recentRejects);
recentRejects->insert(orphanHash);
}
}
mempool.check(pcoinsTip);
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
if (recentRejects->contains(txin.prevout.hash)) {
fRejectedParents = true;
break;
}
}
if (!fRejectedParents) {
uint32_t nFetchFlags = GetFetchFlags(pfrom, chainActive.Tip());
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
pfrom->AddInventoryKnown(_inv);
if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
}
AddOrphanTx(ptx, pfrom->GetId());
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
if (nEvicted > 0)
LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
} else {
LogPrint("mempool", "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
// We will continue to reject this tx since it has rejected
// parents so avoid re-requesting it from other peers.
recentRejects->insert(tx.GetHash());
}
} else {
if (!tx.HasWitness() && !state.CorruptionPossible()) {
// Do not use rejection cache for witness transactions or
// witness-stripped transactions, as they can have been malleated.
// See https://github.com/bitcoin/bitcoin/issues/8279 for details.
assert(recentRejects);
recentRejects->insert(tx.GetHash());
if (RecursiveDynamicUsage(*ptx) < 100000) {
AddToCompactExtraTransactions(ptx);
}
} else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
AddToCompactExtraTransactions(ptx);
}
if (pfrom->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
// Always relay transactions received from whitelisted peers, even
// if they were already in the mempool or rejected from it due
// to policy, allowing the node to function as a gateway for
// nodes hidden behind it.
//
// Never relay transactions that we would assign a non-zero DoS
// score for, as we expect peers to do the same with us in that
// case.
int nDoS = 0;
if (!state.IsInvalid(nDoS) || nDoS == 0) {
LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
RelayTransaction(tx);
} else {
LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->id, FormatStateMessage(state));
}
}
}
for (const CTransactionRef& removedTx : lRemovedTxn)
AddToCompactExtraTransactions(removedTx);
int nDoS = 0;
if (state.IsInvalid(nDoS))
{
LogPrint("mempoolrej", "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
pfrom->id,
FormatStateMessage(state));
if (state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
pfrom->PushMessage(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
if (nDoS > 0) {
Misbehaving(pfrom->GetId(), nDoS);
}
}
}
else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
{
std::vector<CBlockHeader> headers;
// Bypass the normal CBlock deserialization, as we don't want to risk deserializing 'MAX_HEADERS_RESULTS' full blocks.
unsigned int nCount = ReadCompactSize(vRecv);
if (nCount > MAX_HEADERS_RESULTS) {
Misbehaving(pfrom->GetId(), 20);
return error("headers message size = %u", nCount);
}
headers.resize(nCount);
for (unsigned int n = 0; n < nCount; n++)
vRecv >> headers[n];
LOCK(cs_main);
if (nCount == 0) {
// Nothing interesting. Stop asking this peers for more headers.
return true;
}
CBlockIndex *pindexLast = NULL;
BOOST_FOREACH(const CBlockHeader& header, headers) {
CValidationState state;
if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
Misbehaving(pfrom->GetId(), 20);
return error("non-continuous headers sequence: %s != %s", header.hashPrevBlock.ToString(), pindexLast->GetBlockHash().ToString());
}
if (!AcceptBlockHeader(header, state, chainparams, &pindexLast)) {
int nDoS;
if (state.IsInvalid(nDoS)) {
if (nDoS > 0)
Misbehaving(pfrom->GetId(), nDoS);
return error("invalid header received");
}
}
}
if (pindexLast)
UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
// Headers message had its maximum size; the peer may have more headers.
// TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
// from there instead.
LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256());
}
bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
CNodeState *nodestate = State(pfrom->GetId());
// If this set of headers is valid and ends in a block with at least as
// much work as our tip, download as much as possible.
if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
vector<CBlockIndex *> vToFetch;
CBlockIndex *pindexWalk = pindexLast;
// Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
!mapBlocksInFlight.count(pindexWalk->GetBlockHash())) {
// We don't have this block, and it's not yet in flight.
vToFetch.push_back(pindexWalk);
}
pindexWalk = pindexWalk->pprev;
}
// If pindexWalk still isn't on our main chain, we're looking at a
// very large reorg at a time we think we're close to caught up to
// the main chain -- this shouldn't really happen. Bail out on the
// direct fetch and rely on parallel download instead.
if (!chainActive.Contains(pindexWalk)) {
LogPrint("net", "Large reorg, won't direct fetch to %s (%d)\n",
pindexLast->GetBlockHash().ToString(),
pindexLast->nHeight);
} else {
vector<CInv> vGetData;
// Download as much as possible, from earliest to latest.
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vToFetch) {
if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
// Can't download any more from this peer
break;
}
vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex);
LogPrint("net", "Requesting block %s from peer=%d\n",
pindex->GetBlockHash().ToString(), pfrom->id);
}
if (vGetData.size() > 1) {
LogPrint("net", "Downloading blocks toward %s (%d) via headers direct fetch\n",
pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
}
if (vGetData.size() > 0) {
pfrom->PushMessage(NetMsgType::GETDATA, vGetData);
}
}
}
CheckBlockIndex(chainparams.GetConsensus());
}
else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
{
CBlock block;
vRecv >> block;
CInv inv(MSG_BLOCK, block.GetHash());
LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
pfrom->AddInventoryKnown(inv);
CValidationState state;
// Process all blocks from whitelisted peers, even if not requested,
// unless we're still syncing with the network.
// Such an unrequested block may still be processed, subject to the
// conditions in AcceptBlock().
bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
ProcessNewBlock(state, chainparams, pfrom, &block, forceProcessing, NULL);
int nDoS;
if (state.IsInvalid(nDoS)) {
assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
pfrom->PushMessage(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
if (nDoS > 0) {
LOCK(cs_main);
Misbehaving(pfrom->GetId(), nDoS);
}
}
}
else if (strCommand == NetMsgType::GETADDR)
{
// This asymmetric behavior for inbound and outbound connections was introduced
// to prevent a fingerprinting attack: an attacker can send specific fake addresses
// to users' AddrMan and later request them by sending getaddr messages.
// Making nodes which are behind NAT and can only make outgoing connections ignore
// the getaddr message mitigates the attack.
if (!pfrom->fInbound) {
LogPrint("net", "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->id);
return true;
}
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == NetMsgType::MEMPOOL)
{
if (CNode::OutboundTargetReached(false) && !pfrom->fWhitelisted)
{
LogPrint("net", "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
pfrom->fDisconnect = true;
return true;
}
LOCK(pfrom->cs_inventory);
pfrom->fSendMempool = true;
}
else if (strCommand == NetMsgType::PING)
{
uint64_t nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage(NetMsgType::PONG, nonce);
}
else if (strCommand == NetMsgType::PONG)
{
int64_t pingUsecEnd = nTimeReceived;
uint64_t nonce = 0;
size_t nAvail = vRecv.in_avail();
bool bPingFinished = false;
std::string sProblem;
if (nAvail >= sizeof(nonce)) {
vRecv >> nonce;
// Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
if (pfrom->nPingNonceSent != 0) {
if (nonce == pfrom->nPingNonceSent) {
// Matching pong received, this ping is no longer outstanding
bPingFinished = true;
int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
if (pingUsecTime > 0) {
// Successful ping time measurement, replace previous
pfrom->nPingUsecTime = pingUsecTime;
pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
} else {
// This should never happen
sProblem = "Timing mishap";
}
} else {
// Nonce mismatches are normal when pings are overlapping
sProblem = "Nonce mismatch";
if (nonce == 0) {
// This is most likely a bug in another implementation somewhere; cancel this ping
bPingFinished = true;
sProblem = "Nonce zero";
}
}
} else {
sProblem = "Unsolicited pong without ping";
}
} else {
// This is most likely a bug in another implementation somewhere; cancel this ping
bPingFinished = true;
sProblem = "Short payload";
}
if (!(sProblem.empty())) {
LogPrint("net", "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
pfrom->id,
sProblem,
pfrom->nPingNonceSent,
nonce,
nAvail);
}
if (bPingFinished) {
pfrom->nPingNonceSent = 0;
}
}
else if (fAlerts && strCommand == NetMsgType::ALERT)
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert(chainparams.AlertKey()))
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
Misbehaving(pfrom->GetId(), 10);
}
}
}
else if (strCommand == NetMsgType::FILTERLOAD)
{
CBloomFilter filter;
vRecv >> filter;
LOCK(pfrom->cs_filter);
if (!filter.IsWithinSizeConstraints())
// There is no excuse for sending a too-large filter
Misbehaving(pfrom->GetId(), 100);
else
{
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter(filter);
pfrom->pfilter->UpdateEmptyFull();
}
pfrom->fRelayTxes = true;
}
else if (strCommand == NetMsgType::FILTERADD)
{
vector<unsigned char> vData;
vRecv >> vData;
// Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
// and thus, the maximum size any matched object can have) in a filteradd message
if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
Misbehaving(pfrom->GetId(), 100);
} else {
LOCK(pfrom->cs_filter);
if (pfrom->pfilter)
pfrom->pfilter->insert(vData);
else
Misbehaving(pfrom->GetId(), 100);
}
}
else if (strCommand == NetMsgType::FILTERCLEAR)
{
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter();
pfrom->fRelayTxes = true;
}
else if (strCommand == NetMsgType::REJECT)
{
if (fDebug) {
try {
string strMsg; unsigned char ccode; string strReason;
vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
ostringstream ss;
ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
{
uint256 hash;
vRecv >> hash;
ss << ": hash " << hash.ToString();
}
LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
} catch (const std::ios_base::failure&) {
// Avoid feedback loops by preventing reject messages from triggering a new reject message.
LogPrint("net", "Unparseable reject message received\n");
}
}
}
else
{
// Ignore unknown commands for extensibility
LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
}
return true;
}
// requires LOCK(cs_vRecvMsg)
bool ProcessMessages(CNode* pfrom)
{
const CChainParams& chainparams = Params();
//if (fDebug)
// LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
bool fOk = true;
if (!pfrom->vRecvGetData.empty())
ProcessGetData(pfrom, chainparams.GetConsensus());
// this maintains the order of responses
if (!pfrom->vRecvGetData.empty()) return fOk;
std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
// get next message
CNetMessage& msg = *it;
//if (fDebug)
// LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
// msg.hdr.nMessageSize, msg.vRecv.size(),
// msg.complete() ? "Y" : "N");
// end, if an incomplete message is found
if (!msg.complete())
break;
// at this point, any failure means we can delete the current message
it++;
// Scan for message start
if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), MESSAGE_START_SIZE) != 0) {
LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
fOk = false;
break;
}
// Read header
CMessageHeader& hdr = msg.hdr;
if (!hdr.IsValid(chainparams.MessageStart()))
{
LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
// Checksum
CDataStream& vRecv = msg.vRecv;
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
if (nChecksum != hdr.nChecksum)
{
LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Process message
bool fRet = false;
try
{
fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams);
boost::this_thread::interruption_point();
}
catch (const std::ios_base::failure& e)
{
pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, string("error parsing message"));
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
LogPrintf("%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
break;
}
// In case the connection got shut down, its receive buffer was wiped
if (!pfrom->fDisconnect)
pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
return fOk;
}
class CompareInvMempoolOrder
{
CTxMemPool *mp;
public:
CompareInvMempoolOrder(CTxMemPool *mempool)
{
mp = mempool;
}
bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
{
/* As std::make_heap produces a max-heap, we want the entries with the
* fewest ancestors/highest fee to sort later. */
return mp->CompareDepthAndScore(*b, *a);
}
};
bool SendMessages(CNode* pto)
{
const Consensus::Params& consensusParams = Params().GetConsensus();
{
// Don't send anything until we get its version message
if (pto->nVersion == 0)
return true;
//
// Message: ping
//
bool pingSend = false;
if (pto->fPingQueued) {
// RPC ping request by user
pingSend = true;
}
if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
// Ping automatically sent as a latency probe & keepalive.
pingSend = true;
}
if (pingSend) {
uint64_t nonce = 0;
while (nonce == 0) {
GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
}
pto->fPingQueued = false;
pto->nPingUsecStart = GetTimeMicros();
pto->nPingNonceSent = nonce;
pto->PushMessage(NetMsgType::PING, nonce);
}
TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
if (!lockMain)
return true;
// Address refresh broadcast
int64_t nNow = GetTimeMicros();
if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
AdvertizeLocal(pto);
pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
}
//
// Message: addr
//
if (pto->nNextAddrSend < nNow) {
pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
if (!pto->addrKnown.contains(addr.GetKey()))
{
pto->addrKnown.insert(addr.GetKey());
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage(NetMsgType::ADDR, vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage(NetMsgType::ADDR, vAddr);
}
CNodeState &state = *State(pto->GetId());
if (state.fShouldBan) {
if (pto->fWhitelisted)
LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
else {
pto->fDisconnect = true;
if (pto->addr.IsLocal())
LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
else
{
CNode::Ban(pto->addr, BanReasonNodeMisbehaving);
}
}
state.fShouldBan = false;
}
BOOST_FOREACH(const CBlockReject& reject, state.rejects)
pto->PushMessage(NetMsgType::REJECT, (string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
state.rejects.clear();
// Start block sync
if (pindexBestHeader == NULL)
pindexBestHeader = chainActive.Tip();
bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
// Only actively request headers from a single peer, unless we're close to today.
if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
state.fSyncStarted = true;
nSyncStarted++;
const CBlockIndex *pindexStart = pindexBestHeader;
/* If possible, start at the block preceding the currently
best known header. This ensures that we always get a
non-empty list of headers back as long as the peer
is up-to-date. With a non-empty response, we can initialise
the peer's known best block. This wouldn't be possible
if we requested starting at pindexBestHeader and
got back an empty response. */
if (pindexStart->pprev)
pindexStart = pindexStart->pprev;
LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
pto->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256());
}
}
// Resend wallet transactions that haven't gotten in a block yet
// Except during reindex, importing and IBD, when old wallet
// transactions become unconfirmed and spams other nodes.
if (!fReindex && !fImporting && !IsInitialBlockDownload())
{
GetMainSignals().Broadcast(nTimeBestReceived);
}
//
// Try sending block announcements via headers
//
{
// If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
// list of block hashes we're relaying, and our peer wants
// headers announcements, then find the first header
// not yet known to our peer but would connect, and send.
// If no header would connect, or if we have too many
// blocks, or if the peer doesn't want headers, just
// add all to the inv queue.
LOCK(pto->cs_inventory);
vector<CBlockHeader> vHeaders;
bool fRevertToInv = (!state.fPreferHeaders || pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
CBlockIndex *pBestIndex = NULL; // last header queued for delivery
ProcessBlockAvailability(pto->id); // ensure pindexBestKnownBlock is up-to-date
if (!fRevertToInv) {
bool fFoundStartingHeader = false;
// Try to find first header that our peer doesn't have, and
// then send all headers past that one. If we come across any
// headers that aren't on chainActive, give up.
BOOST_FOREACH(const uint256 &hash, pto->vBlockHashesToAnnounce) {
BlockMap::iterator mi = mapBlockIndex.find(hash);
assert(mi != mapBlockIndex.end());
CBlockIndex *pindex = mi->second;
if (chainActive[pindex->nHeight] != pindex) {
// Bail out if we reorged away from this block
fRevertToInv = true;
break;
}
if (pBestIndex != NULL && pindex->pprev != pBestIndex) {
// This means that the list of blocks to announce don't
// connect to each other.
// This shouldn't really be possible to hit during
// regular operation (because reorgs should take us to
// a chain that has some block not on the prior chain,
// which should be caught by the prior check), but one
// way this could happen is by using invalidateblock /
// reconsiderblock repeatedly on the tip, causing it to
// be added multiple times to vBlockHashesToAnnounce.
// Robustly deal with this rare situation by reverting
// to an inv.
fRevertToInv = true;
break;
}
pBestIndex = pindex;
if (fFoundStartingHeader) {
// add this to the headers message
vHeaders.push_back(pindex->GetBlockHeader());
} else if (PeerHasHeader(&state, pindex)) {
continue; // keep looking for the first new block
} else if (pindex->pprev == NULL || PeerHasHeader(&state, pindex->pprev)) {
// Peer doesn't have this header but they do have the prior one.
// Start sending headers.
fFoundStartingHeader = true;
vHeaders.push_back(pindex->GetBlockHeader());
} else {
// Peer doesn't have this header or the prior one -- nothing will
// connect, so bail out.
fRevertToInv = true;
break;
}
}
}
if (fRevertToInv) {
// If falling back to using an inv, just try to inv the tip.
// The last entry in vBlockHashesToAnnounce was our tip at some point
// in the past.
if (!pto->vBlockHashesToAnnounce.empty()) {
const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
assert(mi != mapBlockIndex.end());
CBlockIndex *pindex = mi->second;
// Warn if we're announcing a block that is not on the main chain.
// This should be very rare and could be optimized out.
// Just log for now.
if (chainActive[pindex->nHeight] != pindex) {
LogPrint("net", "Announcing block %s not on main chain (tip=%s)\n",
hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
}
// If the peer announced this block to us, don't inv it back.
// (Since block announcements may not be via inv's, we can't solely rely on
// setInventoryKnown to track this.)
if (!PeerHasHeader(&state, pindex)) {
pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
LogPrint("net", "%s: sending inv peer=%d hash=%s\n", __func__,
pto->id, hashToAnnounce.ToString());
}
}
} else if (!vHeaders.empty()) {
if (vHeaders.size() > 1) {
LogPrint("net", "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
vHeaders.size(),
vHeaders.front().GetHash().ToString(),
vHeaders.back().GetHash().ToString(), pto->id);
} else {
LogPrint("net", "%s: sending header %s to peer=%d\n", __func__,
vHeaders.front().GetHash().ToString(), pto->id);
}
pto->PushMessage(NetMsgType::HEADERS, vHeaders);
state.pindexBestHeaderSent = pBestIndex;
}
pto->vBlockHashesToAnnounce.clear();
}
//
// Message: inventory
//
vector<CInv> vInv;
{
LOCK(pto->cs_inventory);
vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
// Add blocks
BOOST_FOREACH(const uint256& hash, pto->vInventoryBlockToSend) {
vInv.push_back(CInv(MSG_BLOCK, hash));
if (vInv.size() == MAX_INV_SZ) {
pto->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
pto->vInventoryBlockToSend.clear();
// Check whether periodic sends should happen
bool fSendTrickle = pto->fWhitelisted;
if (pto->nNextInvSend < nNow) {
fSendTrickle = true;
// Use half the delay for outbound peers, as there is less privacy concern for them.
pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
}
// Time to send but the peer has requested we not relay transactions.
if (fSendTrickle) {
LOCK(pto->cs_filter);
if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
}
// Respond to BIP35 mempool requests
if (fSendTrickle && pto->fSendMempool) {
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
pto->fSendMempool = false;
LOCK(pto->cs_filter);
BOOST_FOREACH(const uint256& hash, vtxid) {
CInv inv(MSG_TX, hash);
pto->setInventoryTxToSend.erase(hash);
if (pto->pfilter) {
CTransaction tx;
bool fInMemPool = mempool.lookup(hash, tx);
if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
if (!pto->pfilter->IsRelevantAndUpdate(tx)) continue;
}
pto->filterInventoryKnown.insert(hash);
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
pto->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
}
// Determine transactions to relay
if (fSendTrickle) {
// Produce a vector with all candidates for sending
vector<std::set<uint256>::iterator> vInvTx;
vInvTx.reserve(pto->setInventoryTxToSend.size());
for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
vInvTx.push_back(it);
}
// Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
// A heap is used so that not all items need sorting if only a few are being sent.
CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
// No reason to drain out at many times the network's capacity,
// especially since we have many peers and some will draw much shorter delays.
unsigned int nRelayedTransactions = 0;
LOCK(pto->cs_filter);
while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
// Fetch the top element from the heap
std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
std::set<uint256>::iterator it = vInvTx.back();
vInvTx.pop_back();
uint256 hash = *it;
// Remove it from the to-be-sent set
pto->setInventoryTxToSend.erase(it);
// Check if not in the filter already
if (pto->filterInventoryKnown.contains(hash)) {
continue;
}
CTransaction tx;
if (!mempool.lookup(hash, tx)) continue;
if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(tx)) continue;
// Send
vInv.push_back(CInv(MSG_TX, hash));
nRelayedTransactions++;
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) {
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
bool ret = mapRelay.insert(std::make_pair(hash, tx)).second;
if (ret) {
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, hash));
}
}
if (vInv.size() == MAX_INV_SZ) {
pto->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
pto->filterInventoryKnown.insert(hash);
}
}
//
// Handle: PoC public nonces
//
const uint256& hashTip = chainActive.Tip()->GetBlockHash();
BOOST_FOREACH(const uint256& hash, pto->vInventoryNoncePoolsToSend) {
map<uint256, CNoncePool>::iterator mi = mapRelayNonces.find(hash);
if (mi != mapRelayNonces.end()) {
CInv inv(MSG_CVN_PUB_NONCE_POOL, hash);
{
LOCK(cs_mapRelayNonces);
// Expire old relay messages
while (!vRelayExpirationNonces.empty() && vRelayExpirationNonces.front().first < GetTime()) {
mapRelayNonces.erase(vRelayExpirationNonces.front().second);
vRelayExpirationNonces.pop_front();
}
// we keep them around for 5h so AlreadyHave() works properly
vRelayExpirationNonces.push_back(std::make_pair(GetTime() + 18000, inv.hash));
}
const CNoncePool& p = mi->second;
const uint32_t nPoolAge = GetPoolAge(p, chainActive.Tip());
// we do not relay expired nonce pools
if (nPoolAge < p.vPublicNonces.size()) {
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
pto->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
}
}
pto->vInventoryNoncePoolsToSend.clear();
//
// Handle: PoC chain signatures
//
BOOST_FOREACH(const uint256& hash, pto->vInventoryChainSignaturesToSend) {
map<uint256, CCvnPartialSignature>::iterator mi = mapRelaySigs.find(hash);
if (mi != mapRelaySigs.end()) {
CInv inv(MSG_CVN_SIGNATURE, hash);
{
LOCK(cs_mapRelaySigs);
// Expire old relay messages
while (!vRelayExpirationSigs.empty() && vRelayExpirationSigs.front().first < GetTime()) {
mapRelaySigs.erase(vRelayExpirationSigs.front().second);
vRelayExpirationSigs.pop_front();
}
// we keep them around for 30min so AlreadyHave() works properly
vRelayExpirationSigs.push_back(std::make_pair(GetTime() + 1800, inv.hash));
}
const CCvnPartialSignature& sig = mi->second;
// we only relay signatures for the active chain tip
if (sig.hashPrevBlock == hashTip) {
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
pto->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
}
}
pto->vInventoryChainSignaturesToSend.clear();
//
// Handle: chain admin public nonces
//
BOOST_FOREACH(const uint256& hash, pto->vInventoryAdminNoncesToSend) {
map<uint256, CAdminNonce>::iterator mi = mapRelayAdminNonces.find(hash);
if (mi != mapRelayAdminNonces.end()) {
CInv inv(MSG_CHAIN_ADMIN_NONCE, hash);
{
LOCK(cs_mapRelayAdminNonces);
// Expire old relay messages
while (!vRelayExpirationAdminNonces.empty() && vRelayExpirationAdminNonces.front().first < GetTime()) {
mapRelayAdminNonces.erase(vRelayExpirationAdminNonces.front().second);
vRelayExpirationAdminNonces.pop_front();
}
// we keep them around for 30min so AlreadyHave() works properly
vRelayExpirationAdminNonces.push_back(std::make_pair(GetTime() + 1800, inv.hash));
}
const CAdminNonce& nonce = mi->second;
// we only relay signatures for the active chain tip
if (nonce.hashRootBlock == hashTip) {
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
pto->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
}
}
pto->vInventoryAdminNoncesToSend.clear();
//
// Handle: chain admin signatures
//
BOOST_FOREACH(const uint256& hash, pto->vInventoryAdminSignaturesToSend) {
map<uint256, CAdminPartialSignature>::iterator mi = mapRelayAdminSigs.find(hash);
if (mi != mapRelayAdminSigs.end()) {
CInv inv(MSG_CHAIN_ADMIN_SIGNATURE, hash);
{
LOCK(cs_mapRelayAdminSigs);
// Expire old relay messages
while (!vRelayExpirationAdminSigs.empty() && vRelayExpirationAdminSigs.front().first < GetTime()) {
mapRelayAdminSigs.erase(vRelayExpirationAdminSigs.front().second);
vRelayExpirationAdminSigs.pop_front();
}
// we keep them around for 30min so AlreadyHave() works properly
vRelayExpirationAdminSigs.push_back(std::make_pair(GetTime() + 1800, inv.hash));
}
const CAdminPartialSignature& sig = mi->second;
// we only relay signatures for the active chain tip
if (sig.hashRootBlock == hashTip) {
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
pto->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
}
}
pto->vInventoryAdminSignaturesToSend.clear();
//
// Handle: PoC chain data
//
BOOST_FOREACH(const uint256& hash, pto->vInventoryChainDataToSend) {
map<uint256, CChainDataMsg>::iterator mi = mapRelayChainData.find(hash);
if (mi != mapRelayChainData.end()) {
CInv inv(MSG_POC_CHAIN_DATA, hash);
{
LOCK(cs_mapRelayChainData);
// Expire old relay messages
while (!vRelayExpirationChainData.empty() && vRelayExpirationChainData.front().first < GetTime()) {
mapRelayChainData.erase(vRelayExpirationChainData.front().second);
vRelayExpirationChainData.pop_front();
}
vRelayExpirationChainData.push_back(std::make_pair(GetTime() + dynParams.nBlockSpacing, inv.hash));
}
const CChainDataMsg& chainData = mi->second;
// we only relay chain data for the active chain tip
if (chainData.hashPrevBlock == hashTip) {
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
pto->PushMessage(NetMsgType::INV, vInv);
vInv.clear();
}
}
}
}
pto->vInventoryChainDataToSend.clear();
}
if (!vInv.empty())
pto->PushMessage(NetMsgType::INV, vInv);
// Detect whether we're stalling
nNow = GetTimeMicros();
if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
// Stalling only triggers when the block download window cannot move. During normal steady state,
// the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
// should only happen during initial block download.
LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
pto->fDisconnect = true;
}
// In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
// (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
// We compensate for other peers to prevent killing off peers due to our own downstream link
// being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
// to unreasonably increase our timeout.
if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
if (nNow > state.nDownloadingSince + dynParams.nBlockSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
pto->fDisconnect = true;
}
}
//
// Message: getdata (blocks)
//
vector<CInv> vGetData;
if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
vector<CBlockIndex*> vToDownload;
NodeId staller = -1;
FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
pindex->nHeight, pto->id);
}
if (state.nBlocksInFlight == 0 && staller != -1) {
if (State(staller)->nStallingSince == 0) {
State(staller)->nStallingSince = nNow;
LogPrint("net", "Stall started peer=%d\n", staller);
}
}
}
//
// Message: getdata (non-blocks)
//
while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(inv))
{
if (fDebug)
LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage(NetMsgType::GETDATA, vGetData);
vGetData.clear();
}
} else {
//If we're not going to ask, don't expect a response.
pto->setAskFor.erase(inv.hash);
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage(NetMsgType::GETDATA, vGetData);
}
return true;
}
std::string CBlockFileInfo::ToString() const {
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
}
class CMainCleanup
{
public:
CMainCleanup() {}
~CMainCleanup() {
// block headers
BlockMap::iterator it1 = mapBlockIndex.begin();
for (; it1 != mapBlockIndex.end(); it1++)
delete (*it1).second;
mapBlockIndex.clear();
// orphan transactions
mapOrphanTransactions.clear();
mapOrphanTransactionsByPrev.clear();
}
} instance_of_cmaincleanup;
| [
"maxtvstream@live.com"
] | maxtvstream@live.com |
60adaf079559383dd57e437b107969667a8ca23a | f2339e85157027dada17fadd67c163ecb8627909 | /Framework/Framework/src/WorkThread.h | adf5a8f399c3d8be9d075a0f5bb1162bf340696d | [] | no_license | fynbntl/Titan | 7ed8869377676b4c5b96df953570d9b4c4b9b102 | b069b7a2d90f4d67c072e7c96fe341a18fedcfe7 | refs/heads/master | 2021-09-01T22:52:37.516407 | 2017-12-29T01:59:29 | 2017-12-29T01:59:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,541 | h | /*******************************************************************
** 文件名: WorkThread.h
** 版 权: (C) 深圳冰川网络技术有限公司 2008 - All Rights Reserved
** 创建人: 陈涛 (Carl Chen)
** 日 期: 11/10/2014
** 版 本: 1.0
** 描 述: 工作线程
********************************************************************/
#pragma once
#include "Thread.h"
#include "IServiceContainer.h"
#include "net/producer_consumer_queue.h"
#include "Net/Reactor.h"
#include "Net/AsynIoFrame.h"
#include <set>
using namespace rkt;
struct ICoroutine;
/**
工作线程:
1.逐个调用分配到该工作线程上的服务的消息处理函数
*/
class WorkThread : public IRunnable,public EventHandler
{
protected:
producer_consumer_queue<SERVICE_PTR> m_add_queue;
producer_consumer_queue<SERVICE_PTR> m_remove_queue;
std::set<SERVICE_PTR> m_service_list;
int m_thread_id; // 当前线程ID
unsigned long m_nResponseTime; // 工作线程响应时间,用来判断是否忙碌
bool m_bAutoRun; // 是自动运行,还是由外部驱动
Reactor * m_pReactor; // 线程反应器,只有事件触发时才工作
FastEvent m_event; // 驱动工作线程的事件
std::map<int, std::list<ICoroutine*>> m_co_free_list; // 空闲协程列表
int m_nCoCount;
// for test
bool m_bSendPerformance;
WorkThread() : m_thread_id(0),m_bAutoRun(false),m_nResponseTime(0),m_pReactor(0),m_bSendPerformance(false),m_nCoCount(0){}
public:
WorkThread( int id,bool bAutoRun) : m_thread_id(id),m_bAutoRun(bAutoRun),m_nResponseTime(0),m_pReactor(0),m_bSendPerformance(false),m_nCoCount(0)
{
}
virtual ~WorkThread()
{
if ( m_pReactor )
{
m_pReactor->Release();
m_pReactor = 0;
}
}
virtual void OnEvent( HANDLE event );
// for test
std::set<SERVICE_PTR> & get_list() { return m_service_list; }
// 添加一个服务到这个工作线程上
void add( SERVICE_PTR pService )
{
m_add_queue.push(pService);
#ifdef SUPPORT_NET_NAMEINF
m_add_queue.setName(pService->get_scheme().scheme->name);
#endif
m_event.setEvent();
}
// 从该工作线程移除一个服务
void remove( SERVICE_PTR pService )
{
m_remove_queue.push(pService);
#ifdef SUPPORT_NET_NAMEINF
m_remove_queue.setName(pService->get_scheme().scheme->name);
#endif
// 这行代码纯粹是因为producer_consumer_queue的特殊实现方式而加的
// 因为producer_consumer_queue总是会保留最后一个节点的引用
SERVICE_PTR ptr = SERVICE_PTR(0);
m_remove_queue.push(ptr);
m_event.setEvent();
}
// 手动驱动工作线程工作
void work()
{
::ConvertThreadToFiber(this);
OnEvent(0);
ConvertFiberToThread();
}
// 取得响应时间,用来判断线程是否忙碌
unsigned long get_response_time()
{
return m_nResponseTime;
}
virtual void run();
virtual void release();
Reactor* get_reactor(){return m_pReactor;}
void send_report_performance_cmd();
// 分配一个可用协程
ICoroutine* allot_co(int nStackSize = 32 * 1024);
// 交还一个协程,如果别的服务器需要运行,再从这里取
void revert_co(ICoroutine* pCo);
// 获取当前线程权重数
unsigned int get_evaluate_score();
private:
void report_performance();
}; | [
"85789685@qq.com"
] | 85789685@qq.com |
8089089bae13124239a87541340655543b862b25 | beaef70fffb6668549da7191ebea16ab4e5ba4f0 | /Olympiad/POI/POI 09-Walk.cpp | 35275416a489d6aef6b0339f73c0151d68098b36 | [] | no_license | QuickSorting/CompetitiveProgramming | fe57922f1ab3d8ee3e066ff8b68fd217eacf6f3c | 9120d7971425f263ba7bd2eb75f86c479a913839 | refs/heads/master | 2021-12-27T19:38:03.477901 | 2021-12-13T17:55:36 | 2021-12-13T17:55:36 | 202,154,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,613 | cpp | /*
Used the tutorial
*/
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 407;
const int MAX_M = 60007;
const int MAX_A = 27;
const int MAX_NODES = MAX_N * MAX_N * MAX_A;
int n, m;
inline int to_idx(int u, int v, int c){
return (u - 1) * MAX_N * MAX_A + (v - 1) * MAX_A + c;
}
pair<int, int> from_idx(int idx){
pair<int, int> ret;
ret.first = idx / MAX_N / MAX_A;
ret.second = (idx / MAX_A) % MAX_N;
++ret.first;
++ret.second;
return ret;
}
inline int idx_char(int idx){
return idx % MAX_A;
}
int a[MAX_N];
vector<pair<int, int> > adj1[MAX_N], adj2[MAX_N];
vector<int> en0, en1;
bool used[MAX_NODES];
int par[MAX_NODES];
map<pair<int, int>, int> mp;
queue<int> q;
int main(){
scanf("%d %d", &n, &m);
for(int i = 0; i < m; ++i){
int u, v;
char c;
scanf("%d %d %c", &u, &v, &c);
c -= 'a';
en1.push_back(to_idx(u, v, 26));
mp[{u, v}] = c;
adj1[v].push_back({u, c});
adj2[u].push_back({v, c});
}
for(int u = 1; u <= n; ++u){
en0.push_back(to_idx(u, u, 26));
}
for(int i = 1; i < MAX_NODES; ++i){
par[i] = -2;
}
for(int x: en0){
q.push(x);
used[x] = true;
par[x] = -1;
}
while(!q.empty()){
int x = q.front();
q.pop();
if(x == en0.back()){
for(int y: en1){
q.push(y);
used[y] = true;
par[y] = -1;
}
}
pair<int, int> pos = from_idx(x);
int curr_ch = idx_char(x);
if(curr_ch == 26){
for(pair<int, int> to: adj1[pos.first]){
int tidx = to_idx(to.first, pos.second, to.second);
if(used[tidx]){
continue;
}
par[tidx] = x;
used[tidx] = true;
q.push(tidx);
}
}
else{
for(pair<int, int> to: adj2[pos.second]){
int tidx = to_idx(pos.first, to.first, 26);
if(to.second != curr_ch || used[tidx]){
continue;
}
par[tidx] = x;
used[tidx] = true;
q.push(tidx);
}
}
}
int d;
cin >> d;
for(int i = 0; i < d; ++i){
cin >> a[i];
}
for(int i = 1; i < d; ++i){
string s1 = "";
string s2 = "";
int curr = to_idx(a[i - 1], a[i], 26);
if(par[curr] == -2){
printf("-1\n");
//cout << "-1\n";
continue;
}
while(par[curr] != -1){
if(idx_char(curr) == 26){
s1 += (char)(idx_char(par[curr]) + 'a');
}
else{
s2 += (char)(idx_char(curr) + 'a');
}
curr = par[curr];
}
string ans = s1;
pair<int, int> pos = from_idx(curr);
if(pos.first != pos.second){
ans += (char)('a' + mp[pos]);
}
reverse(s2.begin(), s2.end());
ans += s2;
//cout << ans.size() << " " << ans << "\n";
printf("%d ", (int)ans.size());
for(char c: ans){
printf("%c", c);
}
printf("\n");
}
return 0;
} | [
""
] | |
4650f20ca5723310f3a3b7929fd77d941248bc60 | 8567438779e6af0754620a25d379c348e4cd5a5d | /cc/output/renderer_pixeltest.cc | 93aa2d84caf86890232568f0d8d4a88c3716fc8a | [
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 137,890 | cc | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/message_loop/message_loop.h"
#include "cc/base/math_util.h"
#include "cc/output/gl_renderer.h"
#include "cc/paint/paint_canvas.h"
#include "cc/paint/paint_flags.h"
#include "cc/quads/draw_quad.h"
#include "cc/quads/picture_draw_quad.h"
#include "cc/quads/texture_draw_quad.h"
#include "cc/resources/video_resource_updater.h"
#include "cc/test/fake_raster_source.h"
#include "cc/test/fake_recording_source.h"
#include "cc/test/pixel_test.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "media/base/video_frame.h"
#include "third_party/skia/include/core/SkColorPriv.h"
#include "third_party/skia/include/core/SkImageFilter.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/effects/SkColorFilterImageFilter.h"
#include "third_party/skia/include/effects/SkColorMatrixFilter.h"
#include "ui/gfx/geometry/rect_conversions.h"
using gpu::gles2::GLES2Interface;
namespace cc {
namespace {
#if !defined(OS_ANDROID)
std::unique_ptr<RenderPass> CreateTestRootRenderPass(int id,
const gfx::Rect& rect) {
std::unique_ptr<RenderPass> pass = RenderPass::Create();
const gfx::Rect output_rect = rect;
const gfx::Rect damage_rect = rect;
const gfx::Transform transform_to_root_target;
pass->SetNew(id, output_rect, damage_rect, transform_to_root_target);
return pass;
}
std::unique_ptr<RenderPass> CreateTestRenderPass(
int id,
const gfx::Rect& rect,
const gfx::Transform& transform_to_root_target) {
std::unique_ptr<RenderPass> pass = RenderPass::Create();
const gfx::Rect output_rect = rect;
const gfx::Rect damage_rect = rect;
pass->SetNew(id, output_rect, damage_rect, transform_to_root_target);
return pass;
}
SharedQuadState* CreateTestSharedQuadState(
gfx::Transform quad_to_target_transform,
const gfx::Rect& rect,
RenderPass* render_pass) {
const gfx::Size layer_bounds = rect.size();
const gfx::Rect visible_layer_rect = rect;
const gfx::Rect clip_rect = rect;
const bool is_clipped = false;
const float opacity = 1.0f;
const SkBlendMode blend_mode = SkBlendMode::kSrcOver;
int sorting_context_id = 0;
SharedQuadState* shared_state = render_pass->CreateAndAppendSharedQuadState();
shared_state->SetAll(quad_to_target_transform, layer_bounds,
visible_layer_rect, clip_rect, is_clipped, opacity,
blend_mode, sorting_context_id);
return shared_state;
}
SharedQuadState* CreateTestSharedQuadStateClipped(
gfx::Transform quad_to_target_transform,
const gfx::Rect& rect,
const gfx::Rect& clip_rect,
RenderPass* render_pass) {
const gfx::Size layer_bounds = rect.size();
const gfx::Rect visible_layer_rect = clip_rect;
const bool is_clipped = true;
const float opacity = 1.0f;
const SkBlendMode blend_mode = SkBlendMode::kSrcOver;
int sorting_context_id = 0;
SharedQuadState* shared_state = render_pass->CreateAndAppendSharedQuadState();
shared_state->SetAll(quad_to_target_transform, layer_bounds,
visible_layer_rect, clip_rect, is_clipped, opacity,
blend_mode, sorting_context_id);
return shared_state;
}
void CreateTestRenderPassDrawQuad(const SharedQuadState* shared_state,
const gfx::Rect& rect,
int pass_id,
RenderPass* render_pass) {
RenderPassDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
quad->SetNew(shared_state, rect, rect, pass_id,
0, // mask_resource_id
gfx::RectF(), // mask_uv_rect
gfx::Size(), // mask_texture_size
gfx::Vector2dF(), // filters scale
gfx::PointF(), // filter origin
gfx::RectF()); // tex_coord_rect
}
void CreateTestTwoColoredTextureDrawQuad(const gfx::Rect& rect,
SkColor texel_color,
SkColor texel_stripe_color,
SkColor background_color,
bool premultiplied_alpha,
const SharedQuadState* shared_state,
ResourceProvider* resource_provider,
RenderPass* render_pass) {
SkPMColor pixel_color = premultiplied_alpha
? SkPreMultiplyColor(texel_color)
: SkPackARGB32NoCheck(SkColorGetA(texel_color),
SkColorGetR(texel_color),
SkColorGetG(texel_color),
SkColorGetB(texel_color));
SkPMColor pixel_stripe_color =
premultiplied_alpha
? SkPreMultiplyColor(texel_stripe_color)
: SkPackARGB32NoCheck(SkColorGetA(texel_stripe_color),
SkColorGetR(texel_stripe_color),
SkColorGetG(texel_stripe_color),
SkColorGetB(texel_stripe_color));
std::vector<uint32_t> pixels(rect.size().GetArea(), pixel_color);
for (int i = rect.height() / 4; i < (rect.height() * 3 / 4); ++i) {
for (int k = rect.width() / 4; k < (rect.width() * 3 / 4); ++k) {
pixels[i * rect.width() + k] = pixel_stripe_color;
}
}
ResourceId resource = resource_provider->CreateResource(
rect.size(), ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888,
gfx::ColorSpace());
resource_provider->CopyToResource(
resource, reinterpret_cast<uint8_t*>(&pixels.front()), rect.size());
float vertex_opacity[4] = {1.0f, 1.0f, 1.0f, 1.0f};
const gfx::PointF uv_top_left(0.0f, 0.0f);
const gfx::PointF uv_bottom_right(1.0f, 1.0f);
const bool flipped = false;
const bool nearest_neighbor = false;
TextureDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
quad->SetNew(shared_state, rect, gfx::Rect(), rect, resource,
premultiplied_alpha, uv_top_left, uv_bottom_right,
background_color, vertex_opacity, flipped, nearest_neighbor,
false);
}
void CreateTestTextureDrawQuad(const gfx::Rect& rect,
SkColor texel_color,
float vertex_opacity[4],
SkColor background_color,
bool premultiplied_alpha,
const SharedQuadState* shared_state,
ResourceProvider* resource_provider,
RenderPass* render_pass) {
SkPMColor pixel_color = premultiplied_alpha ?
SkPreMultiplyColor(texel_color) :
SkPackARGB32NoCheck(SkColorGetA(texel_color),
SkColorGetR(texel_color),
SkColorGetG(texel_color),
SkColorGetB(texel_color));
size_t num_pixels = static_cast<size_t>(rect.width()) * rect.height();
std::vector<uint32_t> pixels(num_pixels, pixel_color);
ResourceId resource = resource_provider->CreateResource(
rect.size(), ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888,
gfx::ColorSpace());
resource_provider->CopyToResource(
resource, reinterpret_cast<uint8_t*>(&pixels.front()), rect.size());
const gfx::PointF uv_top_left(0.0f, 0.0f);
const gfx::PointF uv_bottom_right(1.0f, 1.0f);
const bool flipped = false;
const bool nearest_neighbor = false;
TextureDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
quad->SetNew(shared_state, rect, gfx::Rect(), rect, resource,
premultiplied_alpha, uv_top_left, uv_bottom_right,
background_color, vertex_opacity, flipped, nearest_neighbor,
false);
}
void CreateTestTextureDrawQuad(const gfx::Rect& rect,
SkColor texel_color,
SkColor background_color,
bool premultiplied_alpha,
const SharedQuadState* shared_state,
ResourceProvider* resource_provider,
RenderPass* render_pass) {
float vertex_opacity[4] = {1.0f, 1.0f, 1.0f, 1.0f};
CreateTestTextureDrawQuad(rect, texel_color, vertex_opacity, background_color,
premultiplied_alpha, shared_state,
resource_provider, render_pass);
}
void CreateTestYUVVideoDrawQuad_FromVideoFrame(
const SharedQuadState* shared_state,
scoped_refptr<media::VideoFrame> video_frame,
uint8_t alpha_value,
const gfx::RectF& tex_coord_rect,
RenderPass* render_pass,
VideoResourceUpdater* video_resource_updater,
const gfx::Rect& rect,
const gfx::Rect& visible_rect,
ResourceProvider* resource_provider) {
const bool with_alpha = (video_frame->format() == media::PIXEL_FORMAT_YV12A);
YUVVideoDrawQuad::ColorSpace color_space = YUVVideoDrawQuad::REC_601;
int video_frame_color_space;
if (video_frame->metadata()->GetInteger(
media::VideoFrameMetadata::COLOR_SPACE, &video_frame_color_space) &&
video_frame_color_space == media::COLOR_SPACE_JPEG) {
color_space = YUVVideoDrawQuad::JPEG;
}
gfx::ColorSpace video_color_space = video_frame->ColorSpace();
const gfx::Rect opaque_rect(0, 0, 0, 0);
if (with_alpha) {
memset(video_frame->data(media::VideoFrame::kAPlane), alpha_value,
video_frame->stride(media::VideoFrame::kAPlane) *
video_frame->rows(media::VideoFrame::kAPlane));
}
VideoFrameExternalResources resources =
video_resource_updater->CreateExternalResourcesFromVideoFrame(
video_frame);
EXPECT_EQ(VideoFrameExternalResources::YUV_RESOURCE, resources.type);
EXPECT_EQ(media::VideoFrame::NumPlanes(video_frame->format()),
resources.mailboxes.size());
EXPECT_EQ(media::VideoFrame::NumPlanes(video_frame->format()),
resources.release_callbacks.size());
ResourceId y_resource = resource_provider->CreateResourceFromTextureMailbox(
resources.mailboxes[media::VideoFrame::kYPlane],
SingleReleaseCallbackImpl::Create(
resources.release_callbacks[media::VideoFrame::kYPlane]));
ResourceId u_resource = resource_provider->CreateResourceFromTextureMailbox(
resources.mailboxes[media::VideoFrame::kUPlane],
SingleReleaseCallbackImpl::Create(
resources.release_callbacks[media::VideoFrame::kUPlane]));
ResourceId v_resource = resource_provider->CreateResourceFromTextureMailbox(
resources.mailboxes[media::VideoFrame::kVPlane],
SingleReleaseCallbackImpl::Create(
resources.release_callbacks[media::VideoFrame::kVPlane]));
ResourceId a_resource = 0;
if (with_alpha) {
a_resource = resource_provider->CreateResourceFromTextureMailbox(
resources.mailboxes[media::VideoFrame::kAPlane],
SingleReleaseCallbackImpl::Create(
resources.release_callbacks[media::VideoFrame::kAPlane]));
}
const gfx::Size ya_tex_size = video_frame->coded_size();
const gfx::Size uv_tex_size = media::VideoFrame::PlaneSize(
video_frame->format(), media::VideoFrame::kUPlane,
video_frame->coded_size());
DCHECK(uv_tex_size == media::VideoFrame::PlaneSize(
video_frame->format(), media::VideoFrame::kVPlane,
video_frame->coded_size()));
if (with_alpha) {
DCHECK(ya_tex_size == media::VideoFrame::PlaneSize(
video_frame->format(), media::VideoFrame::kAPlane,
video_frame->coded_size()));
}
gfx::RectF ya_tex_coord_rect(tex_coord_rect.x() * ya_tex_size.width(),
tex_coord_rect.y() * ya_tex_size.height(),
tex_coord_rect.width() * ya_tex_size.width(),
tex_coord_rect.height() * ya_tex_size.height());
gfx::RectF uv_tex_coord_rect(tex_coord_rect.x() * uv_tex_size.width(),
tex_coord_rect.y() * uv_tex_size.height(),
tex_coord_rect.width() * uv_tex_size.width(),
tex_coord_rect.height() * uv_tex_size.height());
YUVVideoDrawQuad* yuv_quad =
render_pass->CreateAndAppendDrawQuad<YUVVideoDrawQuad>();
uint32_t bits_per_channel = 8;
if (video_frame->format() == media::PIXEL_FORMAT_YUV420P10 ||
video_frame->format() == media::PIXEL_FORMAT_YUV422P10 ||
video_frame->format() == media::PIXEL_FORMAT_YUV444P10) {
bits_per_channel = 10;
}
yuv_quad->SetNew(shared_state, rect, opaque_rect, visible_rect,
ya_tex_coord_rect, uv_tex_coord_rect, ya_tex_size,
uv_tex_size, y_resource, u_resource, v_resource, a_resource,
color_space, video_color_space, 0.0f, 1.0f,
bits_per_channel);
}
void CreateTestY16TextureDrawQuad_FromVideoFrame(
const SharedQuadState* shared_state,
scoped_refptr<media::VideoFrame> video_frame,
const gfx::RectF& tex_coord_rect,
RenderPass* render_pass,
VideoResourceUpdater* video_resource_updater,
const gfx::Rect& rect,
const gfx::Rect& visible_rect,
ResourceProvider* resource_provider) {
VideoFrameExternalResources resources =
video_resource_updater->CreateExternalResourcesFromVideoFrame(
video_frame);
EXPECT_EQ(VideoFrameExternalResources::RGBA_RESOURCE, resources.type);
EXPECT_EQ(1u, resources.mailboxes.size());
EXPECT_EQ(1u, resources.release_callbacks.size());
ResourceId y_resource = resource_provider->CreateResourceFromTextureMailbox(
resources.mailboxes[0],
SingleReleaseCallbackImpl::Create(resources.release_callbacks[0]));
TextureDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
float vertex_opacity[4] = {1.0f, 1.0f, 1.0f, 1.0f};
quad->SetNew(shared_state, rect, gfx::Rect(), rect, y_resource, false,
tex_coord_rect.origin(), tex_coord_rect.bottom_right(),
SK_ColorBLACK, vertex_opacity, false, false, false);
}
// Upshift video frame to 10 bit.
scoped_refptr<media::VideoFrame> CreateHighbitVideoFrame(
media::VideoFrame* video_frame) {
media::VideoPixelFormat format;
switch (video_frame->format()) {
case media::PIXEL_FORMAT_I420:
case media::PIXEL_FORMAT_YV12:
format = media::PIXEL_FORMAT_YUV420P10;
break;
case media::PIXEL_FORMAT_YV16:
format = media::PIXEL_FORMAT_YUV422P10;
break;
case media::PIXEL_FORMAT_YV24:
format = media::PIXEL_FORMAT_YUV444P10;
break;
default:
NOTREACHED();
return nullptr;
}
scoped_refptr<media::VideoFrame> ret = media::VideoFrame::CreateFrame(
format, video_frame->coded_size(), video_frame->visible_rect(),
video_frame->natural_size(), video_frame->timestamp());
// Copy all metadata.
ret->metadata()->MergeMetadataFrom(video_frame->metadata());
for (int plane = media::VideoFrame::kYPlane;
plane <= media::VideoFrame::kVPlane; ++plane) {
int width = video_frame->row_bytes(plane);
const uint8_t* src = video_frame->data(plane);
uint16_t* dst = reinterpret_cast<uint16_t*>(ret->data(plane));
for (int row = 0; row < video_frame->rows(plane); row++) {
for (int x = 0; x < width; x++) {
// Replicate the top bits into the lower bits, this way
// 0xFF becomes 0x3FF.
dst[x] = (src[x] << 2) | (src[x] >> 6);
}
src += video_frame->stride(plane);
dst += ret->stride(plane) / 2;
}
}
return ret;
}
void CreateTestYUVVideoDrawQuad_Striped(
const SharedQuadState* shared_state,
media::VideoPixelFormat format,
bool is_transparent,
bool highbit,
const gfx::RectF& tex_coord_rect,
RenderPass* render_pass,
VideoResourceUpdater* video_resource_updater,
const gfx::Rect& rect,
const gfx::Rect& visible_rect,
ResourceProvider* resource_provider) {
scoped_refptr<media::VideoFrame> video_frame = media::VideoFrame::CreateFrame(
format, rect.size(), rect, rect.size(), base::TimeDelta());
// YUV values representing a striped pattern, for validating texture
// coordinates for sampling.
uint8_t y_value = 0;
uint8_t u_value = 0;
uint8_t v_value = 0;
for (int i = 0; i < video_frame->rows(media::VideoFrame::kYPlane); ++i) {
uint8_t* y_row = video_frame->data(media::VideoFrame::kYPlane) +
video_frame->stride(media::VideoFrame::kYPlane) * i;
for (int j = 0; j < video_frame->row_bytes(media::VideoFrame::kYPlane);
++j) {
y_row[j] = (y_value += 1);
}
}
for (int i = 0; i < video_frame->rows(media::VideoFrame::kUPlane); ++i) {
uint8_t* u_row = video_frame->data(media::VideoFrame::kUPlane) +
video_frame->stride(media::VideoFrame::kUPlane) * i;
uint8_t* v_row = video_frame->data(media::VideoFrame::kVPlane) +
video_frame->stride(media::VideoFrame::kVPlane) * i;
for (int j = 0; j < video_frame->row_bytes(media::VideoFrame::kUPlane);
++j) {
u_row[j] = (u_value += 3);
v_row[j] = (v_value += 5);
}
}
uint8_t alpha_value = is_transparent ? 0 : 128;
if (highbit)
video_frame = CreateHighbitVideoFrame(video_frame.get());
CreateTestYUVVideoDrawQuad_FromVideoFrame(
shared_state, video_frame, alpha_value, tex_coord_rect, render_pass,
video_resource_updater, rect, visible_rect, resource_provider);
}
// Creates a video frame of size background_size filled with yuv_background,
// and then draws a foreground rectangle in a different color on top of
// that. The foreground rectangle must have coordinates that are divisible
// by 2 because YUV is a block format.
void CreateTestYUVVideoDrawQuad_TwoColor(
const SharedQuadState* shared_state,
media::VideoPixelFormat format,
media::ColorSpace color_space,
bool is_transparent,
const gfx::RectF& tex_coord_rect,
const gfx::Size& background_size,
const gfx::Rect& visible_rect,
uint8_t y_background,
uint8_t u_background,
uint8_t v_background,
const gfx::Rect& foreground_rect,
uint8_t y_foreground,
uint8_t u_foreground,
uint8_t v_foreground,
RenderPass* render_pass,
VideoResourceUpdater* video_resource_updater,
ResourceProvider* resource_provider) {
const gfx::Rect rect(background_size);
scoped_refptr<media::VideoFrame> video_frame =
media::VideoFrame::CreateFrame(format, background_size, foreground_rect,
foreground_rect.size(), base::TimeDelta());
video_frame->metadata()->SetInteger(media::VideoFrameMetadata::COLOR_SPACE,
color_space);
int planes[] = {media::VideoFrame::kYPlane,
media::VideoFrame::kUPlane,
media::VideoFrame::kVPlane};
uint8_t yuv_background[] = {y_background, u_background, v_background};
uint8_t yuv_foreground[] = {y_foreground, u_foreground, v_foreground};
int sample_size[] = {1, 2, 2};
for (int i = 0; i < 3; ++i) {
memset(video_frame->data(planes[i]), yuv_background[i],
video_frame->stride(planes[i]) * video_frame->rows(planes[i]));
}
for (int i = 0; i < 3; ++i) {
// Since yuv encoding uses block encoding, widths have to be divisible
// by the sample size in order for this function to behave properly.
DCHECK_EQ(foreground_rect.x() % sample_size[i], 0);
DCHECK_EQ(foreground_rect.y() % sample_size[i], 0);
DCHECK_EQ(foreground_rect.width() % sample_size[i], 0);
DCHECK_EQ(foreground_rect.height() % sample_size[i], 0);
gfx::Rect sample_rect(foreground_rect.x() / sample_size[i],
foreground_rect.y() / sample_size[i],
foreground_rect.width() / sample_size[i],
foreground_rect.height() / sample_size[i]);
for (int y = sample_rect.y(); y < sample_rect.bottom(); ++y) {
for (int x = sample_rect.x(); x < sample_rect.right(); ++x) {
size_t offset = y * video_frame->stride(planes[i]) + x;
video_frame->data(planes[i])[offset] = yuv_foreground[i];
}
}
}
uint8_t alpha_value = 255;
CreateTestYUVVideoDrawQuad_FromVideoFrame(
shared_state, video_frame, alpha_value, tex_coord_rect, render_pass,
video_resource_updater, rect, visible_rect, resource_provider);
}
void CreateTestYUVVideoDrawQuad_Solid(
const SharedQuadState* shared_state,
media::VideoPixelFormat format,
media::ColorSpace color_space,
bool is_transparent,
const gfx::RectF& tex_coord_rect,
uint8_t y,
uint8_t u,
uint8_t v,
RenderPass* render_pass,
VideoResourceUpdater* video_resource_updater,
const gfx::Rect& rect,
const gfx::Rect& visible_rect,
ResourceProvider* resource_provider) {
scoped_refptr<media::VideoFrame> video_frame = media::VideoFrame::CreateFrame(
format, rect.size(), rect, rect.size(), base::TimeDelta());
video_frame->metadata()->SetInteger(media::VideoFrameMetadata::COLOR_SPACE,
color_space);
// YUV values of a solid, constant, color. Useful for testing that color
// space/color range are being handled properly.
memset(video_frame->data(media::VideoFrame::kYPlane), y,
video_frame->stride(media::VideoFrame::kYPlane) *
video_frame->rows(media::VideoFrame::kYPlane));
memset(video_frame->data(media::VideoFrame::kUPlane), u,
video_frame->stride(media::VideoFrame::kUPlane) *
video_frame->rows(media::VideoFrame::kUPlane));
memset(video_frame->data(media::VideoFrame::kVPlane), v,
video_frame->stride(media::VideoFrame::kVPlane) *
video_frame->rows(media::VideoFrame::kVPlane));
uint8_t alpha_value = is_transparent ? 0 : 128;
CreateTestYUVVideoDrawQuad_FromVideoFrame(
shared_state, video_frame, alpha_value, tex_coord_rect, render_pass,
video_resource_updater, rect, visible_rect, resource_provider);
}
void CreateTestYUVVideoDrawQuad_NV12(const SharedQuadState* shared_state,
media::ColorSpace video_frame_color_space,
const gfx::ColorSpace& video_color_space,
const gfx::RectF& tex_coord_rect,
uint8_t y,
uint8_t u,
uint8_t v,
RenderPass* render_pass,
const gfx::Rect& rect,
const gfx::Rect& visible_rect,
ResourceProvider* resource_provider) {
YUVVideoDrawQuad::ColorSpace color_space = YUVVideoDrawQuad::REC_601;
if (video_frame_color_space == media::COLOR_SPACE_JPEG) {
color_space = YUVVideoDrawQuad::JPEG;
}
const gfx::Rect opaque_rect(0, 0, 0, 0);
const gfx::Size ya_tex_size = rect.size();
const gfx::Size uv_tex_size = media::VideoFrame::PlaneSize(
media::PIXEL_FORMAT_NV12, media::VideoFrame::kUVPlane, rect.size());
ResourceId y_resource = resource_provider->CreateResource(
rect.size(), ResourceProvider::TEXTURE_HINT_DEFAULT,
resource_provider->YuvResourceFormat(8), gfx::ColorSpace());
ResourceId u_resource = resource_provider->CreateResource(
uv_tex_size, ResourceProvider::TEXTURE_HINT_DEFAULT, RGBA_8888,
gfx::ColorSpace());
ResourceId v_resource = u_resource;
ResourceId a_resource = 0;
std::vector<uint8_t> y_pixels(ya_tex_size.GetArea(), y);
resource_provider->CopyToResource(y_resource, y_pixels.data(), ya_tex_size);
// U goes in the R component and V goes in the G component.
uint32_t rgba_pixel = (u << 24) | (v << 16);
std::vector<uint32_t> uv_pixels(uv_tex_size.GetArea(), rgba_pixel);
resource_provider->CopyToResource(
u_resource, reinterpret_cast<uint8_t*>(uv_pixels.data()), uv_tex_size);
gfx::RectF ya_tex_coord_rect(tex_coord_rect.x() * ya_tex_size.width(),
tex_coord_rect.y() * ya_tex_size.height(),
tex_coord_rect.width() * ya_tex_size.width(),
tex_coord_rect.height() * ya_tex_size.height());
gfx::RectF uv_tex_coord_rect(tex_coord_rect.x() * uv_tex_size.width(),
tex_coord_rect.y() * uv_tex_size.height(),
tex_coord_rect.width() * uv_tex_size.width(),
tex_coord_rect.height() * uv_tex_size.height());
YUVVideoDrawQuad* yuv_quad =
render_pass->CreateAndAppendDrawQuad<YUVVideoDrawQuad>();
yuv_quad->SetNew(shared_state, rect, opaque_rect, visible_rect,
ya_tex_coord_rect, uv_tex_coord_rect, ya_tex_size,
uv_tex_size, y_resource, u_resource, v_resource, a_resource,
color_space, video_color_space, 0.0f, 1.0f, 8);
}
void CreateTestY16TextureDrawQuad_TwoColor(
const SharedQuadState* shared_state,
const gfx::RectF& tex_coord_rect,
uint8_t g_foreground,
uint8_t g_background,
RenderPass* render_pass,
VideoResourceUpdater* video_resource_updater,
const gfx::Rect& rect,
const gfx::Rect& visible_rect,
const gfx::Rect& foreground_rect,
ResourceProvider* resource_provider) {
std::unique_ptr<unsigned char, base::AlignedFreeDeleter> memory(
static_cast<unsigned char*>(
base::AlignedAlloc(rect.size().GetArea() * 2,
media::VideoFrame::kFrameAddressAlignment)));
scoped_refptr<media::VideoFrame> video_frame =
media::VideoFrame::WrapExternalData(
media::PIXEL_FORMAT_Y16, rect.size(), visible_rect,
visible_rect.size(), memory.get(), rect.size().GetArea() * 2,
base::TimeDelta());
DCHECK_EQ(video_frame->rows(0) % 2, 0);
DCHECK_EQ(video_frame->stride(0) % 2, 0);
for (int j = 0; j < video_frame->rows(0); ++j) {
uint8_t* row = video_frame->data(0) + j * video_frame->stride(0);
if (j < foreground_rect.y() || j >= foreground_rect.bottom()) {
for (int i = 0; i < video_frame->stride(0) / 2; ++i) {
*row++ = i & 0xFF; // Fill R with anything. It is not rendered.
*row++ = g_background;
}
} else {
for (int i = 0;
i < std::min(video_frame->stride(0) / 2, foreground_rect.x()); ++i) {
*row++ = i & 0xFF;
*row++ = g_background;
}
for (int i = foreground_rect.x();
i < std::min(video_frame->stride(0) / 2, foreground_rect.right());
++i) {
*row++ = i & 0xFF;
*row++ = g_foreground;
}
for (int i = foreground_rect.right(); i < video_frame->stride(0) / 2;
++i) {
*row++ = i & 0xFF;
*row++ = g_background;
}
}
}
CreateTestY16TextureDrawQuad_FromVideoFrame(
shared_state, video_frame, tex_coord_rect, render_pass,
video_resource_updater, rect, visible_rect, resource_provider);
}
typedef ::testing::Types<GLRenderer,
SoftwareRenderer,
GLRendererWithExpandedViewport,
SoftwareRendererWithExpandedViewport> RendererTypes;
TYPED_TEST_CASE(RendererPixelTest, RendererTypes);
template <typename RendererType>
class SoftwareRendererPixelTest : public RendererPixelTest<RendererType> {};
typedef ::testing::Types<SoftwareRenderer, SoftwareRendererWithExpandedViewport>
SoftwareRendererTypes;
TYPED_TEST_CASE(SoftwareRendererPixelTest, SoftwareRendererTypes);
template <typename RendererType>
class FuzzyForSoftwareOnlyPixelComparator : public PixelComparator {
public:
explicit FuzzyForSoftwareOnlyPixelComparator(bool discard_alpha)
: fuzzy_(discard_alpha), exact_(discard_alpha) {}
bool Compare(const SkBitmap& actual_bmp,
const SkBitmap& expected_bmp) const override;
private:
FuzzyPixelOffByOneComparator fuzzy_;
ExactPixelComparator exact_;
};
template<>
bool FuzzyForSoftwareOnlyPixelComparator<SoftwareRenderer>::Compare(
const SkBitmap& actual_bmp,
const SkBitmap& expected_bmp) const {
return fuzzy_.Compare(actual_bmp, expected_bmp);
}
template <>
bool FuzzyForSoftwareOnlyPixelComparator<
SoftwareRendererWithExpandedViewport>::Compare(
const SkBitmap& actual_bmp,
const SkBitmap& expected_bmp) const {
return fuzzy_.Compare(actual_bmp, expected_bmp);
}
template<typename RendererType>
bool FuzzyForSoftwareOnlyPixelComparator<RendererType>::Compare(
const SkBitmap& actual_bmp,
const SkBitmap& expected_bmp) const {
return exact_.Compare(actual_bmp, expected_bmp);
}
TYPED_TEST(RendererPixelTest, SimpleGreenRect) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
SolidColorDrawQuad* color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(shared_state, rect, rect, SK_ColorGREEN, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("green.png")),
ExactPixelComparator(true)));
}
TYPED_TEST(RendererPixelTest, SimpleGreenRect_NonRootRenderPass) {
gfx::Rect rect(this->device_viewport_size_);
gfx::Rect small_rect(100, 100);
int child_id = 2;
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_id, small_rect, gfx::Transform());
SharedQuadState* child_shared_state =
CreateTestSharedQuadState(gfx::Transform(), small_rect, child_pass.get());
SolidColorDrawQuad* color_quad =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(child_shared_state, rect, rect, SK_ColorGREEN, false);
int root_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRenderPass(root_id, rect, gfx::Transform());
SharedQuadState* root_shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, root_pass.get());
CreateTestRenderPassDrawQuad(
root_shared_state, small_rect, child_id, root_pass.get());
RenderPass* child_pass_ptr = child_pass.get();
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
EXPECT_TRUE(this->RunPixelTestWithReadbackTarget(
&pass_list,
child_pass_ptr,
base::FilePath(FILE_PATH_LITERAL("green_small.png")),
ExactPixelComparator(true)));
}
TYPED_TEST(RendererPixelTest, PremultipliedTextureWithoutBackground) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
CreateTestTextureDrawQuad(gfx::Rect(this->device_viewport_size_),
SkColorSetARGB(128, 0, 255, 0), // Texel color.
SK_ColorTRANSPARENT, // Background color.
true, // Premultiplied alpha.
shared_state,
this->resource_provider_.get(),
pass.get());
SolidColorDrawQuad* color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(shared_state, rect, rect, SK_ColorWHITE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("green_alpha.png")),
FuzzyPixelOffByOneComparator(true)));
}
TYPED_TEST(RendererPixelTest, PremultipliedTextureWithBackground) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* texture_quad_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
texture_quad_state->opacity = 0.8f;
CreateTestTextureDrawQuad(gfx::Rect(this->device_viewport_size_),
SkColorSetARGB(204, 120, 255, 120), // Texel color.
SK_ColorGREEN, // Background color.
true, // Premultiplied alpha.
texture_quad_state,
this->resource_provider_.get(),
pass.get());
SharedQuadState* color_quad_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
SolidColorDrawQuad* color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(color_quad_state, rect, rect, SK_ColorWHITE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("green_alpha.png")),
FuzzyPixelOffByOneComparator(true)));
}
TEST_F(GLRendererPixelTest,
PremultipliedTextureWithBackgroundAndVertexOpacity) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* texture_quad_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
texture_quad_state->opacity = 0.8f;
float vertex_opacity[4] = {1.f, 1.f, 0.f, 0.f};
CreateTestTextureDrawQuad(gfx::Rect(this->device_viewport_size_),
SkColorSetARGB(204, 120, 255, 120), // Texel color.
vertex_opacity,
SK_ColorGREEN, // Background color.
true, // Premultiplied alpha.
texture_quad_state, this->resource_provider_.get(),
pass.get());
SharedQuadState* color_quad_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
SolidColorDrawQuad* color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(color_quad_state, rect, rect, SK_ColorWHITE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("green_alpha_vertex_opacity.png")),
FuzzyPixelOffByOneComparator(true)));
}
template <typename TypeParam>
class IntersectingQuadPixelTest : public RendererPixelTest<TypeParam> {
protected:
void SetupQuadStateAndRenderPass() {
// This sets up a pair of draw quads. They are both rotated
// relative to the root plane, they are also rotated relative to each other.
// The intersect in the middle at a non-perpendicular angle so that any
// errors are hopefully magnified.
// The quads should intersect correctly, as in the front quad should only
// be partially in front of the back quad, and partially behind.
viewport_rect_ = gfx::Rect(this->device_viewport_size_);
quad_rect_ = gfx::Rect(0, 0, this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2.0);
int id = 1;
render_pass_ = CreateTestRootRenderPass(id, viewport_rect_);
// Create the front quad rotated on the Z and Y axis.
gfx::Transform trans;
trans.Translate3d(0, 0, 0.707 * this->device_viewport_size_.width() / 2.0);
trans.RotateAboutZAxis(45.0);
trans.RotateAboutYAxis(45.0);
front_quad_state_ =
CreateTestSharedQuadState(trans, viewport_rect_, render_pass_.get());
front_quad_state_->clip_rect = quad_rect_;
// Make sure they end up in a 3d sorting context.
front_quad_state_->sorting_context_id = 1;
// Create the back quad, and rotate on just the y axis. This will intersect
// the first quad partially.
trans = gfx::Transform();
trans.Translate3d(0, 0, -0.707 * this->device_viewport_size_.width() / 2.0);
trans.RotateAboutYAxis(-45.0);
back_quad_state_ =
CreateTestSharedQuadState(trans, viewport_rect_, render_pass_.get());
back_quad_state_->sorting_context_id = 1;
back_quad_state_->clip_rect = quad_rect_;
}
void AppendBackgroundAndRunTest(const PixelComparator& comparator,
const base::FilePath::CharType* ref_file) {
SharedQuadState* background_quad_state = CreateTestSharedQuadState(
gfx::Transform(), viewport_rect_, render_pass_.get());
SolidColorDrawQuad* background_quad =
render_pass_->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
background_quad->SetNew(background_quad_state, viewport_rect_,
viewport_rect_, SK_ColorWHITE, false);
pass_list_.push_back(std::move(render_pass_));
EXPECT_TRUE(
this->RunPixelTest(&pass_list_, base::FilePath(ref_file), comparator));
}
template <typename T>
T* CreateAndAppendDrawQuad() {
return render_pass_->CreateAndAppendDrawQuad<T>();
}
std::unique_ptr<RenderPass> render_pass_;
gfx::Rect viewport_rect_;
SharedQuadState* front_quad_state_;
SharedQuadState* back_quad_state_;
gfx::Rect quad_rect_;
RenderPassList pass_list_;
};
template <typename TypeParam>
class IntersectingQuadGLPixelTest
: public IntersectingQuadPixelTest<TypeParam> {
public:
void SetUp() override {
IntersectingQuadPixelTest<TypeParam>::SetUp();
video_resource_updater_.reset(
new VideoResourceUpdater(this->output_surface_->context_provider(),
this->resource_provider_.get()));
video_resource_updater2_.reset(
new VideoResourceUpdater(this->output_surface_->context_provider(),
this->resource_provider_.get()));
}
protected:
std::unique_ptr<VideoResourceUpdater> video_resource_updater_;
std::unique_ptr<VideoResourceUpdater> video_resource_updater2_;
};
template <typename TypeParam>
class IntersectingQuadSoftwareTest
: public IntersectingQuadPixelTest<TypeParam> {};
typedef ::testing::Types<SoftwareRenderer, SoftwareRendererWithExpandedViewport>
SoftwareRendererTypes;
typedef ::testing::Types<GLRenderer, GLRendererWithExpandedViewport>
GLRendererTypes;
TYPED_TEST_CASE(IntersectingQuadPixelTest, RendererTypes);
TYPED_TEST_CASE(IntersectingQuadGLPixelTest, GLRendererTypes);
TYPED_TEST_CASE(IntersectingQuadSoftwareTest, SoftwareRendererTypes);
TYPED_TEST(IntersectingQuadPixelTest, SolidColorQuads) {
this->SetupQuadStateAndRenderPass();
SolidColorDrawQuad* quad =
this->template CreateAndAppendDrawQuad<SolidColorDrawQuad>();
SolidColorDrawQuad* quad2 =
this->template CreateAndAppendDrawQuad<SolidColorDrawQuad>();
quad->SetNew(this->front_quad_state_, this->quad_rect_, this->quad_rect_,
SK_ColorBLUE, false);
quad2->SetNew(this->back_quad_state_, this->quad_rect_, this->quad_rect_,
SK_ColorGREEN, false);
SCOPED_TRACE("IntersectingSolidColorQuads");
this->AppendBackgroundAndRunTest(
FuzzyPixelComparator(false, 2.f, 0.f, 256.f, 256, 0.f),
FILE_PATH_LITERAL("intersecting_blue_green.png"));
}
template <typename TypeParam>
SkColor GetColor(const SkColor& color) {
return color;
}
template <>
SkColor GetColor<GLRenderer>(const SkColor& color) {
return SkColorSetARGB(SkColorGetA(color), SkColorGetB(color),
SkColorGetG(color), SkColorGetR(color));
}
template <>
SkColor GetColor<GLRendererWithExpandedViewport>(const SkColor& color) {
return GetColor<GLRenderer>(color);
}
TYPED_TEST(IntersectingQuadPixelTest, TexturedQuads) {
this->SetupQuadStateAndRenderPass();
CreateTestTwoColoredTextureDrawQuad(
this->quad_rect_, GetColor<TypeParam>(SkColorSetARGB(255, 0, 0, 0)),
GetColor<TypeParam>(SkColorSetARGB(255, 0, 0, 255)), SK_ColorTRANSPARENT,
true, this->front_quad_state_, this->resource_provider_.get(),
this->render_pass_.get());
CreateTestTwoColoredTextureDrawQuad(
this->quad_rect_, GetColor<TypeParam>(SkColorSetARGB(255, 0, 255, 0)),
GetColor<TypeParam>(SkColorSetARGB(255, 0, 0, 0)), SK_ColorTRANSPARENT,
true, this->back_quad_state_, this->resource_provider_.get(),
this->render_pass_.get());
SCOPED_TRACE("IntersectingTexturedQuads");
this->AppendBackgroundAndRunTest(
FuzzyPixelComparator(false, 2.f, 0.f, 256.f, 256, 0.f),
FILE_PATH_LITERAL("intersecting_blue_green_squares.png"));
}
TYPED_TEST(IntersectingQuadSoftwareTest, PictureQuads) {
this->SetupQuadStateAndRenderPass();
gfx::Rect outer_rect(this->quad_rect_);
gfx::Rect inner_rect(this->quad_rect_.x() + (this->quad_rect_.width() / 4),
this->quad_rect_.y() + (this->quad_rect_.height() / 4),
this->quad_rect_.width() / 2,
this->quad_rect_.height() / 2);
PaintFlags black_flags;
black_flags.setColor(SK_ColorBLACK);
PaintFlags blue_flags;
blue_flags.setColor(SK_ColorBLUE);
PaintFlags green_flags;
green_flags.setColor(SK_ColorGREEN);
std::unique_ptr<FakeRecordingSource> blue_recording =
FakeRecordingSource::CreateFilledRecordingSource(this->quad_rect_.size());
blue_recording->add_draw_rect_with_flags(outer_rect, black_flags);
blue_recording->add_draw_rect_with_flags(inner_rect, blue_flags);
blue_recording->Rerecord();
scoped_refptr<FakeRasterSource> blue_raster_source =
FakeRasterSource::CreateFromRecordingSource(blue_recording.get(), false);
PictureDrawQuad* blue_quad =
this->render_pass_->template CreateAndAppendDrawQuad<PictureDrawQuad>();
blue_quad->SetNew(this->front_quad_state_, this->quad_rect_, gfx::Rect(),
this->quad_rect_, gfx::RectF(this->quad_rect_),
this->quad_rect_.size(), false, RGBA_8888, this->quad_rect_,
1.f, blue_raster_source);
std::unique_ptr<FakeRecordingSource> green_recording =
FakeRecordingSource::CreateFilledRecordingSource(this->quad_rect_.size());
green_recording->add_draw_rect_with_flags(outer_rect, green_flags);
green_recording->add_draw_rect_with_flags(inner_rect, black_flags);
green_recording->Rerecord();
scoped_refptr<FakeRasterSource> green_raster_source =
FakeRasterSource::CreateFromRecordingSource(green_recording.get(), false);
PictureDrawQuad* green_quad =
this->render_pass_->template CreateAndAppendDrawQuad<PictureDrawQuad>();
green_quad->SetNew(this->back_quad_state_, this->quad_rect_, gfx::Rect(),
this->quad_rect_, gfx::RectF(this->quad_rect_),
this->quad_rect_.size(), false, RGBA_8888,
this->quad_rect_, 1.f, green_raster_source);
SCOPED_TRACE("IntersectingPictureQuadsPass");
this->AppendBackgroundAndRunTest(
FuzzyPixelComparator(false, 2.f, 0.f, 256.f, 256, 0.f),
FILE_PATH_LITERAL("intersecting_blue_green_squares.png"));
}
TYPED_TEST(IntersectingQuadPixelTest, RenderPassQuads) {
this->SetupQuadStateAndRenderPass();
int child_pass_id1 = 2;
int child_pass_id2 = 3;
std::unique_ptr<RenderPass> child_pass1 =
CreateTestRenderPass(child_pass_id1, this->quad_rect_, gfx::Transform());
SharedQuadState* child1_quad_state = CreateTestSharedQuadState(
gfx::Transform(), this->quad_rect_, child_pass1.get());
std::unique_ptr<RenderPass> child_pass2 =
CreateTestRenderPass(child_pass_id2, this->quad_rect_, gfx::Transform());
SharedQuadState* child2_quad_state = CreateTestSharedQuadState(
gfx::Transform(), this->quad_rect_, child_pass2.get());
CreateTestTwoColoredTextureDrawQuad(
this->quad_rect_, GetColor<TypeParam>(SkColorSetARGB(255, 0, 0, 0)),
GetColor<TypeParam>(SkColorSetARGB(255, 0, 0, 255)), SK_ColorTRANSPARENT,
true, child1_quad_state, this->resource_provider_.get(),
child_pass1.get());
CreateTestTwoColoredTextureDrawQuad(
this->quad_rect_, GetColor<TypeParam>(SkColorSetARGB(255, 0, 255, 0)),
GetColor<TypeParam>(SkColorSetARGB(255, 0, 0, 0)), SK_ColorTRANSPARENT,
true, child2_quad_state, this->resource_provider_.get(),
child_pass2.get());
CreateTestRenderPassDrawQuad(this->front_quad_state_, this->quad_rect_,
child_pass_id1, this->render_pass_.get());
CreateTestRenderPassDrawQuad(this->back_quad_state_, this->quad_rect_,
child_pass_id2, this->render_pass_.get());
this->pass_list_.push_back(std::move(child_pass1));
this->pass_list_.push_back(std::move(child_pass2));
SCOPED_TRACE("IntersectingRenderQuadsPass");
this->AppendBackgroundAndRunTest(
FuzzyPixelComparator(false, 2.f, 0.f, 256.f, 256, 0.f),
FILE_PATH_LITERAL("intersecting_blue_green_squares.png"));
}
TYPED_TEST(IntersectingQuadGLPixelTest, YUVVideoQuads) {
this->SetupQuadStateAndRenderPass();
gfx::Rect inner_rect(
((this->quad_rect_.x() + (this->quad_rect_.width() / 4)) & ~0xF),
((this->quad_rect_.y() + (this->quad_rect_.height() / 4)) & ~0xF),
(this->quad_rect_.width() / 2) & ~0xF,
(this->quad_rect_.height() / 2) & ~0xF);
CreateTestYUVVideoDrawQuad_TwoColor(
this->front_quad_state_, media::PIXEL_FORMAT_YV12,
media::COLOR_SPACE_JPEG, false, gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f),
this->quad_rect_.size(), this->quad_rect_, 0, 128, 128, inner_rect, 29,
255, 107, this->render_pass_.get(), this->video_resource_updater_.get(),
this->resource_provider_.get());
CreateTestYUVVideoDrawQuad_TwoColor(
this->back_quad_state_, media::PIXEL_FORMAT_YV12, media::COLOR_SPACE_JPEG,
false, gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), this->quad_rect_.size(),
this->quad_rect_, 149, 43, 21, inner_rect, 0, 128, 128,
this->render_pass_.get(), this->video_resource_updater2_.get(),
this->resource_provider_.get());
SCOPED_TRACE("IntersectingVideoQuads");
this->AppendBackgroundAndRunTest(
FuzzyPixelOffByOneComparator(false),
FILE_PATH_LITERAL("intersecting_blue_green_squares_video.png"));
}
TYPED_TEST(IntersectingQuadGLPixelTest, Y16VideoQuads) {
this->SetupQuadStateAndRenderPass();
gfx::Rect inner_rect(
((this->quad_rect_.x() + (this->quad_rect_.width() / 4)) & ~0xF),
((this->quad_rect_.y() + (this->quad_rect_.height() / 4)) & ~0xF),
(this->quad_rect_.width() / 2) & ~0xF,
(this->quad_rect_.height() / 2) & ~0xF);
CreateTestY16TextureDrawQuad_TwoColor(
this->front_quad_state_, gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), 18, 0,
this->render_pass_.get(), this->video_resource_updater_.get(),
this->quad_rect_, this->quad_rect_, inner_rect,
this->resource_provider_.get());
CreateTestY16TextureDrawQuad_TwoColor(
this->back_quad_state_, gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), 0, 182,
this->render_pass_.get(), this->video_resource_updater2_.get(),
this->quad_rect_, this->quad_rect_, inner_rect,
this->resource_provider_.get());
SCOPED_TRACE("IntersectingVideoQuads");
this->AppendBackgroundAndRunTest(
FuzzyPixelOffByOneComparator(false),
FILE_PATH_LITERAL("intersecting_light_dark_squares_video.png"));
}
// TODO(skaslev): The software renderer does not support non-premultplied alpha.
TEST_F(GLRendererPixelTest, NonPremultipliedTextureWithoutBackground) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
CreateTestTextureDrawQuad(gfx::Rect(this->device_viewport_size_),
SkColorSetARGB(128, 0, 255, 0), // Texel color.
SK_ColorTRANSPARENT, // Background color.
false, // Premultiplied alpha.
shared_state,
this->resource_provider_.get(),
pass.get());
SolidColorDrawQuad* color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(shared_state, rect, rect, SK_ColorWHITE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("green_alpha.png")),
FuzzyPixelOffByOneComparator(true)));
}
// TODO(skaslev): The software renderer does not support non-premultplied alpha.
TEST_F(GLRendererPixelTest, NonPremultipliedTextureWithBackground) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* texture_quad_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
texture_quad_state->opacity = 0.8f;
CreateTestTextureDrawQuad(gfx::Rect(this->device_viewport_size_),
SkColorSetARGB(204, 120, 255, 120), // Texel color.
SK_ColorGREEN, // Background color.
false, // Premultiplied alpha.
texture_quad_state,
this->resource_provider_.get(),
pass.get());
SharedQuadState* color_quad_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
SolidColorDrawQuad* color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(color_quad_state, rect, rect, SK_ColorWHITE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("green_alpha.png")),
FuzzyPixelOffByOneComparator(true)));
}
class VideoGLRendererPixelTest : public GLRendererPixelTest {
protected:
void CreateEdgeBleedPass(media::VideoPixelFormat format,
media::ColorSpace color_space,
RenderPassList* pass_list) {
gfx::Rect rect(200, 200);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
// Scale the video up so that bilinear filtering kicks in to sample more
// than just nearest neighbor would.
gfx::Transform scale_by_2;
scale_by_2.Scale(2.f, 2.f);
gfx::Rect half_rect(100, 100);
SharedQuadState* shared_state =
CreateTestSharedQuadState(scale_by_2, half_rect, pass.get());
gfx::Size background_size(200, 200);
gfx::Rect green_rect(16, 20, 100, 100);
gfx::RectF tex_coord_rect(
static_cast<float>(green_rect.x()) / background_size.width(),
static_cast<float>(green_rect.y()) / background_size.height(),
static_cast<float>(green_rect.width()) / background_size.width(),
static_cast<float>(green_rect.height()) / background_size.height());
// YUV of (149,43,21) should be green (0,255,0) in RGB.
// Create a video frame that has a non-green background rect, with a
// green sub-rectangle that should be the only thing displayed in
// the final image. Bleeding will appear on all four sides of the video
// if the tex coords are not clamped.
CreateTestYUVVideoDrawQuad_TwoColor(
shared_state, format, color_space, false, tex_coord_rect,
background_size, gfx::Rect(background_size), 128, 128, 128, green_rect,
149, 43, 21, pass.get(), video_resource_updater_.get(),
resource_provider_.get());
pass_list->push_back(std::move(pass));
}
void SetUp() override {
GLRendererPixelTest::SetUp();
video_resource_updater_.reset(new VideoResourceUpdater(
output_surface_->context_provider(), resource_provider_.get()));
}
std::unique_ptr<VideoResourceUpdater> video_resource_updater_;
};
class VideoGLRendererPixelHiLoTest
: public VideoGLRendererPixelTest,
public ::testing::WithParamInterface<bool> {};
TEST_P(VideoGLRendererPixelHiLoTest, SimpleYUVRect) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
bool highbit = GetParam();
CreateTestYUVVideoDrawQuad_Striped(
shared_state, media::PIXEL_FORMAT_YV12, false, highbit,
gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), pass.get(),
video_resource_updater_.get(), rect, rect, resource_provider_.get());
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(
this->RunPixelTest(&pass_list,
base::FilePath(FILE_PATH_LITERAL("yuv_stripes.png")),
FuzzyPixelOffByOneComparator(true)));
}
TEST_P(VideoGLRendererPixelHiLoTest, ClippedYUVRect) {
gfx::Rect viewport(this->device_viewport_size_);
gfx::Rect draw_rect(this->device_viewport_size_.width() * 1.5,
this->device_viewport_size_.height() * 1.5);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, viewport);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), viewport, pass.get());
bool highbit = GetParam();
CreateTestYUVVideoDrawQuad_Striped(
shared_state, media::PIXEL_FORMAT_YV12, false, highbit,
gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), pass.get(),
video_resource_updater_.get(), draw_rect, viewport,
resource_provider_.get());
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list, base::FilePath(FILE_PATH_LITERAL("yuv_stripes_clipped.png")),
FuzzyPixelOffByOneComparator(true)));
}
TEST_F(VideoGLRendererPixelHiLoTest, OffsetYUVRect) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
// Intentionally sets frame format to I420 for testing coverage.
CreateTestYUVVideoDrawQuad_Striped(
shared_state, media::PIXEL_FORMAT_I420, false, false,
gfx::RectF(0.125f, 0.25f, 0.75f, 0.5f), pass.get(),
video_resource_updater_.get(), rect, rect, resource_provider_.get());
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list, base::FilePath(FILE_PATH_LITERAL("yuv_stripes_offset.png")),
FuzzyPixelComparator(true, 100.0f, 1.0f, 1.0f, 1, 0)));
}
TEST_F(VideoGLRendererPixelTest, SimpleYUVRectBlack) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
// In MPEG color range YUV values of (15,128,128) should produce black.
CreateTestYUVVideoDrawQuad_Solid(
shared_state, media::PIXEL_FORMAT_YV12, media::COLOR_SPACE_UNSPECIFIED,
false, gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), 15, 128, 128, pass.get(),
video_resource_updater_.get(), rect, rect, resource_provider_.get());
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
// If we didn't get black out of the YUV values above, then we probably have a
// color range issue.
EXPECT_TRUE(this->RunPixelTest(&pass_list,
base::FilePath(FILE_PATH_LITERAL("black.png")),
FuzzyPixelOffByOneComparator(true)));
}
// First argument (test case prefix) is intentionally left empty.
INSTANTIATE_TEST_CASE_P(, VideoGLRendererPixelHiLoTest, ::testing::Bool());
TEST_F(VideoGLRendererPixelTest, SimpleYUVJRect) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
// YUV of (149,43,21) should be green (0,255,0) in RGB.
CreateTestYUVVideoDrawQuad_Solid(
shared_state, media::PIXEL_FORMAT_YV12, media::COLOR_SPACE_JPEG, false,
gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), 149, 43, 21, pass.get(),
video_resource_updater_.get(), rect, rect, resource_provider_.get());
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(&pass_list,
base::FilePath(FILE_PATH_LITERAL("green.png")),
FuzzyPixelOffByOneComparator(true)));
}
TEST_F(VideoGLRendererPixelTest, SimpleNV12JRect) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
// YUV of (149,43,21) should be green (0,255,0) in RGB.
CreateTestYUVVideoDrawQuad_NV12(
shared_state, media::COLOR_SPACE_JPEG, gfx::ColorSpace::CreateJpeg(),
gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), 149, 43, 21, pass.get(), rect, rect,
resource_provider_.get());
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(&pass_list,
base::FilePath(FILE_PATH_LITERAL("green.png")),
FuzzyPixelOffByOneComparator(true)));
}
// Test that a YUV video doesn't bleed outside of its tex coords when the
// tex coord rect is only a partial subrectangle of the coded contents.
TEST_F(VideoGLRendererPixelTest, YUVEdgeBleed) {
RenderPassList pass_list;
CreateEdgeBleedPass(media::PIXEL_FORMAT_YV12, media::COLOR_SPACE_JPEG,
&pass_list);
EXPECT_TRUE(this->RunPixelTest(&pass_list,
base::FilePath(FILE_PATH_LITERAL("green.png")),
FuzzyPixelOffByOneComparator(true)));
}
TEST_F(VideoGLRendererPixelTest, YUVAEdgeBleed) {
RenderPassList pass_list;
CreateEdgeBleedPass(media::PIXEL_FORMAT_YV12A, media::COLOR_SPACE_UNSPECIFIED,
&pass_list);
EXPECT_TRUE(this->RunPixelTest(&pass_list,
base::FilePath(FILE_PATH_LITERAL("green.png")),
FuzzyPixelOffByOneComparator(true)));
}
TEST_F(VideoGLRendererPixelTest, SimpleYUVJRectGrey) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
// Dark grey in JPEG color range (in MPEG, this is black).
CreateTestYUVVideoDrawQuad_Solid(
shared_state, media::PIXEL_FORMAT_YV12, media::COLOR_SPACE_JPEG, false,
gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), 15, 128, 128, pass.get(),
video_resource_updater_.get(), rect, rect, resource_provider_.get());
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(
this->RunPixelTest(&pass_list,
base::FilePath(FILE_PATH_LITERAL("dark_grey.png")),
FuzzyPixelOffByOneComparator(true)));
}
TEST_F(VideoGLRendererPixelHiLoTest, SimpleYUVARect) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
CreateTestYUVVideoDrawQuad_Striped(
shared_state, media::PIXEL_FORMAT_YV12A, false, false,
gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), pass.get(),
video_resource_updater_.get(), rect, rect, resource_provider_.get());
SolidColorDrawQuad* color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(shared_state, rect, rect, SK_ColorWHITE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("yuv_stripes_alpha.png")),
FuzzyPixelOffByOneComparator(true)));
}
TEST_F(VideoGLRendererPixelTest, FullyTransparentYUVARect) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
CreateTestYUVVideoDrawQuad_Striped(
shared_state, media::PIXEL_FORMAT_YV12A, true, false,
gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), pass.get(),
video_resource_updater_.get(), rect, rect, resource_provider_.get());
SolidColorDrawQuad* color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(shared_state, rect, rect, SK_ColorBLACK, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("black.png")),
ExactPixelComparator(true)));
}
TEST_F(VideoGLRendererPixelTest, TwoColorY16Rect) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
gfx::Rect upper_rect(rect.x(), rect.y(), rect.width(), rect.height() / 2);
CreateTestY16TextureDrawQuad_TwoColor(
shared_state, gfx::RectF(0.0f, 0.0f, 1.0f, 1.0f), 68, 123, pass.get(),
video_resource_updater_.get(), rect, rect, upper_rect,
resource_provider_.get());
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("blue_yellow_filter_chain.png")),
FuzzyPixelOffByOneComparator(true)));
}
TYPED_TEST(RendererPixelTest, FastPassColorFilterAlpha) {
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
SkScalar matrix[20];
float amount = 0.5f;
matrix[0] = 0.213f + 0.787f * amount;
matrix[1] = 0.715f - 0.715f * amount;
matrix[2] = 1.f - (matrix[0] + matrix[1]);
matrix[3] = matrix[4] = 0;
matrix[5] = 0.213f - 0.213f * amount;
matrix[6] = 0.715f + 0.285f * amount;
matrix[7] = 1.f - (matrix[5] + matrix[6]);
matrix[8] = matrix[9] = 0;
matrix[10] = 0.213f - 0.213f * amount;
matrix[11] = 0.715f - 0.715f * amount;
matrix[12] = 1.f - (matrix[10] + matrix[11]);
matrix[13] = matrix[14] = 0;
matrix[15] = matrix[16] = matrix[17] = matrix[19] = 0;
matrix[18] = 1;
FilterOperations filters;
filters.Append(
FilterOperation::CreateReferenceFilter(SkColorFilterImageFilter::Make(
SkColorFilter::MakeMatrixFilterRowMajor255(matrix), nullptr)));
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
child_pass->filters = filters;
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
shared_state->opacity = 0.5f;
gfx::Rect blue_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
gfx::Rect yellow_rect(0,
this->device_viewport_size_.height() / 2,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* yellow =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(shared_state, yellow_rect, yellow_rect, SK_ColorYELLOW, false);
SharedQuadState* blank_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
SolidColorDrawQuad* white =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
white->SetNew(
blank_state, viewport_rect, viewport_rect, SK_ColorWHITE, false);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(gfx::Transform(), pass_rect, root_pass.get());
RenderPassDrawQuad* render_pass_quad =
root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
render_pass_quad->SetNew(pass_shared_state, pass_rect, pass_rect,
child_pass_id, 0, gfx::RectF(), gfx::Size(),
gfx::Vector2dF(), gfx::PointF(), gfx::RectF());
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
// This test has alpha=254 for the software renderer vs. alpha=255 for the gl
// renderer so use a fuzzy comparator.
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("blue_yellow_alpha.png")),
FuzzyForSoftwareOnlyPixelComparator<TypeParam>(false)));
}
TYPED_TEST(RendererPixelTest, FastPassSaturateFilter) {
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
FilterOperations filters;
filters.Append(FilterOperation::CreateSaturateFilter(0.5f));
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
child_pass->filters = filters;
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
shared_state->opacity = 0.5f;
gfx::Rect blue_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
gfx::Rect yellow_rect(0,
this->device_viewport_size_.height() / 2,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* yellow =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(shared_state, yellow_rect, yellow_rect, SK_ColorYELLOW, false);
SharedQuadState* blank_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
SolidColorDrawQuad* white =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
white->SetNew(
blank_state, viewport_rect, viewport_rect, SK_ColorWHITE, false);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(gfx::Transform(), pass_rect, root_pass.get());
RenderPassDrawQuad* render_pass_quad =
root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
render_pass_quad->SetNew(pass_shared_state, pass_rect, pass_rect,
child_pass_id, 0, gfx::RectF(), gfx::Size(),
gfx::Vector2dF(), gfx::PointF(), gfx::RectF());
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
// This test blends slightly differently with the software renderer vs. the gl
// renderer so use a fuzzy comparator.
EXPECT_TRUE(this->RunPixelTest(
&pass_list, base::FilePath(FILE_PATH_LITERAL("blue_yellow_alpha.png")),
FuzzyForSoftwareOnlyPixelComparator<TypeParam>(false)));
}
TYPED_TEST(RendererPixelTest, FastPassFilterChain) {
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
FilterOperations filters;
filters.Append(FilterOperation::CreateGrayscaleFilter(1.f));
filters.Append(FilterOperation::CreateBrightnessFilter(0.5f));
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
child_pass->filters = filters;
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
shared_state->opacity = 0.5f;
gfx::Rect blue_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
gfx::Rect yellow_rect(0,
this->device_viewport_size_.height() / 2,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* yellow =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(shared_state, yellow_rect, yellow_rect, SK_ColorYELLOW, false);
SharedQuadState* blank_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
SolidColorDrawQuad* white =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
white->SetNew(
blank_state, viewport_rect, viewport_rect, SK_ColorWHITE, false);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(gfx::Transform(), pass_rect, root_pass.get());
RenderPassDrawQuad* render_pass_quad =
root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
render_pass_quad->SetNew(pass_shared_state, pass_rect, pass_rect,
child_pass_id, 0, gfx::RectF(), gfx::Size(),
gfx::Vector2dF(), gfx::PointF(), gfx::RectF());
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
// This test blends slightly differently with the software renderer vs. the gl
// renderer so use a fuzzy comparator.
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("blue_yellow_filter_chain.png")),
FuzzyForSoftwareOnlyPixelComparator<TypeParam>(false)));
}
TYPED_TEST(RendererPixelTest, FastPassColorFilterAlphaTranslation) {
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
SkScalar matrix[20];
float amount = 0.5f;
matrix[0] = 0.213f + 0.787f * amount;
matrix[1] = 0.715f - 0.715f * amount;
matrix[2] = 1.f - (matrix[0] + matrix[1]);
matrix[3] = 0;
matrix[4] = 20.f;
matrix[5] = 0.213f - 0.213f * amount;
matrix[6] = 0.715f + 0.285f * amount;
matrix[7] = 1.f - (matrix[5] + matrix[6]);
matrix[8] = 0;
matrix[9] = 200.f;
matrix[10] = 0.213f - 0.213f * amount;
matrix[11] = 0.715f - 0.715f * amount;
matrix[12] = 1.f - (matrix[10] + matrix[11]);
matrix[13] = 0;
matrix[14] = 1.5f;
matrix[15] = matrix[16] = matrix[17] = matrix[19] = 0;
matrix[18] = 1;
FilterOperations filters;
filters.Append(
FilterOperation::CreateReferenceFilter(SkColorFilterImageFilter::Make(
SkColorFilter::MakeMatrixFilterRowMajor255(matrix), nullptr)));
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
child_pass->filters = filters;
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
shared_state->opacity = 0.5f;
gfx::Rect blue_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
gfx::Rect yellow_rect(0,
this->device_viewport_size_.height() / 2,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* yellow =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(shared_state, yellow_rect, yellow_rect, SK_ColorYELLOW, false);
SharedQuadState* blank_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
SolidColorDrawQuad* white =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
white->SetNew(
blank_state, viewport_rect, viewport_rect, SK_ColorWHITE, false);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(gfx::Transform(), pass_rect, root_pass.get());
RenderPassDrawQuad* render_pass_quad =
root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
render_pass_quad->SetNew(pass_shared_state, pass_rect, pass_rect,
child_pass_id, 0, gfx::RectF(), gfx::Size(),
gfx::Vector2dF(), gfx::PointF(), gfx::RectF());
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
// This test has alpha=254 for the software renderer vs. alpha=255 for the gl
// renderer so use a fuzzy comparator.
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("blue_yellow_alpha_translate.png")),
FuzzyForSoftwareOnlyPixelComparator<TypeParam>(false)));
}
TYPED_TEST(RendererPixelTest, EnlargedRenderPassTexture) {
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
gfx::Rect blue_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
gfx::Rect yellow_rect(0,
this->device_viewport_size_.height() / 2,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* yellow =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(shared_state, yellow_rect, yellow_rect, SK_ColorYELLOW, false);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(gfx::Transform(), pass_rect, root_pass.get());
CreateTestRenderPassDrawQuad(
pass_shared_state, pass_rect, child_pass_id, root_pass.get());
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
this->renderer_->SetEnlargePassTextureAmountForTesting(gfx::Size(50, 75));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("blue_yellow.png")),
ExactPixelComparator(true)));
}
TYPED_TEST(RendererPixelTest, EnlargedRenderPassTextureWithAntiAliasing) {
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
gfx::Rect blue_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
gfx::Rect yellow_rect(0,
this->device_viewport_size_.height() / 2,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* yellow =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(shared_state, yellow_rect, yellow_rect, SK_ColorYELLOW, false);
gfx::Transform aa_transform;
aa_transform.Translate(0.5, 0.0);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(aa_transform, pass_rect, root_pass.get());
CreateTestRenderPassDrawQuad(
pass_shared_state, pass_rect, child_pass_id, root_pass.get());
SharedQuadState* root_shared_state = CreateTestSharedQuadState(
gfx::Transform(), viewport_rect, root_pass.get());
SolidColorDrawQuad* background =
root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
background->SetNew(root_shared_state,
gfx::Rect(this->device_viewport_size_),
gfx::Rect(this->device_viewport_size_),
SK_ColorWHITE,
false);
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
this->renderer_->SetEnlargePassTextureAmountForTesting(gfx::Size(50, 75));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("blue_yellow_anti_aliasing.png")),
FuzzyPixelOffByOneComparator(true)));
}
// This tests the case where we have a RenderPass with a mask, but the quad
// for the masked surface does not include the full surface texture.
TYPED_TEST(RendererPixelTest, RenderPassAndMaskWithPartialQuad) {
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
SharedQuadState* root_pass_shared_state = CreateTestSharedQuadState(
gfx::Transform(), viewport_rect, root_pass.get());
int child_pass_id = 2;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, viewport_rect, transform_to_root);
SharedQuadState* child_pass_shared_state = CreateTestSharedQuadState(
gfx::Transform(), viewport_rect, child_pass.get());
// The child render pass is just a green box.
static const SkColor kCSSGreen = 0xff008000;
SolidColorDrawQuad* green =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
green->SetNew(
child_pass_shared_state, viewport_rect, viewport_rect, kCSSGreen, false);
// Make a mask.
gfx::Rect mask_rect = viewport_rect;
SkBitmap bitmap;
bitmap.allocPixels(
SkImageInfo::MakeN32Premul(mask_rect.width(), mask_rect.height()));
PaintCanvas canvas(bitmap);
PaintFlags flags;
flags.setStyle(PaintFlags::kStroke_Style);
flags.setStrokeWidth(SkIntToScalar(4));
flags.setColor(SK_ColorWHITE);
canvas.clear(SK_ColorTRANSPARENT);
gfx::Rect rect = mask_rect;
while (!rect.IsEmpty()) {
rect.Inset(6, 6, 4, 4);
canvas.drawRect(
SkRect::MakeXYWH(rect.x(), rect.y(), rect.width(), rect.height()),
flags);
rect.Inset(6, 6, 4, 4);
}
ResourceId mask_resource_id = this->resource_provider_->CreateResource(
mask_rect.size(), ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888,
gfx::ColorSpace());
{
SkAutoLockPixels lock(bitmap);
this->resource_provider_->CopyToResource(
mask_resource_id, reinterpret_cast<uint8_t*>(bitmap.getPixels()),
mask_rect.size());
}
// This RenderPassDrawQuad does not include the full |viewport_rect| which is
// the size of the child render pass.
gfx::Rect sub_rect = gfx::Rect(50, 50, 200, 100);
EXPECT_NE(sub_rect.x(), child_pass->output_rect.x());
EXPECT_NE(sub_rect.y(), child_pass->output_rect.y());
EXPECT_NE(sub_rect.right(), child_pass->output_rect.right());
EXPECT_NE(sub_rect.bottom(), child_pass->output_rect.bottom());
// Set up a mask on the RenderPassDrawQuad.
RenderPassDrawQuad* mask_quad =
root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
mask_quad->SetNew(
root_pass_shared_state, sub_rect, sub_rect, child_pass_id,
mask_resource_id,
gfx::ScaleRect(gfx::RectF(sub_rect), 2.f / mask_rect.width(),
2.f / mask_rect.height()), // mask_uv_rect
gfx::Size(mask_rect.size()), // mask_texture_size
gfx::Vector2dF(), // filters scale
gfx::PointF(), // filter origin
gfx::RectF()); // tex_coord_rect
// White background behind the masked render pass.
SolidColorDrawQuad* white =
root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
white->SetNew(root_pass_shared_state,
viewport_rect,
viewport_rect,
SK_ColorWHITE,
false);
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("mask_bottom_right.png")),
ExactPixelComparator(true)));
}
// This tests the case where we have a RenderPass with a mask, but the quad
// for the masked surface does not include the full surface texture.
TYPED_TEST(RendererPixelTest, RenderPassAndMaskWithPartialQuad2) {
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
SharedQuadState* root_pass_shared_state = CreateTestSharedQuadState(
gfx::Transform(), viewport_rect, root_pass.get());
int child_pass_id = 2;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, viewport_rect, transform_to_root);
SharedQuadState* child_pass_shared_state = CreateTestSharedQuadState(
gfx::Transform(), viewport_rect, child_pass.get());
// The child render pass is just a green box.
static const SkColor kCSSGreen = 0xff008000;
SolidColorDrawQuad* green =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
green->SetNew(child_pass_shared_state, viewport_rect, viewport_rect,
kCSSGreen, false);
// Make a mask.
gfx::Rect mask_rect = viewport_rect;
SkBitmap bitmap;
bitmap.allocPixels(
SkImageInfo::MakeN32Premul(mask_rect.width(), mask_rect.height()));
PaintCanvas canvas(bitmap);
PaintFlags flags;
flags.setStyle(PaintFlags::kStroke_Style);
flags.setStrokeWidth(SkIntToScalar(4));
flags.setColor(SK_ColorWHITE);
canvas.clear(SK_ColorTRANSPARENT);
gfx::Rect rect = mask_rect;
while (!rect.IsEmpty()) {
rect.Inset(6, 6, 4, 4);
canvas.drawRect(
SkRect::MakeXYWH(rect.x(), rect.y(), rect.width(), rect.height()),
flags);
rect.Inset(6, 6, 4, 4);
}
ResourceId mask_resource_id = this->resource_provider_->CreateResource(
mask_rect.size(), ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888,
gfx::ColorSpace());
{
SkAutoLockPixels lock(bitmap);
this->resource_provider_->CopyToResource(
mask_resource_id, reinterpret_cast<uint8_t*>(bitmap.getPixels()),
mask_rect.size());
}
// This RenderPassDrawQuad does not include the full |viewport_rect| which is
// the size of the child render pass.
gfx::Rect sub_rect = gfx::Rect(50, 20, 200, 60);
EXPECT_NE(sub_rect.x(), child_pass->output_rect.x());
EXPECT_NE(sub_rect.y(), child_pass->output_rect.y());
EXPECT_NE(sub_rect.right(), child_pass->output_rect.right());
EXPECT_NE(sub_rect.bottom(), child_pass->output_rect.bottom());
// Set up a mask on the RenderPassDrawQuad.
RenderPassDrawQuad* mask_quad =
root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
mask_quad->SetNew(
root_pass_shared_state, sub_rect, sub_rect, child_pass_id,
mask_resource_id,
gfx::ScaleRect(gfx::RectF(sub_rect), 2.f / mask_rect.width(),
2.f / mask_rect.height()), // mask_uv_rect
gfx::Size(mask_rect.size()), // mask_texture_size
gfx::Vector2dF(), // filters scale
gfx::PointF(), // filter origin
gfx::RectF()); // tex_coord_rect
// White background behind the masked render pass.
SolidColorDrawQuad* white =
root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
white->SetNew(root_pass_shared_state, viewport_rect, viewport_rect,
SK_ColorWHITE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list, base::FilePath(FILE_PATH_LITERAL("mask_middle.png")),
ExactPixelComparator(true)));
}
template <typename RendererType>
class RendererPixelTestWithBackgroundFilter
: public RendererPixelTest<RendererType> {
protected:
void SetUpRenderPassList() {
gfx::Rect device_viewport_rect(this->device_viewport_size_);
int root_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_id, device_viewport_rect);
root_pass->has_transparent_background = false;
gfx::Transform identity_quad_to_target_transform;
int filter_pass_id = 2;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> filter_pass = CreateTestRenderPass(
filter_pass_id, filter_pass_layer_rect_, transform_to_root);
filter_pass->background_filters = this->background_filters_;
// A non-visible quad in the filtering render pass.
{
SharedQuadState* shared_state =
CreateTestSharedQuadState(identity_quad_to_target_transform,
filter_pass_layer_rect_, filter_pass.get());
SolidColorDrawQuad* color_quad =
filter_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(shared_state, filter_pass_layer_rect_,
filter_pass_layer_rect_, SK_ColorTRANSPARENT, false);
}
{
SharedQuadState* shared_state =
CreateTestSharedQuadState(filter_pass_to_target_transform_,
filter_pass_layer_rect_, filter_pass.get());
RenderPassDrawQuad* filter_pass_quad =
root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
filter_pass_quad->SetNew(shared_state, filter_pass_layer_rect_,
filter_pass_layer_rect_, filter_pass_id,
0, // mask_resource_id
gfx::RectF(), // mask_uv_rect
gfx::Size(), // mask_texture_size
gfx::Vector2dF(1.0f, 1.0f), // filters_scale
gfx::PointF(), // filters_origin
gfx::RectF()); // tex_coord_rect
}
const int kColumnWidth = device_viewport_rect.width() / 3;
gfx::Rect left_rect = gfx::Rect(0, 0, kColumnWidth, 20);
for (int i = 0; left_rect.y() < device_viewport_rect.height(); ++i) {
SharedQuadState* shared_state = CreateTestSharedQuadState(
identity_quad_to_target_transform, left_rect, root_pass.get());
SolidColorDrawQuad* color_quad =
root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(
shared_state, left_rect, left_rect, SK_ColorGREEN, false);
left_rect += gfx::Vector2d(0, left_rect.height() + 1);
}
gfx::Rect middle_rect = gfx::Rect(kColumnWidth+1, 0, kColumnWidth, 20);
for (int i = 0; middle_rect.y() < device_viewport_rect.height(); ++i) {
SharedQuadState* shared_state = CreateTestSharedQuadState(
identity_quad_to_target_transform, middle_rect, root_pass.get());
SolidColorDrawQuad* color_quad =
root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(
shared_state, middle_rect, middle_rect, SK_ColorRED, false);
middle_rect += gfx::Vector2d(0, middle_rect.height() + 1);
}
gfx::Rect right_rect = gfx::Rect((kColumnWidth+1)*2, 0, kColumnWidth, 20);
for (int i = 0; right_rect.y() < device_viewport_rect.height(); ++i) {
SharedQuadState* shared_state = CreateTestSharedQuadState(
identity_quad_to_target_transform, right_rect, root_pass.get());
SolidColorDrawQuad* color_quad =
root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
color_quad->SetNew(
shared_state, right_rect, right_rect, SK_ColorBLUE, false);
right_rect += gfx::Vector2d(0, right_rect.height() + 1);
}
SharedQuadState* shared_state =
CreateTestSharedQuadState(identity_quad_to_target_transform,
device_viewport_rect, root_pass.get());
SolidColorDrawQuad* background_quad =
root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
background_quad->SetNew(shared_state,
device_viewport_rect,
device_viewport_rect,
SK_ColorWHITE,
false);
pass_list_.push_back(std::move(filter_pass));
pass_list_.push_back(std::move(root_pass));
}
RenderPassList pass_list_;
FilterOperations background_filters_;
gfx::Transform filter_pass_to_target_transform_;
gfx::Rect filter_pass_layer_rect_;
};
typedef ::testing::Types<GLRenderer, SoftwareRenderer>
BackgroundFilterRendererTypes;
TYPED_TEST_CASE(RendererPixelTestWithBackgroundFilter,
BackgroundFilterRendererTypes);
typedef RendererPixelTestWithBackgroundFilter<GLRenderer>
GLRendererPixelTestWithBackgroundFilter;
// TODO(skaslev): The software renderer does not support filters yet.
TEST_F(GLRendererPixelTestWithBackgroundFilter, InvertFilter) {
this->background_filters_.Append(
FilterOperation::CreateInvertFilter(1.f));
this->filter_pass_layer_rect_ = gfx::Rect(this->device_viewport_size_);
this->filter_pass_layer_rect_.Inset(12, 14, 16, 18);
this->SetUpRenderPassList();
EXPECT_TRUE(this->RunPixelTest(
&this->pass_list_,
base::FilePath(FILE_PATH_LITERAL("background_filter.png")),
ExactPixelComparator(true)));
}
class ExternalStencilPixelTest : public GLRendererPixelTest {
protected:
void ClearBackgroundToGreen() {
GLES2Interface* gl = output_surface_->context_provider()->ContextGL();
output_surface_->EnsureBackbuffer();
output_surface_->Reshape(device_viewport_size_, 1, gfx::ColorSpace(), true,
false);
gl->ClearColor(0.f, 1.f, 0.f, 1.f);
gl->Clear(GL_COLOR_BUFFER_BIT);
}
void PopulateStencilBuffer() {
// Set two quadrants of the stencil buffer to 1.
GLES2Interface* gl = output_surface_->context_provider()->ContextGL();
output_surface_->EnsureBackbuffer();
output_surface_->Reshape(device_viewport_size_, 1, gfx::ColorSpace(), true,
false);
gl->ClearStencil(0);
gl->Clear(GL_STENCIL_BUFFER_BIT);
gl->Enable(GL_SCISSOR_TEST);
gl->ClearStencil(1);
gl->Scissor(0,
0,
device_viewport_size_.width() / 2,
device_viewport_size_.height() / 2);
gl->Clear(GL_STENCIL_BUFFER_BIT);
gl->Scissor(device_viewport_size_.width() / 2,
device_viewport_size_.height() / 2,
device_viewport_size_.width(),
device_viewport_size_.height());
gl->Clear(GL_STENCIL_BUFFER_BIT);
gl->StencilFunc(GL_EQUAL, 1, 1);
}
};
TEST_F(ExternalStencilPixelTest, StencilTestEnabled) {
ClearBackgroundToGreen();
PopulateStencilBuffer();
this->EnableExternalStencilTest();
// Draw a blue quad that covers the entire device viewport. It should be
// clipped to the bottom left and top right corners by the external stencil.
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* blue_shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
SolidColorDrawQuad* blue =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(blue_shared_state, rect, rect, SK_ColorBLUE, false);
pass->has_transparent_background = false;
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers.png")),
ExactPixelComparator(true)));
}
TEST_F(ExternalStencilPixelTest, StencilTestDisabled) {
PopulateStencilBuffer();
// Draw a green quad that covers the entire device viewport. The stencil
// buffer should be ignored.
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* green_shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
SolidColorDrawQuad* green =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
green->SetNew(green_shared_state, rect, rect, SK_ColorGREEN, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("green.png")),
ExactPixelComparator(true)));
}
TEST_F(ExternalStencilPixelTest, RenderSurfacesIgnoreStencil) {
// The stencil test should apply only to the final render pass.
ClearBackgroundToGreen();
PopulateStencilBuffer();
this->EnableExternalStencilTest();
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
root_pass->has_transparent_background = false;
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
gfx::Rect blue_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height());
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(gfx::Transform(), pass_rect, root_pass.get());
CreateTestRenderPassDrawQuad(
pass_shared_state, pass_rect, child_pass_id, root_pass.get());
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers.png")),
ExactPixelComparator(true)));
}
// Software renderer does not support anti-aliased edges.
TEST_F(GLRendererPixelTest, AntiAliasing) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
gfx::Transform red_quad_to_target_transform;
red_quad_to_target_transform.Rotate(10);
SharedQuadState* red_shared_state =
CreateTestSharedQuadState(red_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* red = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
red->SetNew(red_shared_state, rect, rect, SK_ColorRED, false);
gfx::Transform yellow_quad_to_target_transform;
yellow_quad_to_target_transform.Rotate(5);
SharedQuadState* yellow_shared_state = CreateTestSharedQuadState(
yellow_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* yellow =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(yellow_shared_state, rect, rect, SK_ColorYELLOW, false);
gfx::Transform blue_quad_to_target_transform;
SharedQuadState* blue_shared_state = CreateTestSharedQuadState(
blue_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* blue =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(blue_shared_state, rect, rect, SK_ColorBLUE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("anti_aliasing.png")),
FuzzyPixelOffByOneComparator(true)));
}
// This test tests that anti-aliasing works for axis aligned quads.
// Anti-aliasing is only supported in the gl renderer.
TEST_F(GLRendererPixelTest, AxisAligned) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, rect, transform_to_root);
gfx::Transform red_quad_to_target_transform;
red_quad_to_target_transform.Translate(50, 50);
red_quad_to_target_transform.Scale(0.5f + 1.0f / (rect.width() * 2.0f),
0.5f + 1.0f / (rect.height() * 2.0f));
SharedQuadState* red_shared_state =
CreateTestSharedQuadState(red_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* red = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
red->SetNew(red_shared_state, rect, rect, SK_ColorRED, false);
gfx::Transform yellow_quad_to_target_transform;
yellow_quad_to_target_transform.Translate(25.5f, 25.5f);
yellow_quad_to_target_transform.Scale(0.5f, 0.5f);
SharedQuadState* yellow_shared_state = CreateTestSharedQuadState(
yellow_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* yellow =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(yellow_shared_state, rect, rect, SK_ColorYELLOW, false);
gfx::Transform blue_quad_to_target_transform;
SharedQuadState* blue_shared_state = CreateTestSharedQuadState(
blue_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* blue =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(blue_shared_state, rect, rect, SK_ColorBLUE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("axis_aligned.png")),
ExactPixelComparator(true)));
}
// This test tests that forcing anti-aliasing off works as expected.
// Anti-aliasing is only supported in the gl renderer.
TEST_F(GLRendererPixelTest, ForceAntiAliasingOff) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, rect, transform_to_root);
gfx::Transform hole_quad_to_target_transform;
hole_quad_to_target_transform.Translate(50, 50);
hole_quad_to_target_transform.Scale(0.5f + 1.0f / (rect.width() * 2.0f),
0.5f + 1.0f / (rect.height() * 2.0f));
SharedQuadState* hole_shared_state = CreateTestSharedQuadState(
hole_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* hole =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
hole->SetAll(
hole_shared_state, rect, rect, rect, false, SK_ColorTRANSPARENT, true);
gfx::Transform green_quad_to_target_transform;
SharedQuadState* green_shared_state = CreateTestSharedQuadState(
green_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* green =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
green->SetNew(green_shared_state, rect, rect, SK_ColorGREEN, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("force_anti_aliasing_off.png")),
ExactPixelComparator(false)));
}
TEST_F(GLRendererPixelTest, AntiAliasingPerspective) {
gfx::Rect rect(this->device_viewport_size_);
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(1, rect);
gfx::Rect red_rect(0, 0, 180, 500);
gfx::Transform red_quad_to_target_transform(
1.0f, 2.4520f, 10.6206f, 19.0f, 0.0f, 0.3528f, 5.9737f, 9.5f, 0.0f,
-0.2250f, -0.9744f, 0.0f, 0.0f, 0.0225f, 0.0974f, 1.0f);
SharedQuadState* red_shared_state = CreateTestSharedQuadState(
red_quad_to_target_transform, red_rect, pass.get());
SolidColorDrawQuad* red = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
red->SetNew(red_shared_state, red_rect, red_rect, SK_ColorRED, false);
gfx::Rect green_rect(19, 7, 180, 10);
SharedQuadState* green_shared_state =
CreateTestSharedQuadState(gfx::Transform(), green_rect, pass.get());
SolidColorDrawQuad* green =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
green->SetNew(
green_shared_state, green_rect, green_rect, SK_ColorGREEN, false);
SharedQuadState* blue_shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
SolidColorDrawQuad* blue =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(blue_shared_state, rect, rect, SK_ColorBLUE, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("anti_aliasing_perspective.png")),
FuzzyPixelOffByOneComparator(true)));
}
TYPED_TEST(SoftwareRendererPixelTest, PictureDrawQuadIdentityScale) {
gfx::Rect viewport(this->device_viewport_size_);
// TODO(enne): the renderer should figure this out on its own.
ResourceFormat texture_format = RGBA_8888;
bool nearest_neighbor = false;
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, viewport, transform_to_root);
// One clipped blue quad in the lower right corner. Outside the clip
// is red, which should not appear.
gfx::Rect blue_rect(gfx::Size(100, 100));
gfx::Rect blue_clip_rect(gfx::Point(50, 50), gfx::Size(50, 50));
std::unique_ptr<FakeRecordingSource> blue_recording =
FakeRecordingSource::CreateFilledRecordingSource(blue_rect.size());
PaintFlags red_flags;
red_flags.setColor(SK_ColorRED);
blue_recording->add_draw_rect_with_flags(blue_rect, red_flags);
PaintFlags blue_flags;
blue_flags.setColor(SK_ColorBLUE);
blue_recording->add_draw_rect_with_flags(blue_clip_rect, blue_flags);
blue_recording->Rerecord();
scoped_refptr<FakeRasterSource> blue_raster_source =
FakeRasterSource::CreateFromRecordingSource(blue_recording.get(), false);
gfx::Vector2d offset(viewport.bottom_right() - blue_rect.bottom_right());
gfx::Transform blue_quad_to_target_transform;
blue_quad_to_target_transform.Translate(offset.x(), offset.y());
gfx::Rect blue_target_clip_rect = MathUtil::MapEnclosingClippedRect(
blue_quad_to_target_transform, blue_clip_rect);
SharedQuadState* blue_shared_state =
CreateTestSharedQuadStateClipped(blue_quad_to_target_transform, blue_rect,
blue_target_clip_rect, pass.get());
PictureDrawQuad* blue_quad = pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
blue_quad->SetNew(blue_shared_state,
viewport, // Intentionally bigger than clip.
gfx::Rect(), viewport, gfx::RectF(viewport),
viewport.size(), nearest_neighbor, texture_format, viewport,
1.f, std::move(blue_raster_source));
// One viewport-filling green quad.
std::unique_ptr<FakeRecordingSource> green_recording =
FakeRecordingSource::CreateFilledRecordingSource(viewport.size());
PaintFlags green_flags;
green_flags.setColor(SK_ColorGREEN);
green_recording->add_draw_rect_with_flags(viewport, green_flags);
green_recording->Rerecord();
scoped_refptr<FakeRasterSource> green_raster_source =
FakeRasterSource::CreateFromRecordingSource(green_recording.get(), false);
gfx::Transform green_quad_to_target_transform;
SharedQuadState* green_shared_state = CreateTestSharedQuadState(
green_quad_to_target_transform, viewport, pass.get());
PictureDrawQuad* green_quad =
pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
green_quad->SetNew(green_shared_state, viewport, gfx::Rect(), viewport,
gfx::RectF(0.f, 0.f, 1.f, 1.f), viewport.size(),
nearest_neighbor, texture_format, viewport, 1.f,
std::move(green_raster_source));
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("green_with_blue_corner.png")),
ExactPixelComparator(true)));
}
// Not WithSkiaGPUBackend since that path currently requires tiles for opacity.
TYPED_TEST(SoftwareRendererPixelTest, PictureDrawQuadOpacity) {
gfx::Rect viewport(this->device_viewport_size_);
ResourceFormat texture_format = RGBA_8888;
bool nearest_neighbor = false;
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, viewport, transform_to_root);
// One viewport-filling 0.5-opacity green quad.
std::unique_ptr<FakeRecordingSource> green_recording =
FakeRecordingSource::CreateFilledRecordingSource(viewport.size());
PaintFlags green_flags;
green_flags.setColor(SK_ColorGREEN);
green_recording->add_draw_rect_with_flags(viewport, green_flags);
green_recording->Rerecord();
scoped_refptr<FakeRasterSource> green_raster_source =
FakeRasterSource::CreateFromRecordingSource(green_recording.get(), false);
gfx::Transform green_quad_to_target_transform;
SharedQuadState* green_shared_state = CreateTestSharedQuadState(
green_quad_to_target_transform, viewport, pass.get());
green_shared_state->opacity = 0.5f;
PictureDrawQuad* green_quad =
pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
green_quad->SetNew(green_shared_state, viewport, gfx::Rect(), viewport,
gfx::RectF(0, 0, 1, 1), viewport.size(), nearest_neighbor,
texture_format, viewport, 1.f, green_raster_source.get());
// One viewport-filling white quad.
std::unique_ptr<FakeRecordingSource> white_recording =
FakeRecordingSource::CreateFilledRecordingSource(viewport.size());
PaintFlags white_flags;
white_flags.setColor(SK_ColorWHITE);
white_recording->add_draw_rect_with_flags(viewport, white_flags);
white_recording->Rerecord();
scoped_refptr<FakeRasterSource> white_raster_source =
FakeRasterSource::CreateFromRecordingSource(white_recording.get(), false);
gfx::Transform white_quad_to_target_transform;
SharedQuadState* white_shared_state = CreateTestSharedQuadState(
white_quad_to_target_transform, viewport, pass.get());
PictureDrawQuad* white_quad =
pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
white_quad->SetNew(white_shared_state, viewport, gfx::Rect(), viewport,
gfx::RectF(0, 0, 1, 1), viewport.size(), nearest_neighbor,
texture_format, viewport, 1.f,
std::move(white_raster_source));
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("green_alpha.png")),
FuzzyPixelOffByOneComparator(true)));
}
template<typename TypeParam> bool IsSoftwareRenderer() {
return false;
}
template<>
bool IsSoftwareRenderer<SoftwareRenderer>() {
return true;
}
template<>
bool IsSoftwareRenderer<SoftwareRendererWithExpandedViewport>() {
return true;
}
void draw_point_color(SkCanvas* canvas, SkScalar x, SkScalar y, SkColor color) {
SkPaint paint;
paint.setColor(color);
canvas->drawPoint(x, y, paint);
}
// If we disable image filtering, then a 2x2 bitmap should appear as four
// huge sharp squares.
TYPED_TEST(SoftwareRendererPixelTest, PictureDrawQuadDisableImageFiltering) {
// We only care about this in software mode since bilinear filtering is
// cheap in hardware.
if (!IsSoftwareRenderer<TypeParam>())
return;
gfx::Rect viewport(this->device_viewport_size_);
ResourceFormat texture_format = RGBA_8888;
bool nearest_neighbor = false;
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, viewport, transform_to_root);
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(2, 2);
ASSERT_NE(surface, nullptr);
SkCanvas* canvas = surface->getCanvas();
draw_point_color(canvas, 0, 0, SK_ColorGREEN);
draw_point_color(canvas, 0, 1, SK_ColorBLUE);
draw_point_color(canvas, 1, 0, SK_ColorBLUE);
draw_point_color(canvas, 1, 1, SK_ColorGREEN);
std::unique_ptr<FakeRecordingSource> recording =
FakeRecordingSource::CreateFilledRecordingSource(viewport.size());
PaintFlags flags;
flags.setFilterQuality(kLow_SkFilterQuality);
recording->add_draw_image_with_flags(surface->makeImageSnapshot(),
gfx::Point(), flags);
recording->Rerecord();
scoped_refptr<FakeRasterSource> raster_source =
FakeRasterSource::CreateFromRecordingSource(recording.get(), false);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state =
CreateTestSharedQuadState(quad_to_target_transform, viewport, pass.get());
PictureDrawQuad* quad = pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
quad->SetNew(shared_state, viewport, gfx::Rect(), viewport,
gfx::RectF(0, 0, 2, 2), viewport.size(), nearest_neighbor,
texture_format, viewport, 1.f, std::move(raster_source));
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
this->disable_picture_quad_image_filtering_ = true;
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers.png")),
ExactPixelComparator(true)));
}
// This disables filtering by setting |nearest_neighbor| on the PictureDrawQuad.
TYPED_TEST(SoftwareRendererPixelTest, PictureDrawQuadNearestNeighbor) {
gfx::Rect viewport(this->device_viewport_size_);
ResourceFormat texture_format = RGBA_8888;
bool nearest_neighbor = true;
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, viewport, transform_to_root);
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(2, 2);
ASSERT_NE(surface, nullptr);
SkCanvas* canvas = surface->getCanvas();
draw_point_color(canvas, 0, 0, SK_ColorGREEN);
draw_point_color(canvas, 0, 1, SK_ColorBLUE);
draw_point_color(canvas, 1, 0, SK_ColorBLUE);
draw_point_color(canvas, 1, 1, SK_ColorGREEN);
std::unique_ptr<FakeRecordingSource> recording =
FakeRecordingSource::CreateFilledRecordingSource(viewport.size());
PaintFlags flags;
flags.setFilterQuality(kLow_SkFilterQuality);
recording->add_draw_image_with_flags(surface->makeImageSnapshot(),
gfx::Point(), flags);
recording->Rerecord();
scoped_refptr<FakeRasterSource> raster_source =
FakeRasterSource::CreateFromRecordingSource(recording.get(), false);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state =
CreateTestSharedQuadState(quad_to_target_transform, viewport, pass.get());
PictureDrawQuad* quad = pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
quad->SetNew(shared_state, viewport, gfx::Rect(), viewport,
gfx::RectF(0, 0, 2, 2), viewport.size(), nearest_neighbor,
texture_format, viewport, 1.f, std::move(raster_source));
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers.png")),
ExactPixelComparator(true)));
}
// This disables filtering by setting |nearest_neighbor| on the TileDrawQuad.
TYPED_TEST(RendererPixelTest, TileDrawQuadNearestNeighbor) {
gfx::Rect viewport(this->device_viewport_size_);
bool swizzle_contents = true;
bool nearest_neighbor = true;
SkBitmap bitmap;
bitmap.allocN32Pixels(2, 2);
{
SkAutoLockPixels lock(bitmap);
SkCanvas canvas(bitmap);
draw_point_color(&canvas, 0, 0, SK_ColorGREEN);
draw_point_color(&canvas, 0, 1, SK_ColorBLUE);
draw_point_color(&canvas, 1, 0, SK_ColorBLUE);
draw_point_color(&canvas, 1, 1, SK_ColorGREEN);
}
gfx::Size tile_size(2, 2);
ResourceId resource = this->resource_provider_->CreateResource(
tile_size, ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888,
gfx::ColorSpace());
{
SkAutoLockPixels lock(bitmap);
this->resource_provider_->CopyToResource(
resource, static_cast<uint8_t*>(bitmap.getPixels()), tile_size);
}
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, viewport, transform_to_root);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state =
CreateTestSharedQuadState(quad_to_target_transform, viewport, pass.get());
TileDrawQuad* quad = pass->CreateAndAppendDrawQuad<TileDrawQuad>();
quad->SetNew(shared_state, viewport, gfx::Rect(), viewport, resource,
gfx::RectF(gfx::Rect(tile_size)), tile_size, swizzle_contents,
nearest_neighbor);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers.png")),
ExactPixelComparator(true)));
}
// This disables filtering by setting |nearest_neighbor| to true on the
// TextureDrawQuad.
TYPED_TEST(SoftwareRendererPixelTest, TextureDrawQuadNearestNeighbor) {
gfx::Rect viewport(this->device_viewport_size_);
bool nearest_neighbor = true;
SkBitmap bitmap;
bitmap.allocN32Pixels(2, 2);
{
SkAutoLockPixels lock(bitmap);
SkCanvas canvas(bitmap);
draw_point_color(&canvas, 0, 0, SK_ColorGREEN);
draw_point_color(&canvas, 0, 1, SK_ColorBLUE);
draw_point_color(&canvas, 1, 0, SK_ColorBLUE);
draw_point_color(&canvas, 1, 1, SK_ColorGREEN);
}
gfx::Size tile_size(2, 2);
ResourceId resource = this->resource_provider_->CreateResource(
tile_size, ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888,
gfx::ColorSpace());
{
SkAutoLockPixels lock(bitmap);
this->resource_provider_->CopyToResource(
resource, static_cast<uint8_t*>(bitmap.getPixels()), tile_size);
}
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, viewport, transform_to_root);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state =
CreateTestSharedQuadState(quad_to_target_transform, viewport, pass.get());
float vertex_opacity[4] = {1.0f, 1.0f, 1.0f, 1.0f};
TextureDrawQuad* quad = pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
quad->SetNew(shared_state, viewport, gfx::Rect(), viewport, resource, false,
gfx::PointF(0, 0), gfx::PointF(1, 1), SK_ColorBLACK,
vertex_opacity, false, nearest_neighbor, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers.png")),
FuzzyPixelComparator(false, 2.f, 0.f, 256.f, 256, 0.f)));
}
// This ensures filtering is enabled by setting |nearest_neighbor| to false on
// the TextureDrawQuad.
TYPED_TEST(SoftwareRendererPixelTest, TextureDrawQuadLinear) {
gfx::Rect viewport(this->device_viewport_size_);
bool nearest_neighbor = false;
SkBitmap bitmap;
bitmap.allocN32Pixels(2, 2);
{
SkAutoLockPixels lock(bitmap);
SkCanvas canvas(bitmap);
draw_point_color(&canvas, 0, 0, SK_ColorGREEN);
draw_point_color(&canvas, 0, 1, SK_ColorBLUE);
draw_point_color(&canvas, 1, 0, SK_ColorBLUE);
draw_point_color(&canvas, 1, 1, SK_ColorGREEN);
}
gfx::Size tile_size(2, 2);
ResourceId resource = this->resource_provider_->CreateResource(
tile_size, ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888,
gfx::ColorSpace());
{
SkAutoLockPixels lock(bitmap);
this->resource_provider_->CopyToResource(
resource, static_cast<uint8_t*>(bitmap.getPixels()), tile_size);
}
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, viewport, transform_to_root);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state =
CreateTestSharedQuadState(quad_to_target_transform, viewport, pass.get());
float vertex_opacity[4] = {1.0f, 1.0f, 1.0f, 1.0f};
TextureDrawQuad* quad = pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
quad->SetNew(shared_state, viewport, gfx::Rect(), viewport, resource, false,
gfx::PointF(0, 0), gfx::PointF(1, 1), SK_ColorBLACK,
vertex_opacity, false, nearest_neighbor, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
// Allow for a small amount of error as the blending alogrithm used by Skia is
// affected by the offset in the expanded rect.
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers_linear.png")),
FuzzyPixelComparator(false, 100.f, 0.f, 16.f, 16.f, 0.f)));
}
TYPED_TEST(SoftwareRendererPixelTest, PictureDrawQuadNonIdentityScale) {
gfx::Rect viewport(this->device_viewport_size_);
// TODO(enne): the renderer should figure this out on its own.
ResourceFormat texture_format = RGBA_8888;
bool nearest_neighbor = false;
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, viewport, transform_to_root);
// As scaling up the blue checkerboards will cause sampling on the GPU,
// a few extra "cleanup rects" need to be added to clobber the blending
// to make the output image more clean. This will also test subrects
// of the layer.
gfx::Transform green_quad_to_target_transform;
gfx::Rect green_rect1(gfx::Point(80, 0), gfx::Size(20, 100));
gfx::Rect green_rect2(gfx::Point(0, 80), gfx::Size(100, 20));
std::unique_ptr<FakeRecordingSource> green_recording =
FakeRecordingSource::CreateFilledRecordingSource(viewport.size());
PaintFlags red_flags;
red_flags.setColor(SK_ColorRED);
green_recording->add_draw_rect_with_flags(viewport, red_flags);
PaintFlags green_flags;
green_flags.setColor(SK_ColorGREEN);
green_recording->add_draw_rect_with_flags(green_rect1, green_flags);
green_recording->add_draw_rect_with_flags(green_rect2, green_flags);
green_recording->Rerecord();
scoped_refptr<FakeRasterSource> green_raster_source =
FakeRasterSource::CreateFromRecordingSource(green_recording.get(), false);
SharedQuadState* top_right_green_shared_quad_state =
CreateTestSharedQuadState(green_quad_to_target_transform, viewport,
pass.get());
PictureDrawQuad* green_quad1 =
pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
green_quad1->SetNew(
top_right_green_shared_quad_state, green_rect1, gfx::Rect(), green_rect1,
gfx::RectF(gfx::SizeF(green_rect1.size())), green_rect1.size(),
nearest_neighbor, texture_format, green_rect1, 1.f, green_raster_source);
PictureDrawQuad* green_quad2 =
pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
green_quad2->SetNew(top_right_green_shared_quad_state, green_rect2,
gfx::Rect(), green_rect2,
gfx::RectF(gfx::SizeF(green_rect2.size())),
green_rect2.size(), nearest_neighbor, texture_format,
green_rect2, 1.f, std::move(green_raster_source));
// Add a green clipped checkerboard in the bottom right to help test
// interleaving picture quad content and solid color content.
gfx::Rect bottom_right_rect(
gfx::Point(viewport.width() / 2, viewport.height() / 2),
gfx::Size(viewport.width() / 2, viewport.height() / 2));
SharedQuadState* bottom_right_green_shared_state =
CreateTestSharedQuadStateClipped(green_quad_to_target_transform, viewport,
bottom_right_rect, pass.get());
SolidColorDrawQuad* bottom_right_color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
bottom_right_color_quad->SetNew(bottom_right_green_shared_state,
viewport,
viewport,
SK_ColorGREEN,
false);
// Add two blue checkerboards taking up the bottom left and top right,
// but use content scales as content rects to make this happen.
// The content is at a 4x content scale.
gfx::Rect layer_rect(gfx::Size(20, 30));
float contents_scale = 4.f;
// Two rects that touch at their corners, arbitrarily placed in the layer.
gfx::RectF blue_layer_rect1(gfx::PointF(5.5f, 9.0f), gfx::SizeF(2.5f, 2.5f));
gfx::RectF blue_layer_rect2(gfx::PointF(8.0f, 6.5f), gfx::SizeF(2.5f, 2.5f));
gfx::RectF union_layer_rect = blue_layer_rect1;
union_layer_rect.Union(blue_layer_rect2);
// Because scaling up will cause sampling outside the rects, add one extra
// pixel of buffer at the final content scale.
float inset = -1.f / contents_scale;
blue_layer_rect1.Inset(inset, inset, inset, inset);
blue_layer_rect2.Inset(inset, inset, inset, inset);
std::unique_ptr<FakeRecordingSource> recording =
FakeRecordingSource::CreateFilledRecordingSource(layer_rect.size());
Region outside(layer_rect);
outside.Subtract(gfx::ToEnclosingRect(union_layer_rect));
for (Region::Iterator iter(outside); iter.has_rect(); iter.next()) {
recording->add_draw_rect_with_flags(iter.rect(), red_flags);
}
PaintFlags blue_flags;
blue_flags.setColor(SK_ColorBLUE);
recording->add_draw_rectf_with_flags(blue_layer_rect1, blue_flags);
recording->add_draw_rectf_with_flags(blue_layer_rect2, blue_flags);
recording->Rerecord();
scoped_refptr<FakeRasterSource> raster_source =
FakeRasterSource::CreateFromRecordingSource(recording.get(), false);
gfx::Rect content_union_rect(
gfx::ToEnclosingRect(gfx::ScaleRect(union_layer_rect, contents_scale)));
// At a scale of 4x the rectangles with a width of 2.5 will take up 10 pixels,
// so scale an additional 10x to make them 100x100.
gfx::Transform quad_to_target_transform;
quad_to_target_transform.Scale(10.0, 10.0);
gfx::Rect quad_content_rect(gfx::Size(20, 20));
SharedQuadState* blue_shared_state = CreateTestSharedQuadState(
quad_to_target_transform, quad_content_rect, pass.get());
PictureDrawQuad* blue_quad = pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
blue_quad->SetNew(blue_shared_state, quad_content_rect, gfx::Rect(),
quad_content_rect, gfx::RectF(quad_content_rect),
content_union_rect.size(), nearest_neighbor, texture_format,
content_union_rect, contents_scale,
std::move(raster_source));
// Fill left half of viewport with green.
gfx::Transform half_green_quad_to_target_transform;
gfx::Rect half_green_rect(gfx::Size(viewport.width() / 2, viewport.height()));
SharedQuadState* half_green_shared_state = CreateTestSharedQuadState(
half_green_quad_to_target_transform, half_green_rect, pass.get());
SolidColorDrawQuad* half_color_quad =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
half_color_quad->SetNew(half_green_shared_state,
half_green_rect,
half_green_rect,
SK_ColorGREEN,
false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers.png")),
ExactPixelComparator(true)));
}
typedef RendererPixelTest<GLRendererWithFlippedSurface>
GLRendererPixelTestWithFlippedOutputSurface;
TEST_F(GLRendererPixelTestWithFlippedOutputSurface, ExplicitFlipTest) {
// This draws a blue rect above a yellow rect with an inverted output surface.
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
gfx::Rect blue_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
gfx::Rect yellow_rect(0,
this->device_viewport_size_.height() / 2,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* yellow =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(shared_state, yellow_rect, yellow_rect, SK_ColorYELLOW, false);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(gfx::Transform(), pass_rect, root_pass.get());
CreateTestRenderPassDrawQuad(
pass_shared_state, pass_rect, child_pass_id, root_pass.get());
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list,
base::FilePath(FILE_PATH_LITERAL("blue_yellow_flipped.png")),
ExactPixelComparator(true)));
}
TEST_F(GLRendererPixelTestWithFlippedOutputSurface, CheckChildPassUnflipped) {
// This draws a blue rect above a yellow rect with an inverted output surface.
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
gfx::Rect blue_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
gfx::Rect yellow_rect(0,
this->device_viewport_size_.height() / 2,
this->device_viewport_size_.width(),
this->device_viewport_size_.height() / 2);
SolidColorDrawQuad* yellow =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
yellow->SetNew(shared_state, yellow_rect, yellow_rect, SK_ColorYELLOW, false);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(gfx::Transform(), pass_rect, root_pass.get());
CreateTestRenderPassDrawQuad(
pass_shared_state, pass_rect, child_pass_id, root_pass.get());
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
// Check that the child pass remains unflipped.
EXPECT_TRUE(this->RunPixelTestWithReadbackTarget(
&pass_list, pass_list.front().get(),
base::FilePath(FILE_PATH_LITERAL("blue_yellow.png")),
ExactPixelComparator(true)));
}
TEST_F(GLRendererPixelTest, CheckReadbackSubset) {
gfx::Rect viewport_rect(this->device_viewport_size_);
int root_pass_id = 1;
std::unique_ptr<RenderPass> root_pass =
CreateTestRootRenderPass(root_pass_id, viewport_rect);
int child_pass_id = 2;
gfx::Rect pass_rect(this->device_viewport_size_);
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> child_pass =
CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root);
gfx::Transform quad_to_target_transform;
SharedQuadState* shared_state = CreateTestSharedQuadState(
quad_to_target_transform, viewport_rect, child_pass.get());
// Draw a green quad full-size with a blue quad in the lower-right corner.
gfx::Rect blue_rect(this->device_viewport_size_.width() * 3 / 4,
this->device_viewport_size_.height() * 3 / 4,
this->device_viewport_size_.width() * 3 / 4,
this->device_viewport_size_.height() * 3 / 4);
SolidColorDrawQuad* blue =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
blue->SetNew(shared_state, blue_rect, blue_rect, SK_ColorBLUE, false);
gfx::Rect green_rect(0,
0,
this->device_viewport_size_.width(),
this->device_viewport_size_.height());
SolidColorDrawQuad* green =
child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
green->SetNew(shared_state, green_rect, green_rect, SK_ColorGREEN, false);
SharedQuadState* pass_shared_state =
CreateTestSharedQuadState(gfx::Transform(), pass_rect, root_pass.get());
CreateTestRenderPassDrawQuad(
pass_shared_state, pass_rect, child_pass_id, root_pass.get());
RenderPassList pass_list;
pass_list.push_back(std::move(child_pass));
pass_list.push_back(std::move(root_pass));
// Check that the child pass remains unflipped.
gfx::Rect capture_rect(this->device_viewport_size_.width() / 2,
this->device_viewport_size_.height() / 2,
this->device_viewport_size_.width() / 2,
this->device_viewport_size_.height() / 2);
EXPECT_TRUE(this->RunPixelTestWithReadbackTargetAndArea(
&pass_list, pass_list.front().get(),
base::FilePath(FILE_PATH_LITERAL("green_small_with_blue_corner.png")),
ExactPixelComparator(true), &capture_rect));
}
TEST_F(GLRendererPixelTest, TextureQuadBatching) {
// This test verifies that multiple texture quads using the same resource
// get drawn correctly. It implicitly is trying to test that the
// GLRenderer does the right thing with its draw quad cache.
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect);
SharedQuadState* shared_state =
CreateTestSharedQuadState(gfx::Transform(), rect, pass.get());
// Make a mask.
gfx::Rect mask_rect = rect;
SkBitmap bitmap;
bitmap.allocPixels(
SkImageInfo::MakeN32Premul(mask_rect.width(), mask_rect.height()));
SkCanvas canvas(bitmap);
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SkIntToScalar(4));
paint.setColor(SK_ColorGREEN);
canvas.clear(SK_ColorWHITE);
gfx::Rect inset_rect = rect;
while (!inset_rect.IsEmpty()) {
inset_rect.Inset(6, 6, 4, 4);
canvas.drawRect(SkRect::MakeXYWH(inset_rect.x(), inset_rect.y(),
inset_rect.width(), inset_rect.height()),
paint);
inset_rect.Inset(6, 6, 4, 4);
}
ResourceId resource = this->resource_provider_->CreateResource(
mask_rect.size(), ResourceProvider::TEXTURE_HINT_IMMUTABLE, RGBA_8888,
gfx::ColorSpace());
{
SkAutoLockPixels lock(bitmap);
this->resource_provider_->CopyToResource(
resource, reinterpret_cast<uint8_t*>(bitmap.getPixels()),
mask_rect.size());
}
// Arbitrary dividing lengths to divide up the resource into 16 quads.
int widths[] = {
0, 60, 50, 40,
};
int heights[] = {
0, 10, 80, 50,
};
size_t num_quads = 4;
for (size_t i = 0; i < num_quads; ++i) {
int x_start = widths[i];
int x_end = i == num_quads - 1 ? rect.width() : widths[i + 1];
DCHECK_LE(x_end, rect.width());
for (size_t j = 0; j < num_quads; ++j) {
int y_start = heights[j];
int y_end = j == num_quads - 1 ? rect.height() : heights[j + 1];
DCHECK_LE(y_end, rect.height());
float vertex_opacity[4] = {1.0f, 1.0f, 1.0f, 1.0f};
gfx::Rect layer_rect(x_start, y_start, x_end - x_start, y_end - y_start);
gfx::RectF uv_rect = gfx::ScaleRect(
gfx::RectF(layer_rect), 1.f / rect.width(), 1.f / rect.height());
TextureDrawQuad* texture_quad =
pass->CreateAndAppendDrawQuad<TextureDrawQuad>();
texture_quad->SetNew(shared_state, layer_rect, layer_rect, layer_rect,
resource, true, uv_rect.origin(),
uv_rect.bottom_right(), SK_ColorWHITE,
vertex_opacity, false, false, false);
}
}
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(
&pass_list, base::FilePath(FILE_PATH_LITERAL("spiral.png")),
FuzzyPixelOffByOneComparator(true)));
}
class GLRendererPixelTestWithOverdrawFeedback : public GLRendererPixelTest {
protected:
void SetUp() override {
settings_.renderer_settings.show_overdraw_feedback = true;
GLRendererPixelTest::SetUp();
}
};
TEST_F(GLRendererPixelTestWithOverdrawFeedback, TranslucentRectangles) {
gfx::Rect rect(this->device_viewport_size_);
int id = 1;
gfx::Transform transform_to_root;
std::unique_ptr<RenderPass> pass =
CreateTestRenderPass(id, rect, transform_to_root);
gfx::Transform dark_gray_quad_to_target_transform;
dark_gray_quad_to_target_transform.Translate(50, 50);
dark_gray_quad_to_target_transform.Scale(
0.5f + 1.0f / (rect.width() * 2.0f),
0.5f + 1.0f / (rect.height() * 2.0f));
SharedQuadState* dark_gray_shared_state = CreateTestSharedQuadState(
dark_gray_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* dark_gray =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
dark_gray->SetNew(dark_gray_shared_state, rect, rect, 0x10444444, false);
gfx::Transform light_gray_quad_to_target_transform;
light_gray_quad_to_target_transform.Translate(25.5f, 25.5f);
light_gray_quad_to_target_transform.Scale(0.5f, 0.5f);
SharedQuadState* light_gray_shared_state = CreateTestSharedQuadState(
light_gray_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* light_gray =
pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
light_gray->SetNew(light_gray_shared_state, rect, rect, 0x10CCCCCC, false);
gfx::Transform bg_quad_to_target_transform;
SharedQuadState* bg_shared_state =
CreateTestSharedQuadState(bg_quad_to_target_transform, rect, pass.get());
SolidColorDrawQuad* bg = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
bg->SetNew(bg_shared_state, rect, rect, SK_ColorBLACK, false);
RenderPassList pass_list;
pass_list.push_back(std::move(pass));
EXPECT_TRUE(this->RunPixelTest(&pass_list, base::FilePath(FILE_PATH_LITERAL(
"translucent_rectangles.png")),
ExactPixelComparator(true)));
}
#endif // !defined(OS_ANDROID)
} // namespace
} // namespace cc
| [
"hedonist.ky@gmail.com"
] | hedonist.ky@gmail.com |
36430a32ad03c823d411e692a7719e528b03b733 | 8f02939917edda1e714ffc26f305ac6778986e2d | /competitions/ICPC/2021/seoul-regional/F.cc | 54cb85245f40f6e3384b7863b98b2e43bedf5b47 | [] | no_license | queuedq/ps | fd6ee880d67484d666970e7ef85459683fa5b106 | d45bd3037a389495d9937afa47cf0f74cd3f09cf | refs/heads/master | 2023-08-18T16:45:18.970261 | 2023-08-17T17:04:19 | 2023-08-17T17:04:19 | 134,966,734 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,201 | cc | #include <bits/stdc++.h>
#define endl "\n"
#define all(x) (x).begin(), (x).end()
using namespace std;
using lld = long long;
using pii = pair<int, int>;
using pll = pair<lld, lld>;
////////////////////////////////////////////////////////////////
const int MN = 1e6+5;
const int INF = 2e9;
int N, A[MN], B[MN], P[MN], S[MN], D[MN], E[MN];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
////////////////////////////////
cin >> N;
for (int i=1; i<=N; i++) cin >> A[i];
for (int j=1; j<=N; j++) cin >> B[j];
sort(A+1, A+N+1);
sort(B+1, B+N+1);
for (int i=1; i<=N; i++) P[i] = max(P[i-1], abs(A[i] - B[i]));
for (int i=N; i>=1; i--) S[i] = max(S[i+1], abs(A[i] - B[i]));
for (int i=1; i<=N-1; i++) {
D[i] = min(P[i], max(D[i-1], abs(A[i] - B[i+1])));
}
for (int i=N; i>=2; i--) {
E[i] = min(S[i], max(E[i+1], abs(A[i] - B[i-1])));
}
int mn = S[2], opt = 1;
for (int i=1; i<=N-1; i++) {
if (max(D[i], S[i+2]) < mn) { opt = i+1; mn = max(D[i], S[i+2]); }
}
for (int i=2; i<=N; i++) {
if (max(E[i], P[i-2]) < mn) { opt = i-1; mn = max(E[i], P[i-2]); }
}
cout << A[opt] << endl;
////////////////////////////////
return 0;
}
| [
"queuedq@gmail.com"
] | queuedq@gmail.com |
e798633b013ebce1327ade78cd7f9605bd1513b4 | 9593f022f5eafdc26dfa6a4a7acbe0a27fb9a196 | /outsourcing_security_system/outsourcing_system_test.cpp | 795cffc8ddf55890de30f39833130f3f2a74ac2a | [] | no_license | zhengyunhai/outsourcing_security_sys | 2da09144f84f48adad6c5b1f945d042d24184d78 | 04fc2b0f4c113b5d5ff8cd95db1004a3d2bf9a06 | refs/heads/master | 2020-09-11T22:14:34.558539 | 2019-11-17T06:40:52 | 2019-11-17T06:40:52 | 222,207,394 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,871 | cpp | /*基于NTL库的模指数外包的加密处理程序 just for fun*/
#include<NTL/ZZ.h>
#include<NTL/tools.h>
#include<NTL/LLL.h>
#include<time.h>
#include<iostream>
#include<fstream>
#include<sys/time.h>
#include<windows.h>
#include <cstdlib>
#include <cmath>
#include <NTL/config.h>
#include <NTL/mach_desc.h>
#include<NTL/matrix.h>
#include<NTL/mat_ZZ.h>
#include<NTL/vec_ZZ.h>
#include<NTL/vector.h>
NTL_CLIENT
void gen_pq(ZZ& p,ZZ& q,ZZ& g,int p_len,int q_len);
void randpairs(ZZ p,ZZ q,ZZ g,int n,vec_ZZ& k,vec_ZZ& gk);
void gen_ua(ZZ p,ZZ q,ZZ& u,ZZ& a);
char* trans10to16(char* str16,ZZ num);
int main(void)
{
struct timeval tstart1,tend1,tstart2,tend2,tstart3,tend3;
float time1,time2,time3;
ifstream inf;
ofstream outf;
char str[1000],str16[1000];
//p q g生成调用
ZZ p,q,g;
int p_len,q_len;
cout<<"p长度=";
cin>>p_len;
cout<<"q长度=";
cin>>q_len;
gen_pq(p,q,g,p_len,q_len);
//或者pqg读入
//inf.open("p 3072 q 256 g.txt");
/* inf.open("p 1024 q 160 g.txt");
inf>>p>>q>>g;
inf.close();
*/
cout<<"p q g="<<p<<" "<<q<<" "<<g<<endl;
//rand调用生成pairs
int n;
vec_ZZ k,gk;
cout<<"生成盲化数对个数n=(6?)";
cin>>n;
k.SetLength(n);
gk.SetLength(n);
randpairs(p,q,g,n,k,gk);
cout<<"pairs="<<k<<" "<<gk<<endl;
//u a 生成调用,ua没有长度限制 ,在Zp Zq 中即可
ZZ u,a;
gen_ua(p,q,u,a);
cout<<"u a="<<u<<" "<<a<<endl;
/*===========================其他本地计算==============================*/
//仅做攻击
ZZ t1,t2,r,y1,y2,x1,x2;
ZZ temp,temp1,temp2,temp3,temp4,temp5;
ZZ A,B,C,D,X,Y,Z,A_,B_,C_,D_;
mat_ZZ L;
L.SetDims(4,4);
//生成ti r
int al,be1,be2,j;
//危险范围内
RandomLen(t1,64);
t2=t1;
do{
RandomBnd(r,ZZ(12));
}while(r<2);
be1=NumBits(t1);
be2=NumBits(t2);
al=NumBits(r);
cout<<"bits="<<al<<" "<<be1<<" "<<be2<<endl;
cout<<"t1="<<t1<<endl<<"t2="<<t2<<endl<<"r="<<r<<endl;
//计算xiyi
//cout<<"k1t1="<<k1t1<<endl;
ZZ zd;
XGCD(zd,temp1,temp,operator*(k[1],t1),q);//这里的temp1是没有模q的,z=temp1*k1t1+temp*q=1,即temp1为k1t1模q的逆
cout<<"gcd="<<zd<<endl<<"inv="<<temp1<<endl<<"test(1)="<<endl<<MulMod(operator*(k[1],t1)%q,temp1%q,q)<<endl<<MulMod(operator*(k[1],t1),temp1,q)%q<<endl; //correct
temp2=SubMod(operator*(k[5],a),k[3],q);//k5a-k3 mod q
y1=MulMod(temp1%q,temp2%q,q);//cout<<"y1="<<y1<<endl;
x1=SubMod(a%q,operator*(t1,y1)%q,q);
cout<<"x1y1="<<x1<<" "<<y1<<endl;
//计算x2,y2
XGCD(zd,temp1,temp,operator*(k[2],t2),q);//同上 XGCD.疑问:这里用k2t2和前边求k1t1时是否也需要先模q?
cout<<"gcd="<<zd<<endl<<"inv="<<temp1<<endl<<"test(1)="<<endl<<MulMod(operator*(k[2],t2)%q,temp1%q,q)<<endl<<MulMod(operator*(k[2],t2),temp1,q)%q<<endl;
cout<<r<<" "<<k[0]<<" "<<k[4]<<endl;
temp2=SubMod(r*operator*(k[0],a),k[4],q);//temp2=k6*r*a-k4 mod q
//temp2=SubMod(k6ra,k4,q)%q;//这里究竟要不要多模一次,但最后求得的x2y2是一样的,不影响
y2=MulMod(temp1%q,temp2%q,q);
x2=SubMod(operator*(r,a)%q,operator*(t2,y2)%q,q);//输入参数超过q时要先模q,小于q的可模可不模
cout<<"x2="<<x2<<endl;
cout<<"y2="<<y2<<endl;
//多项式系数
A=x1;
B=y1;
C=-y2;
D=-x2;
X=ZZ(12);
cout<<"ABCD="<<endl<<A<<endl<<B<<endl<<C<<endl<<D<<endl;
do{
RandomLen(Z,64);
Y=operator*(X,Z);
}while(operator>(t2,Z));
cout<<"X="<<X<<endl<<"Y="<<Y<<endl<<"Z="<<Z<<endl;
XGCD(zd,D_,temp,D,q);
cout<<"gcd="<<zd<<endl;
A_=operator*(D_,A);//乘D的逆
B_=operator*(D_,B);
C_=operator*(D_,C);
//构造格基
L(1,1)=ZZ(1); L(1,2)=operator*(A_,X); L(1,3)=operator*(B_,Y); L(1,4)=operator*(C_,Z);
L(2,1)=ZZ(0); L(2,2)=operator*(q,X); L(2,3)=ZZ(0); L(2,4)=ZZ(0);
L(3,1)=ZZ(0); L(3,2)=ZZ(0); L(3,3)=operator*(q,Y); L(3,4)=ZZ(0);
L(4,1)=ZZ(0); L(4,2)=ZZ(0); L(4,3)=ZZ(0); L(4,4)=operator*(q,Z);
outf.open("attack_result.txt");
outf<<"约化前格基为:"<<endl;
outf<<"L(1,1)="<<trans10to16(str16,L(1,1))<<endl;outf<<"L(1,2)="<<trans10to16(str16,L(1,2))<<endl;outf<<"L(1,3)="<<trans10to16(str16,L(1,3))<<endl;outf<<"L(1,4)="<<trans10to16(str16,L(1,4))<<endl;
outf<<"L(2,1)="<<trans10to16(str16,L(2,1))<<endl;outf<<"L(2,2)="<<trans10to16(str16,L(2,2))<<endl;outf<<"L(2,3)="<<trans10to16(str16,L(2,3))<<endl;outf<<"L(2,4)="<<trans10to16(str16,L(2,4))<<endl;
outf<<"L(3,1)="<<trans10to16(str16,L(3,1))<<endl;outf<<"L(3,2)="<<trans10to16(str16,L(3,2))<<endl;outf<<"L(3,3)="<<trans10to16(str16,L(3,3))<<endl;outf<<"L(3,4)="<<trans10to16(str16,L(3,4))<<endl;
outf<<"L(4,1)="<<trans10to16(str16,L(4,1))<<endl;outf<<"L(4,2)="<<trans10to16(str16,L(4,2))<<endl;outf<<"L(4,3)="<<trans10to16(str16,L(4,3))<<endl;outf<<"L(4,4)="<<trans10to16(str16,L(4,4))<<endl;
outf.close();
//约化
gettimeofday(&tstart1,NULL);
ZZ det2;
LLL(det2,L,0);
//攻击结果
ZZ h1,h2,h3,h4,g1,g2,g3,g4,f1,f2,f3,f4;
ZZ x,y,z,x0,y0,z0,tempa,tempb,tempres;
// h1=L(1,1);h2=L(1,2);h3=L(1,3);h4=L(1,4);
// g1=L(2,1);g2=L(2,2);g3=L(2,3);g4=L(2,4);
// f1=L(3,1);f2=L(3,2);f3=L(3,3);f4=L(3,4);
temp1=operator-(operator*(L(1,2),L(2,1)),operator*(L(1,1),L(2,2)));
temp2=operator-(operator*(L(1,2),L(3,3)),operator*(L(1,3),L(3,2)));
temp3=operator-(operator*(L(1,2),L(3,1)),operator*(L(1,1),L(3,2)));
temp4=operator-(operator*(L(1,2),L(2,3)),operator*(L(1,3),L(2,2)));
tempa=operator-(operator*(temp1,temp2),operator*(temp3,temp4));
temp1=operator-(operator*(L(1,2),L(2,4)),operator*(L(1,4),L(2,2)));
temp2=operator-(operator*(L(1,2),L(3,3)),operator*(L(1,3),L(3,2)));
temp3=operator-(operator*(L(1,2),L(3,4)),operator*(L(1,4),L(3,2)));
temp4=operator-(operator*(L(1,2),L(2,3)),operator*(L(1,3),L(2,2)));
tempb=operator-(operator*(temp1,temp2),operator*(temp3,temp4));
//temp2=operator-(operator*(operator-(operator*(h2,g4),operator*(h4,g2)),operator-(operator*(h2,f3),operator*(h3,f2))),operator*(operator-(operator*(h2,f4),operator*(h4,f2)),operator-(operator*(h2,g3),operator*(h3,g2))));
// temp1=operator-(operator*(operator-(operator*(,),operator*(,)),operator-(operator*(,),operator*(,))),operator*(operator-(operator*(,),operator*(,)),operator-(operator*(,),operator*(,))));
tempa=-operator*(tempa,Z);
// cout<<"divide(z0)? (should be 1)="<<divide(tempa,tempb)<<endl;
z0=operator/(tempa,tempb);
temp1=operator-(operator*(L(1,2),L(2,4)),operator*(L(1,4),L(2,2)));
temp2=operator-(operator*(L(1,2),L(2,1)),operator*(L(1,1),L(2,2)));
temp3=operator-(operator*(L(1,2),L(2,3)),operator*(L(1,3),L(2,2)));
tempa=operator+(operator*(temp1,z0),operator*(temp2,Z));
tempb=operator*(temp3,Z);
tempa=-operator*(tempa,Y);
// cout<<"divide(y0)? (should be 1)="<<divide(tempa,tempb)<<endl;
y0=operator/(tempa,tempb);
temp1=operator*(operator*(Y,Z),L(1,1));
temp2=operator*(operator*(L(1,3),y0),Z);
temp3=operator*(operator*(L(1,4),z0),Y);
temp4=operator*(operator*(Y,Z),L(1,2));
tempa=operator+(operator+(temp1,temp2),temp3);
tempb=temp4;
tempa=-operator*(tempa,X);
// cout<<"divide(x0)? (should be 1)="<<divide(tempa,tempb)<<endl;
x0=operator/(tempa,tempb);
gettimeofday(&tend1,NULL);
time1=1000*(tend1.tv_sec-tstart1.tv_sec)+(tend1.tv_usec-tstart1.tv_usec)/1000;
cout<<"time="<<time1<<"ms"<<endl;
//ceshi
// cout<<"t2="<<t2<<" "<<"z0="<<z0<<endl;
// cout<<"rt1="<<operator*(r,t1)<<" "<<"y0="<<y0<<endl;
// cout<<"r="<<r<<" "<<"x0="<<x0<<endl;
cout<<"CHECK RESULT:"<<endl;
if(!compare(x0,r)) cout<<"x0 is CORRECT!"<<endl;else cout<<"x0 is WRONG!"<<endl;
if(!compare(y0,operator*(r,t1))) cout<<"y0 is CORRECT!"<<endl;else cout<<"y0 is WRONG!"<<endl;
if(!compare(z0,t2)) cout<<"z0 is CORRECT!"<<endl;else cout<<"z0 is WRONG!"<<endl;
if(!compare(a,operator+(x1,operator*(t1,y1))%q))cout<<"check a correct"<<endl;else cout<<"check a wrong!"<<endl;
cout<<endl<<"ATTACK FINISH!"<<endl;
//外包计算部分
//check ad recoveer
//计时
//输出为文档 in 16
outf.open("attack_result.txt",ios::app);
outf<<"p="<<endl<<trans10to16(str,p)<<endl;
outf<<"q="<<endl<<trans10to16(str,q)<<endl;
outf<<"g="<<endl<<trans10to16(str,g)<<endl;
outf<<"u="<<endl<<trans10to16(str,u)<<endl;
outf<<"a="<<endl<<trans10to16(str,a)<<endl;
outf<<"r="<<endl<<trans10to16(str,r)<<endl;
outf<<"t1,t2="<<endl<<trans10to16(str,t1)<<endl;
outf<<"X="<<trans10to16(str,X)<<endl;
outf<<"Y="<<trans10to16(str,Y)<<endl;
outf<<"Z="<<trans10to16(str,Z)<<endl;
outf<<"x1="<<endl<<trans10to16(str,x1)<<endl;
outf<<"y1="<<endl<<trans10to16(str,y1)<<endl;
outf<<"x2="<<endl<<trans10to16(str,x2)<<endl;
outf<<"y2="<<endl<<trans10to16(str,y2)<<endl<<"约化后格基如下:"<<endl;
outf<<"L(1,1)="<<trans10to16(str16,L(1,1))<<endl;outf<<"L(1,2)="<<trans10to16(str16,L(1,2))<<endl;outf<<"L(1,3)="<<trans10to16(str16,L(1,3))<<endl;outf<<"L(1,4)="<<trans10to16(str16,L(1,4))<<endl;
outf<<"L(2,1)="<<trans10to16(str16,L(2,1))<<endl;outf<<"L(2,2)="<<trans10to16(str16,L(2,2))<<endl;outf<<"L(2,3)="<<trans10to16(str16,L(2,3))<<endl;outf<<"L(2,4)="<<trans10to16(str16,L(2,4))<<endl;
outf<<"L(3,1)="<<trans10to16(str16,L(3,1))<<endl;outf<<"L(3,2)="<<trans10to16(str16,L(3,2))<<endl;outf<<"L(3,3)="<<trans10to16(str16,L(3,3))<<endl;outf<<"L(3,4)="<<trans10to16(str16,L(3,4))<<endl;
outf<<"L(4,1)="<<trans10to16(str16,L(4,1))<<endl;outf<<"L(4,2)="<<trans10to16(str16,L(4,2))<<endl;outf<<"L(4,3)="<<trans10to16(str16,L(4,3))<<endl;outf<<"L(4,4)="<<trans10to16(str16,L(4,4))<<endl;
outf<<"求得解如下:"<<endl<<"x0(r)="<<trans10to16(str,x0)<<endl;outf<<"y0(rt1)="<<trans10to16(str,y0)<<endl;outf<<"z0(t2)="<<trans10to16(str,z0)<<endl;
outf<<"恢复指数a="<<trans10to16(str,operator+(x1,operator*(t1,y1))%q)<<endl;
outf.close();
}
| [
"noreply@github.com"
] | noreply@github.com |
80527ea333a433e28602724e89cb7c331f4bb47a | c67a90d8aba17b6740da7b0112c06eb73e359300 | /test/dioptre/math/triangle.cpp | d034bc70c3f0357ab6a6a406f6a84c35fd7412be | [
"MIT"
] | permissive | tobscher/rts | ec717c536f0ae2fcec7a962e7f8e63088863a42d | 7f30faf6a13d309e4db828be8be3c05d28c05364 | refs/heads/master | 2016-09-06T17:16:37.615725 | 2015-10-03T11:25:35 | 2015-10-03T11:25:35 | 32,095,728 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | cpp | #include <gtest/gtest.h>
#include "glm/glm.hpp"
#include "dioptre/math/triangle.h"
TEST(Triangle, Initialization) {
glm::vec3 a(0.1, 0.2, 0.3);
glm::vec3 b(0.4, 0.5, 0.6);
glm::vec3 c(0.7, 0.8, 0.9);
dioptre::math::Triangle triangle(a, b, c);
EXPECT_EQ(a, triangle.a());
EXPECT_EQ(b, triangle.b());
EXPECT_EQ(c, triangle.c());
}
| [
"tobias.haar@gmail.com"
] | tobias.haar@gmail.com |
7f86fd42f1c966bec4335c8c6d0d2f2c943fe612 | 777a75e6ed0934c193aece9de4421f8d8db01aac | /src/Providers/UNIXProviders/IKERule/UNIX_IKERule_VMS.hpp | e4638c4f042ec662468fe179534cb99d4905b02b | [
"MIT"
] | permissive | brunolauze/openpegasus-providers-old | 20fc13958016e35dc4d87f93d1999db0eae9010a | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | refs/heads/master | 2021-01-01T20:05:44.559362 | 2014-04-30T17:50:06 | 2014-04-30T17:50:06 | 19,132,738 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,282 | hpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
UNIX_IKERule::UNIX_IKERule(void)
{
}
UNIX_IKERule::~UNIX_IKERule(void)
{
}
Boolean UNIX_IKERule::getInstanceID(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
return true;
}
String UNIX_IKERule::getInstanceID() const
{
return String ("");
}
Boolean UNIX_IKERule::getCaption(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CAPTION, getCaption());
return true;
}
String UNIX_IKERule::getCaption() const
{
return String ("");
}
Boolean UNIX_IKERule::getDescription(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
return true;
}
String UNIX_IKERule::getDescription() const
{
return String ("");
}
Boolean UNIX_IKERule::getElementName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
return true;
}
String UNIX_IKERule::getElementName() const
{
return String("IKERule");
}
Boolean UNIX_IKERule::getCommonName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_COMMON_NAME, getCommonName());
return true;
}
String UNIX_IKERule::getCommonName() const
{
return String ("");
}
Boolean UNIX_IKERule::getPolicyKeywords(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_POLICY_KEYWORDS, getPolicyKeywords());
return true;
}
Array<String> UNIX_IKERule::getPolicyKeywords() const
{
Array<String> as;
return as;
}
Boolean UNIX_IKERule::getPolicyDecisionStrategy(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_POLICY_DECISION_STRATEGY, getPolicyDecisionStrategy());
return true;
}
Uint16 UNIX_IKERule::getPolicyDecisionStrategy() const
{
return Uint16(0);
}
Boolean UNIX_IKERule::getPolicyRoles(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_POLICY_ROLES, getPolicyRoles());
return true;
}
Array<String> UNIX_IKERule::getPolicyRoles() const
{
Array<String> as;
return as;
}
Boolean UNIX_IKERule::getEnabled(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ENABLED, getEnabled());
return true;
}
Uint16 UNIX_IKERule::getEnabled() const
{
return Uint16(0);
}
Boolean UNIX_IKERule::getSystemCreationClassName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_SYSTEM_CREATION_CLASS_NAME, getSystemCreationClassName());
return true;
}
String UNIX_IKERule::getSystemCreationClassName() const
{
return String("UNIX_ComputerSystem");
}
Boolean UNIX_IKERule::getSystemName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_SYSTEM_NAME, getSystemName());
return true;
}
String UNIX_IKERule::getSystemName() const
{
return CIMHelper::HostName;
}
Boolean UNIX_IKERule::getCreationClassName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CREATION_CLASS_NAME, getCreationClassName());
return true;
}
String UNIX_IKERule::getCreationClassName() const
{
return String("UNIX_IKERule");
}
Boolean UNIX_IKERule::getPolicyRuleName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_POLICY_RULE_NAME, getPolicyRuleName());
return true;
}
String UNIX_IKERule::getPolicyRuleName() const
{
return String ("");
}
Boolean UNIX_IKERule::getConditionListType(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CONDITION_LIST_TYPE, getConditionListType());
return true;
}
Uint16 UNIX_IKERule::getConditionListType() const
{
return Uint16(0);
}
Boolean UNIX_IKERule::getRuleUsage(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_RULE_USAGE, getRuleUsage());
return true;
}
String UNIX_IKERule::getRuleUsage() const
{
return String ("");
}
Boolean UNIX_IKERule::getPriority(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIORITY, getPriority());
return true;
}
Uint16 UNIX_IKERule::getPriority() const
{
return Uint16(0);
}
Boolean UNIX_IKERule::getMandatory(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_MANDATORY, getMandatory());
return true;
}
Boolean UNIX_IKERule::getMandatory() const
{
return Boolean(false);
}
Boolean UNIX_IKERule::getSequencedActions(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_SEQUENCED_ACTIONS, getSequencedActions());
return true;
}
Uint16 UNIX_IKERule::getSequencedActions() const
{
return Uint16(0);
}
Boolean UNIX_IKERule::getExecutionStrategy(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_EXECUTION_STRATEGY, getExecutionStrategy());
return true;
}
Uint16 UNIX_IKERule::getExecutionStrategy() const
{
return Uint16(0);
}
Boolean UNIX_IKERule::getLimitNegotiation(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_LIMIT_NEGOTIATION, getLimitNegotiation());
return true;
}
Uint16 UNIX_IKERule::getLimitNegotiation() const
{
return Uint16(0);
}
Boolean UNIX_IKERule::getIdentityContexts(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_IDENTITY_CONTEXTS, getIdentityContexts());
return true;
}
Array<String> UNIX_IKERule::getIdentityContexts() const
{
Array<String> as;
return as;
}
Boolean UNIX_IKERule::initialize()
{
return false;
}
Boolean UNIX_IKERule::load(int &pIndex)
{
return false;
}
Boolean UNIX_IKERule::finalize()
{
return false;
}
Boolean UNIX_IKERule::find(Array<CIMKeyBinding> &kbArray)
{
CIMKeyBinding kb;
String systemCreationClassNameKey;
String systemNameKey;
String creationClassNameKey;
String policyRuleNameKey;
for(Uint32 i = 0; i < kbArray.size(); i++)
{
kb = kbArray[i];
CIMName keyName = kb.getName();
if (keyName.equal(PROPERTY_SYSTEM_CREATION_CLASS_NAME)) systemCreationClassNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_SYSTEM_NAME)) systemNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_CREATION_CLASS_NAME)) creationClassNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_POLICY_RULE_NAME)) policyRuleNameKey = kb.getValue();
}
/* EXecute find with extracted keys */
return false;
}
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
bc7084b2cde8e43cd86182d169e2c9a43569d99c | 50217ceede2d6a0c10ed5e3a45854cd69f4ae05f | /dsa/XVDPU-TRD/vck190_platform/overlays/Vitis_Libraries/vision/L2/examples/sobelfilter/xf_sobel_tb.cpp | cb213df8e3eec9a41ce936ccdb58fafd015177db | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | poldni/Vitis-AI | ddf79938629d4a8c20e1e4997f6445ec42ec7fed | 981f85e04d9b4b8fc2f97e92c0cf28206fde0716 | refs/heads/master | 2022-05-18T06:39:13.094061 | 2022-03-28T19:39:26 | 2022-03-28T19:39:26 | 455,650,766 | 0 | 0 | Apache-2.0 | 2022-02-04T18:14:19 | 2022-02-04T18:14:18 | null | UTF-8 | C++ | false | false | 6,194 | cpp | /*
* Copyright 2019 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include "common/xf_headers.hpp"
#include "xf_sobel_config.h"
#include "xcl2.hpp"
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "Invalid Number of Arguments!\nUsage:\n");
fprintf(stderr, "<Executable Name> <input image path> \n");
return -1;
}
char in[100], in1[100], out_hlsx[100], out_ocvx[100];
char out_errorx[100], out_hlsy[100], out_ocvy[100], out_errory[100];
cv::Mat in_img, in_gray, diff;
cv::Mat c_grad_x_1, c_grad_y_1;
cv::Mat c_grad_x, c_grad_y;
cv::Mat hls_grad_x, hls_grad_y;
cv::Mat diff_grad_x, diff_grad_y;
// reading in the color image
#if GRAY
in_img = cv::imread(argv[1], 0);
#else
in_img = cv::imread(argv[1], 1);
#endif
if (in_img.data == NULL) {
fprintf(stderr, "Cannot open image at %s\n", in);
return 0;
}
///////////////// Opencv Reference ////////////////////////
int scale = 1;
int delta = 0;
#if (FILTER_WIDTH != 7)
int ddepth = CV_8U;
typedef unsigned char TYPE; // Should be short int when ddepth is CV_16S
#if GRAY
#define PTYPE CV_8UC1 // Should be CV_16S when ddepth is CV_16S
#else
#define PTYPE CV_8UC3 // Should be CV_16S when ddepth is CV_16S
#endif
#endif
#if (FILTER_WIDTH == 7)
int ddepth = -1; // CV_32F; //Should be CV_32F if the output pixel type is XF_32UC1
typedef unsigned char TYPE; // Should be int when ddepth is CV_32F
#if GRAY
#define PTYPE CV_8UC1 // Should be CV_16S when ddepth is CV_16S
#else
#define PTYPE CV_8UC3 // Should be CV_16S when ddepth is CV_16S
#endif
#endif
// create memory for output images
hls_grad_x.create(in_img.rows, in_img.cols, PTYPE);
hls_grad_y.create(in_img.rows, in_img.cols, PTYPE);
diff_grad_x.create(in_img.rows, in_img.cols, PTYPE);
diff_grad_y.create(in_img.rows, in_img.cols, PTYPE);
cv::Sobel(in_img, c_grad_x_1, ddepth, 1, 0, FILTER_WIDTH, scale, delta, cv::BORDER_CONSTANT);
cv::Sobel(in_img, c_grad_y_1, ddepth, 0, 1, FILTER_WIDTH, scale, delta, cv::BORDER_CONSTANT);
imwrite("out_ocvx.jpg", c_grad_x_1);
imwrite("out_ocvy.jpg", c_grad_y_1);
/////////////////////////////////////// CL ////////////////////////
int height = in_img.rows;
int width = in_img.cols;
std::vector<cl::Device> devices = xcl::get_xil_devices();
cl::Device device = devices[0];
cl::Context context(device);
cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE);
std::string device_name = device.getInfo<CL_DEVICE_NAME>();
std::string binaryFile = xcl::find_binary_file(device_name, "krnl_sobel");
cl::Program::Binaries bins = xcl::import_binary_file(binaryFile);
devices.resize(1);
cl::Program program(context, devices, bins);
cl::Kernel krnl(program, "sobel_accel");
std::vector<cl::Memory> inBufVec, outBufVec1, outBufVec2;
cl::Buffer imageToDevice(context, CL_MEM_READ_ONLY, (height * width * CH_TYPE));
cl::Buffer imageFromDevice1(context, CL_MEM_WRITE_ONLY, (height * width * CH_TYPE));
cl::Buffer imageFromDevice2(context, CL_MEM_WRITE_ONLY, (height * width * CH_TYPE));
// Set the kernel arguments
krnl.setArg(0, imageToDevice);
krnl.setArg(1, imageFromDevice1);
krnl.setArg(2, imageFromDevice2);
krnl.setArg(3, height);
krnl.setArg(4, width);
q.enqueueWriteBuffer(imageToDevice, CL_TRUE, 0, (height * width * CH_TYPE), in_img.data);
// Profiling Objects
cl_ulong start = 0;
cl_ulong end = 0;
double diff_prof = 0.0f;
cl::Event event_sp;
printf("before kernel .... !!!\n");
// Launch the kernel
q.enqueueTask(krnl, NULL, &event_sp);
clWaitForEvents(1, (const cl_event*)&event_sp);
printf("after kernel .... !!!\n");
event_sp.getProfilingInfo(CL_PROFILING_COMMAND_START, &start);
event_sp.getProfilingInfo(CL_PROFILING_COMMAND_END, &end);
diff_prof = end - start;
std::cout << (diff_prof / 1000000) << "ms" << std::endl;
// q.enqueueMigrateMemObjects(outBufVec1,CL_MIGRATE_MEM_OBJECT_HOST);
// q.enqueueMigrateMemObjects(outBufVec2,CL_MIGRATE_MEM_OBJECT_HOST);
q.enqueueReadBuffer(imageFromDevice1, CL_TRUE, 0, (height * width * CH_TYPE), hls_grad_x.data);
q.enqueueReadBuffer(imageFromDevice2, CL_TRUE, 0, (height * width * CH_TYPE), hls_grad_y.data);
q.finish();
/////////////////////////////////////// end of CL ////////////////////////
////////////////// Compute Absolute Difference ////////////////////
#if (FILTER_WIDTH == 3 | FILTER_WIDTH == 5)
absdiff(c_grad_x_1, hls_grad_x, diff_grad_x);
absdiff(c_grad_y_1, hls_grad_y, diff_grad_y);
#endif
#if (FILTER_WIDTH == 7)
if (OUT_TYPE == XF_8UC1 || OUT_TYPE == XF_16SC1 || OUT_TYPE == XF_8UC3 || OUT_TYPE == XF_16SC3) {
absdiff(c_grad_x_1, hls_grad_x, diff_grad_x);
absdiff(c_grad_y_1, hls_grad_y, diff_grad_y);
} else if (OUT_TYPE == XF_32UC1) {
c_grad_x_1.convertTo(c_grad_x, CV_32S);
c_grad_y_1.convertTo(c_grad_y, CV_32S);
absdiff(c_grad_x, hls_grad_x, diff_grad_x);
absdiff(c_grad_y, hls_grad_y, diff_grad_y);
}
#endif
imwrite("out_errorx.jpg", diff_grad_x);
imwrite("out_errory.jpg", diff_grad_y);
float err_per, err_per1;
int ret;
xf::cv::analyzeDiff(diff_grad_x, 0, err_per);
xf::cv::analyzeDiff(diff_grad_y, 0, err_per1);
if (err_per > 0.0f) {
fprintf(stderr, "Test failed .... !!!\n ");
ret = 1;
} else {
std::cout << "Test Passed .... !!!" << std::endl;
ret = 0;
}
return ret;
}
| [
"do-not-reply@gitenterprise.xilinx.com"
] | do-not-reply@gitenterprise.xilinx.com |
643e80f7ce0afbdb7321bcd719ce040b661403a1 | bcc2f8e226d0cfb54c2f8b50c98aa4691fe96900 | /source/cpp/rest/requests/tasksrequest.cpp | a840851469ff0222ab6e83ddbba37a6380de9955 | [] | no_license | ImageMonkey/imagemonkey-thegame | a5872aebf943010e3c5ef6a4189572a85057ac06 | 59a0472709c90c10d9d7baddec0635b5e304eea6 | refs/heads/master | 2020-04-14T09:34:06.634000 | 2019-11-29T13:52:15 | 2019-11-29T13:52:15 | 163,763,067 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 398 | cpp | #include "tasksrequest.h"
#include <QFile>
#include <QUrlQuery>
#include <QUuid>
GetTasksRequest::GetTasksRequest()
: BasicRequest (),
m_username("")
{
}
void GetTasksRequest::setUsername(const QString& username) {
QUrl url(m_baseUrl + "user/" + username + "/games/imagehunt/tasks");
m_request->setUrl(url);
m_username = username;
}
GetTasksRequest::~GetTasksRequest() {
}
| [
"schluchti@gmail.com"
] | schluchti@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.