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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0747199684b9f8728081d8218d77404c0e8ce1d7 | ff6b880d6c254069e6ea47ed693f979946397552 | /OOP/Lab5/Lab5/laba4/laba4/Win32Project2/PointEditor.h | 8df63ed40423791c81437b9d55a247766d6a48f5 | [] | no_license | Slavick-Vinnitskyi/University | 047b293c61cc1b53e88e8e61fec829cef020a95a | d040d1515cccbd45e7c9e0ae1e60953a04e44f89 | refs/heads/master | 2021-07-10T14:18:27.855192 | 2018-11-19T17:30:59 | 2018-11-19T17:30:59 | 135,054,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | h | #pragma once
#include "Editor.h"
#include "ShapeEditor.h"
#include "PointShape.h"
class PointEditor: public ShapeEditor
{
public:
void OnLBdown(HWND hwnd, int x, int y) {}
void NewShape()
{
shape = new Point();
}
void OnLBup(HWND hwnd, int x, int y)
{
shape->SetX1Y1(x, y);
}
void OnMouseMove(HWND hwnd, int x, int y) {}
void DrawShadow(HDC hdc){}
};
| [
"noreply@github.com"
] | noreply@github.com |
d51bcd7367213da5902fbb484e013be18a821aab | 19daf06821b0d51541102254383e0c92f0136750 | /include/cool-tree.handcode.h | f971125fced40dcb8c88870fa4dd85e35260c29a | [] | no_license | rish246/CompilerDesign | b39e2ebdb5543752c0771a546eb49847b18d0cc7 | 5bdade7731741a020d622eb9bde7ea4a929c8d0f | refs/heads/main | 2023-03-08T14:35:18.525267 | 2021-02-22T05:54:30 | 2021-02-22T05:54:30 | 326,186,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,865 | h | //
// The following include files must come first.
// Read this first
// Then Read the COOL_TREE_H
#ifndef COOL_TREE_HANDCODE_H
#define COOL_TREE_HANDCODE_H
#include <iostream>
<<<<<<< HEAD
#include "./tree.h"
=======
#include "./tree.hpp"
>>>>>>> f3b6a6f722898ad27256033354da69be5af6ce9a
#include "./cool.h"
#include "./StringTab.hpp"
/*
-- Read Tree.h
-- Read cool.h
*/
<<<<<<< HEAD
// #define yylineno curr_lineno;
// Defining the yylineno to be equal to curr_lineno
=======
#define yylineno curr_lineno;
>>>>>>> f3b6a6f722898ad27256033354da69be5af6ce9a
extern int yylineno;
inline Boolean copy_Boolean(Boolean b) { return b; }
inline void assert_Boolean(Boolean) {}
inline void dump_Boolean(ostream &stream, int padding, Boolean b)
{
stream << pad(padding) << (int)b << "\n";
}
<<<<<<< HEAD
// we have to provide definitions in a cpp file
=======
>>>>>>> f3b6a6f722898ad27256033354da69be5af6ce9a
void dump_Symbol(ostream &stream, int padding, Symbol b);
void assert_Symbol(Symbol b);
Symbol copy_Symbol(Symbol b);
class Program_class;
typedef Program_class *Program;
class Class__class;
typedef Class__class *Class_;
class Feature_class;
typedef Feature_class *Feature;
class Formal_class;
typedef Formal_class *Formal;
class Expression_class;
typedef Expression_class *Expression;
class Case_class;
typedef Case_class *Case;
typedef list_node<Class_> Classes_class;
typedef Classes_class *Classes;
typedef list_node<Feature> Features_class;
typedef Features_class *Features;
typedef list_node<Formal> Formals_class;
typedef Formals_class *Formals;
typedef list_node<Expression> Expressions_class;
typedef Expressions_class *Expressions;
typedef list_node<Case> Cases_class;
typedef Cases_class *Cases;
<<<<<<< HEAD
// #define Program_EXTRAS \
// virtual void dump_with_types(ostream &, int) = 0;
// #define program_EXTRAS \
// void dump_with_types(ostream &, int);
// #define Class__EXTRAS \
// virtual Symbol get_filename() = 0; \
// virtual void dump_with_types(ostream &, int) = 0;
// #define class__EXTRAS \
// Symbol get_filename() { return filename; } \
// void dump_with_types(ostream &, int);
// #define Feature_EXTRAS \
// virtual void dump_with_types(ostream &, int) = 0;
// #define Feature_SHARED_EXTRAS \
// void dump_with_types(ostream &, int);
// #define Formal_EXTRAS \
// virtual void dump_with_types(ostream &, int) = 0;
// #define formal_EXTRAS \
// void dump_with_types(ostream &, int);
// #define Case_EXTRAS \
// virtual void dump_with_types(ostream &, int) = 0;
// #define branch_EXTRAS \
// void dump_with_types(ostream &, int);
// #define Expression_EXTRAS \
// Symbol type; \
// Symbol get_type() { return type; } \
// Expression set_type(Symbol s) \
// { \
// type = s; \
// return this; \
// } \
// virtual void dump_with_types(ostream &, int) = 0; \
// void dump_type(ostream &, int); \
// Expression_class() { type = (Symbol)NULL; }
// #define Expression_SHARED_EXTRAS \
// void dump_with_types(ostream &, int);
=======
#define Program_EXTRAS \
virtual void dump_with_types(ostream &, int) = 0;
#define program_EXTRAS \
void dump_with_types(ostream &, int);
#define Class__EXTRAS \
virtual Symbol get_filename() = 0; \
virtual void dump_with_types(ostream &, int) = 0;
#define class__EXTRAS \
Symbol get_filename() { return filename; } \
void dump_with_types(ostream &, int);
#define Feature_EXTRAS \
virtual void dump_with_types(ostream &, int) = 0;
#define Feature_SHARED_EXTRAS \
void dump_with_types(ostream &, int);
#define Formal_EXTRAS \
virtual void dump_with_types(ostream &, int) = 0;
#define formal_EXTRAS \
void dump_with_types(ostream &, int);
#define Case_EXTRAS \
virtual void dump_with_types(ostream &, int) = 0;
#define branch_EXTRAS \
void dump_with_types(ostream &, int);
#define Expression_EXTRAS \
Symbol type; \
Symbol get_type() { return type; } \
Expression set_type(Symbol s) \
{ \
type = s; \
return this; \
} \
virtual void dump_with_types(ostream &, int) = 0; \
void dump_type(ostream &, int); \
Expression_class() { type = (Symbol)NULL; }
#define Expression_SHARED_EXTRAS \
void dump_with_types(ostream &, int);
>>>>>>> f3b6a6f722898ad27256033354da69be5af6ce9a
#endif
| [
"rishabhkatna2228@gmail.com"
] | rishabhkatna2228@gmail.com |
4a218545c0287975271517023738dfc852323481 | 74f084a0a5d2cc70fa49708a4f070aa271dba1b3 | /src/server/server/game/src/HackShield_Impl.h | 245895242f02eb1c4a763bdaa3d8f23feeceda32 | [] | no_license | rafalohaki/Metin2-Work | 293f9c2318fca74bd433942a7156a3f8ba18241d | c0adbc14cd15ea12a78e61db570b3963d755ab75 | refs/heads/main | 2023-05-30T17:23:56.347527 | 2021-06-14T18:44:54 | 2021-06-14T18:44:54 | 382,686,870 | 0 | 0 | null | 2021-07-03T18:38:23 | 2021-07-03T18:38:22 | null | UTF-8 | C++ | false | false | 963 | h |
#ifndef HACK_SHIELD_IMPL_H_
#define HACK_SHIELD_IMPL_H_
#include <boost/unordered_map.hpp>
#ifdef __FreeBSD__
// Live build only
#define UNIX
#include <AntiCpXSvr.h>
#undef UNIX
#endif
#pragma pack(1)
typedef struct SPacketGCHSCheck
{
uint8_t bHeader;
#ifdef __FreeBSD__
AHNHS_TRANS_BUFFER Req;
#endif
} TPacketGCHSCheck;
#pragma pack()
class CHackShieldImpl
{
public:
bool Initialize ();
void Release ();
bool CreateClientHandle (uint32_t dwPlayerID);
void DeleteClientHandle (uint32_t dwPlayerID);
bool SendCheckPacket (LPCHARACTER ch);
bool VerifyAck (LPCHARACTER ch, TPacketGCHSCheck* buf);
private:
#ifdef __FreeBSD__
AHNHS_SERVER_HANDLE handle_;
typedef boost::unordered_map<uint32_t, AHNHS_CLIENT_HANDLE> ClientHandleContainer;
ClientHandleContainer CliehtHandleMap_;
typedef boost::unordered_map<uint32_t, bool> ClientCheckContainer;
ClientCheckContainer ClientCheckMap_;
#endif
};
#endif /* HACK_SHIELD_IMPL_H_ */
| [
"46651742+ASIKOO@users.noreply.github.com"
] | 46651742+ASIKOO@users.noreply.github.com |
83cc0d126d99f8069d7965b7fa6b0e8682317013 | 0d7cd9b8f04d6b924a5183e056731c9b7c3eb651 | /GeekForGeeks/Queues/reverseque.cpp | 73a167bea57edbf282537772d8fbfb8c38586803 | [] | no_license | SayantoRoy/DS-and-ALGO | a5e065d0ba84580fb4190331a49aa658ef865463 | 2246e4fd9df3b88ec2228c6b0334cc8a38016c63 | refs/heads/master | 2022-12-12T00:39:37.630556 | 2020-09-04T17:36:15 | 2020-09-04T17:36:15 | 260,521,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,198 | cpp |
#include<iostream>
#include<stack>
using namespace std;
struct node
{
int data;
node* next;
};
node* head = NULL;
node* tail = NULL;
void push(int x)
{
node* temp = new node;
temp->data =x;
temp->next =NULL;
if(head == NULL)
{
head = temp;
tail = temp;
}
else
{
node* p = tail;
p->next = temp;
tail = temp;
}
}
void pop()
{
if(head == tail)
{
cout<<"UnderFlow"<<endl;
}
else
{
cout<<head->data<<endl;
head = head->next;
}
}
void display(node* head)
{
node*p = head;
cout<<"Display in flow : \n";
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
void reverseit()
{
stack<int> s;
node* p = head;
while(p!=NULL)
{
s.push(p->data);
p=p->next;
}
head = NULL;
tail = NULL;
while(!s.empty())
{
push(s.top());
s.pop();
}
}
int main()
{
int n;
cin>>n;
for(int i =0;i<n;i++)
{
int k;
cin>>k;
push(k);
}
display(head);
cout<<endl;
reverseit();
cout<<endl;
display(head);
return 0;
}
| [
"sroy.sayanto@gmail.com"
] | sroy.sayanto@gmail.com |
de7ebbee79d1a6afcaaa99b50a43fd23e9065f12 | 9e0864a47932097f584cafb9606b1038d3d99fc5 | /cmake/include/irrlicht/IParticleGravityAffector.h | 22421edf0d7ebd8aa385665dff81bde1e0e1e285 | [] | no_license | arzeo68/OOP_indie_studio | d7a83d6363a711fd6a27027cf8221d079f67b4a8 | 14ad93650d7fa09ac63ee0158f327b7996defe96 | refs/heads/master | 2022-12-11T22:25:29.843477 | 2020-09-04T15:16:22 | 2020-09-04T15:16:22 | 292,878,597 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,426 | h | // Copyright (C) 2002-2012 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_PARTICLE_GRAVITY_AFFECTOR_H_INCLUDED__
#define __I_PARTICLE_GRAVITY_AFFECTOR_H_INCLUDED__
#include "IParticleAffector.h"
namespace irr
{
namespace scene
{
//! A particle affector which applies gravity to particles.
class IParticleGravityAffector : public IParticleAffector
{
public:
//! Set the time in milliseconds when the gravity force is totally lost
/** At that point the particle does not move any more. */
virtual void setTimeForceLost(f32 timeForceLost) = 0;
//! Set the direction and force of gravity in all 3 dimensions.
virtual void setGravity(const core::vector3df &gravity) = 0;
//! Get the time in milliseconds when the gravity force is totally lost
virtual f32 getTimeForceLost() const = 0;
//! Get the direction and force of gravity.
virtual const core::vector3df &getGravity() const = 0;
//! Get emitter type
virtual E_PARTICLE_AFFECTOR_TYPE getType() const
{
return EPAT_GRAVITY;
}
};
} // end namespace scene
} // end namespace irr
#endif // __I_PARTICLE_GRAVITY_AFFECTOR_H_INCLUDED__
| [
"alexis.walter@epitech.eu"
] | alexis.walter@epitech.eu |
7b2d43b3abff9c8a52de8ea7201716f26caf65de | a3634de7800ae5fe8e68532d7c3a7570b9c61c5b | /hackerrank/non-divisible-subset.cpp | b8662f659eed1438d0ac6d1c31149dcb50bfea1e | [] | no_license | MayankChaturvedi/competitive-coding | a737a2a36b8aa7aea1193f2db4b32b081f78e2ba | 9e9bd21de669c7b7bd29a262b29965ecc80ad621 | refs/heads/master | 2020-03-18T01:39:29.447631 | 2018-02-19T15:04:32 | 2018-02-19T15:04:32 | 134,152,930 | 0 | 1 | null | 2018-05-20T13:27:35 | 2018-05-20T13:27:34 | null | UTF-8 | C++ | false | false | 669 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n, k;
cin>>n>>k;
int q[k]={0};
int count=0, s[n];
for(int i=0; i<n; i++)
cin>>s[i];
for(int i=0; i<n; i++)
q[s[i]%k]++;
if(q[0]>0)
count++;
//cout<<q[0];
for(int i=1; i<k/2 + (k%2); i++)
{ if(q[i]>=q[k-i])
count+=q[i];
else
count+=q[k-i];
//cout<<q[i]<<' '<<q[k-i]<<endl;
}
if(k%2==0 && q[k/2]>0)
count++;
cout<<count;
return 0;
}
| [
"f20160006@goa.bits-pilani.ac.in"
] | f20160006@goa.bits-pilani.ac.in |
c14dbf178bdc3b9f060a1a4eb71cfa668fc970d0 | 6c1fdffe8569ea66178264210a5dc2cdb2cc2f9c | /linkedlist/SinglyLinkedList.h | f17e8c64138d055cd2b710d98967d672e69edd28 | [] | no_license | DarBeck/singlylinkedlist | 2d09253b20db458656312335080d93502d9ba94a | f961e4677be5e308d16ac8147353c52f0265b6b1 | refs/heads/master | 2022-12-24T07:08:59.291208 | 2020-10-04T02:01:53 | 2020-10-04T02:01:53 | 300,086,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | h | #pragma once
#include "Node.h"
class SinglyLinkedList
{
public:
SinglyLinkedList();
void InsertAtBack(shared_ptr<Student> data);
void RemoveStudent(int studentId);
shared_ptr<Student> SearchStudent(int studentId);
void DisplayList();
void DestroyList();
private:
shared_ptr<Node> head;
};
| [
"darren.beckford@hotmail.com"
] | darren.beckford@hotmail.com |
9003897b16b65341eb8a9c3e52469c6cf7507a3d | 67fc9e51437e351579fe9d2d349040c25936472a | /wrappers/7.0.0/vtkRectilinearGridToTetrahedraWrap.h | d5cd2b0424f78a3075645f6f81663e593ac1a5cb | [] | permissive | axkibe/node-vtk | 51b3207c7a7d3b59a4dd46a51e754984c3302dec | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | refs/heads/master | 2023-03-05T07:45:45.577220 | 2020-03-30T09:31:07 | 2020-03-30T09:31:07 | 48,490,707 | 6 | 0 | BSD-3-Clause | 2022-12-07T20:41:45 | 2015-12-23T12:58:43 | C++ | UTF-8 | C++ | false | false | 2,383 | h | /* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#ifndef NATIVE_EXTENSION_VTK_VTKRECTILINEARGRIDTOTETRAHEDRAWRAP_H
#define NATIVE_EXTENSION_VTK_VTKRECTILINEARGRIDTOTETRAHEDRAWRAP_H
#include <nan.h>
#include <vtkSmartPointer.h>
#include <vtkRectilinearGridToTetrahedra.h>
#include "vtkUnstructuredGridAlgorithmWrap.h"
#include "../../plus/plus.h"
class VtkRectilinearGridToTetrahedraWrap : public VtkUnstructuredGridAlgorithmWrap
{
public:
using Nan::ObjectWrap::Wrap;
static void Init(v8::Local<v8::Object> exports);
static void InitPtpl();
static void ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info);
VtkRectilinearGridToTetrahedraWrap(vtkSmartPointer<vtkRectilinearGridToTetrahedra>);
VtkRectilinearGridToTetrahedraWrap();
~VtkRectilinearGridToTetrahedraWrap( );
static Nan::Persistent<v8::FunctionTemplate> ptpl;
private:
static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetRememberVoxelId(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetTetraPerCell(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void RememberVoxelIdOff(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void RememberVoxelIdOn(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetInput(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetRememberVoxelId(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetTetraPerCell(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetTetraPerCellTo12(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetTetraPerCellTo5(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetTetraPerCellTo5And12(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetTetraPerCellTo6(const Nan::FunctionCallbackInfo<v8::Value>& info);
#ifdef VTK_NODE_PLUS_VTKRECTILINEARGRIDTOTETRAHEDRAWRAP_CLASSDEF
VTK_NODE_PLUS_VTKRECTILINEARGRIDTOTETRAHEDRAWRAP_CLASSDEF
#endif
};
#endif
| [
"axkibe@gmail.com"
] | axkibe@gmail.com |
5e02ffa4015efbf4482b13056d9315cef9eafda8 | 0314af7877ed3cde78101aca56d45673dce223c6 | /MotionSwitchAccumulator/ManageRecordedDataOnMySQL/src/embodied_brain/main.cpp | 3def8fe1466d0642af1c5a6837356f569343a8cc | [] | no_license | t-inamura/EmbodiedBrain | 60be19b9ee5385159f153e4d7b95699917ae6b75 | dc10dfabe19e7d321b612e96c965b4b6cfa6109f | refs/heads/master | 2020-12-18T15:22:20.422154 | 2018-05-20T00:24:05 | 2018-05-20T00:24:05 | 26,864,993 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,469 | cpp | /*
* データベース(MySQL)に収録された各種データを簡易なコマンドでメンテナンスする
*
* <流れ>
* 1. コンソールからのコマンド入力で、テーブルをメンテナンスする
* メンテナンス対象テーブルは以下
* ・Perception Neuron動作サマリテーブル(perception_neuron_motions_summary)
* ・Perception Neuron動作時系列テーブル(perception_neuron_motions_time_series)
* ・動作切替実験_収録情報テーブル(msw_recording_info)
* 2. 情報表示、更新、削除 等をコンソールからの簡易なコマンド入力で行う
*
* <引数>
* なし
*
* <その他>
* ・設定ファイル名は、ManageRecordedDataOnMySQL.ini
*/
#include <embodied_brain/common/Param.h>
#include <embodied_brain/manage_recorded_data_on_mysql.h>
#include <iostream>
const std::string Param::PARAM_FILE_NAME = "ManageRecordedDataOnMySQL.ini";
std::string Param::dbHost;
int Param::dbPort;
std::string Param::dbSchema;
std::string Param::dbUser;
std::string Param::dbPass;
/*
* メイン
*/
int main(int argc, char **argv)
{
try
{
//コンフィグファイルからデータベース関連のパラメータを取得する
Param::readConfigFile();
ManageRecordedDataOnMySQL manageRecordedDataOnMySQL;
manageRecordedDataOnMySQL.run();
}
catch (std::exception& ex)
{
std::cout << ex.what() << std::endl;
}
}
| [
"tome-yamada@nii.ac.jp"
] | tome-yamada@nii.ac.jp |
a66ddc0778723d03664190d750427db60841e7d8 | ab0a8234e443a6aa152b9f7b135a1e2560e9db33 | /Server/CGSF/LogicLayer/MOGame/triggerareacomponent.h | 0b524aefa2f4ee2ea12ec21f3f8817695afb8c82 | [] | no_license | zetarus/Americano | 71c358d8d12b144c8858983c23d9236f7d0e941b | b62466329cf6f515661ef9fb9b9d2ae90a032a60 | refs/heads/master | 2023-04-08T04:26:29.043048 | 2018-04-19T11:21:14 | 2018-04-19T11:21:14 | 104,159,178 | 9 | 2 | null | 2023-03-23T12:10:51 | 2017-09-20T03:11:44 | C++ | UTF-8 | C++ | false | false | 3,315 | h | /*
* The Mana Server
* Copyright (C) 2006-2010 The Mana World Development Team
* Copyright (C) 2012 The Mana Developers
*
* This file is part of The Mana Server.
*
* The Mana Server is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* The Mana Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with The Mana Server. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRIGGERAREACOMPONENT_H
#define TRIGGERAREACOMPONENT_H
#include "entity.h"
#include "scripting/script.h"
#include "utils/point.h"
#include <set>
class Entity;
class TriggerAction
{
public:
virtual ~TriggerAction() {}
virtual void process(Entity *obj) = 0;
};
class WarpAction : public TriggerAction
{
public:
WarpAction(MapComposite *m, const Point &point)
: mMap(m), mTargetPoint(point) {}
virtual void process(Entity *obj);
private:
MapComposite *mMap;
Point mTargetPoint;
};
class AutowarpAction: public TriggerAction
{
public:
enum ExitDirection {
ExitNorth,
ExitEast,
ExitSouth,
ExitWest
};
AutowarpAction(MapComposite *m,
const ManaRectangle &sourceArea,
const ManaRectangle &targetArea,
ExitDirection direction)
: mMap(m),
mSourceArea(sourceArea),
mTargetArea(targetArea),
mDirection(direction)
{}
virtual void process(Entity *obj);
private:
/** Target map */
MapComposite *mMap;
/** Source area - used to calculate warp offset and warp direction */
ManaRectangle mSourceArea;
/** Target area */
ManaRectangle mTargetArea;
/** The direction to exit target area */
ExitDirection mDirection;
};
class ScriptAction : public TriggerAction
{
public:
ScriptAction(Script *script, Script::Ref callback, int arg);
virtual void process(Entity *obj);
private:
Script *mScript; // Script object to be called
Script::Ref mCallback; // Reference to the function to call
int mArg; // Argument passed to script function (meaning is function-specific)
};
class TriggerAreaComponent : public Component
{
public:
static const ComponentType type = CT_TriggerArea;
/**
* Creates a rectangular trigger for a given map.
*/
TriggerAreaComponent(const ManaRectangle &r,
TriggerAction *ptr,
bool once) :
mZone(r),
mAction(ptr),
mOnce(once)
{}
void update(Entity &entity);
private:
ManaRectangle mZone;
TriggerAction *mAction;
bool mOnce;
std::set<Entity *> mInside;
};
#endif // TRIGGERAREACOMPONENT_H
| [
"sinyonzzang@gmail.com"
] | sinyonzzang@gmail.com |
fc098f061c84e4f1637d855df27dd824cf9ec2d8 | ab4eb5ad30c66fb309f39bf6e1d30483a6b2c295 | /Pg1_03.cpp | 5a861757224c6ef2aa6ad6d76b07d4a2baf3f408 | [] | no_license | Kuro524/programming-at-nit | 1162e302ac04abb06579e73bd7175da0adee2b41 | af4ba96b08865916320e7b7d34a95e31f47c6b09 | refs/heads/master | 2021-01-10T16:48:29.204377 | 2016-04-14T21:21:27 | 2016-04-14T21:21:27 | 55,895,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | cpp | /*//////////////////////////////////////////////////////////////////////////////////
課題3 5つの値の最大値を求め表示するプログラムを作成しなさい。
キーワード:if文、比較演算子、代入演算子
最終更新日:2016.03.28
*/
#define _CRT_SECURE_NO_WARNINGS // 余計な警告が出ないようにする
#include <stdio.h>
int main( void )
{
int a, b, c, d, e; // 調べる値
int max; // 最大値を入れる
printf( "数値を5つ入力してください > " );
scanf( "%d %d %d %d %d", &a, &b, &c, &d, &e );
max = a;
if( max < b ) max = b;
if( max < c ) max = c;
if( max < d ) max = d;
if( max < e ) max = e;
// 結果を表示する
printf( "最大値は %d です\n", max );
return 0;
}
| [
"Kota Konishi"
] | Kota Konishi |
e4a6c59359d8a21ebb876877162bc6caf2c85c5b | 9cd2aae81efacf6e661cf238d42a4ecf345a92c6 | /tests/studentTests.cpp | 4789da58636ad74927f434adf910f307bbc49f07 | [] | no_license | liu861/Letter-Encryptor-Decryptor | 8019b6e7fad73431ca80a29bbbf85b774bc4e22e | ce28b9ba12bb1e8bacb736aa097b01bfb18b93b7 | refs/heads/master | 2022-11-10T16:56:45.168058 | 2020-07-02T04:04:54 | 2020-07-02T04:04:54 | 260,891,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,128 | cpp | #include "catch.hpp"
#include "srcmain.h"
// Helper function declarations (don't change this)
extern bool CheckTextFilesSame(const std::string& fileNameA,
const std::string& fileNameB);
// Your tests -- only add sections
TEST_CASE("Substitution Decrypt Tests", "[student]")
{
SECTION("Decrypt -- Simple")
{
const char* argv[] = {
"dsub",
"input/simple-enc.txt",
"output/simple-clear-out.txt"
};
ProcessCommandArgs(4, argv);
bool result = CheckTextFilesSame("output/simple-clear-out.txt", "input/simple-clear.txt");
REQUIRE(result);
}
// TODO: Add more decrypt test sections!
}
TEST_CASE("Substitution Encrypt Tests", "[student]")
{
SECTION("Encrypt -- Simple")
{
const char* argv[] = {
"esub",
"input/simple-clear.txt",
"output/simple-enc-out.txt"
};
ProcessCommandArgs(4, argv);
bool result = CheckTextFilesSame("output/simple-enc-out.txt", "input/simple-enc.txt");
REQUIRE(result);
}
// TODO: Add more encrypt test sections!
}
| [
"scottmai@usc.edu"
] | scottmai@usc.edu |
d9bc1b7751d00cd3b0e326ee7b6acee7299c7369 | 5f9b26a41102c38da28b8f757a5586f9bc7cf71a | /crates/zig_build_bin_windows_x86_64/zig-windows-x86_64-0.5.0+80ff549e2/lib/zig/libcxx/include/string | 1db9ee4433ce6f5996c91cbf6a0166e220ac301a | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0"
] | permissive | jeremyBanks/zig_with_cargo | f8e65f14adf17ed8d477f0856257422c2158c63f | f8ee46b891bbcdca7ff20f5cad64aa94c5a1d2d1 | refs/heads/master | 2021-02-06T10:26:17.614138 | 2020-03-09T04:46:26 | 2020-03-09T04:46:26 | 243,905,553 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 165,858 | // -*- C++ -*-
//===--------------------------- string -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_STRING
#define _LIBCPP_STRING
/*
string synopsis
namespace std
{
template <class stateT>
class fpos
{
private:
stateT st;
public:
fpos(streamoff = streamoff());
operator streamoff() const;
stateT state() const;
void state(stateT);
fpos& operator+=(streamoff);
fpos operator+ (streamoff) const;
fpos& operator-=(streamoff);
fpos operator- (streamoff) const;
};
template <class stateT> streamoff operator-(const fpos<stateT>& x, const fpos<stateT>& y);
template <class stateT> bool operator==(const fpos<stateT>& x, const fpos<stateT>& y);
template <class stateT> bool operator!=(const fpos<stateT>& x, const fpos<stateT>& y);
template <class charT>
struct char_traits
{
typedef charT char_type;
typedef ... int_type;
typedef streamoff off_type;
typedef streampos pos_type;
typedef mbstate_t state_type;
static void assign(char_type& c1, const char_type& c2) noexcept;
static constexpr bool eq(char_type c1, char_type c2) noexcept;
static constexpr bool lt(char_type c1, char_type c2) noexcept;
static int compare(const char_type* s1, const char_type* s2, size_t n);
static size_t length(const char_type* s);
static const char_type* find(const char_type* s, size_t n, const char_type& a);
static char_type* move(char_type* s1, const char_type* s2, size_t n);
static char_type* copy(char_type* s1, const char_type* s2, size_t n);
static char_type* assign(char_type* s, size_t n, char_type a);
static constexpr int_type not_eof(int_type c) noexcept;
static constexpr char_type to_char_type(int_type c) noexcept;
static constexpr int_type to_int_type(char_type c) noexcept;
static constexpr bool eq_int_type(int_type c1, int_type c2) noexcept;
static constexpr int_type eof() noexcept;
};
template <> struct char_traits<char>;
template <> struct char_traits<wchar_t>;
template<class charT, class traits = char_traits<charT>, class Allocator = allocator<charT> >
class basic_string
{
public:
// types:
typedef traits traits_type;
typedef typename traits_type::char_type value_type;
typedef Allocator allocator_type;
typedef typename allocator_type::size_type size_type;
typedef typename allocator_type::difference_type difference_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef implementation-defined iterator;
typedef implementation-defined const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
static const size_type npos = -1;
basic_string()
noexcept(is_nothrow_default_constructible<allocator_type>::value);
explicit basic_string(const allocator_type& a);
basic_string(const basic_string& str);
basic_string(basic_string&& str)
noexcept(is_nothrow_move_constructible<allocator_type>::value);
basic_string(const basic_string& str, size_type pos,
const allocator_type& a = allocator_type());
basic_string(const basic_string& str, size_type pos, size_type n,
const Allocator& a = Allocator());
template<class T>
basic_string(const T& t, size_type pos, size_type n, const Allocator& a = Allocator()); // C++17
template <class T>
explicit basic_string(const T& t, const Allocator& a = Allocator()); // C++17
basic_string(const value_type* s, const allocator_type& a = allocator_type());
basic_string(const value_type* s, size_type n, const allocator_type& a = allocator_type());
basic_string(size_type n, value_type c, const allocator_type& a = allocator_type());
template<class InputIterator>
basic_string(InputIterator begin, InputIterator end,
const allocator_type& a = allocator_type());
basic_string(initializer_list<value_type>, const Allocator& = Allocator());
basic_string(const basic_string&, const Allocator&);
basic_string(basic_string&&, const Allocator&);
~basic_string();
operator basic_string_view<charT, traits>() const noexcept;
basic_string& operator=(const basic_string& str);
template <class T>
basic_string& operator=(const T& t); // C++17
basic_string& operator=(basic_string&& str)
noexcept(
allocator_type::propagate_on_container_move_assignment::value ||
allocator_type::is_always_equal::value ); // C++17
basic_string& operator=(const value_type* s);
basic_string& operator=(value_type c);
basic_string& operator=(initializer_list<value_type>);
iterator begin() noexcept;
const_iterator begin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
const_iterator cbegin() const noexcept;
const_iterator cend() const noexcept;
const_reverse_iterator crbegin() const noexcept;
const_reverse_iterator crend() const noexcept;
size_type size() const noexcept;
size_type length() const noexcept;
size_type max_size() const noexcept;
size_type capacity() const noexcept;
void resize(size_type n, value_type c);
void resize(size_type n);
void reserve(size_type res_arg = 0);
void shrink_to_fit();
void clear() noexcept;
bool empty() const noexcept;
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
const_reference at(size_type n) const;
reference at(size_type n);
basic_string& operator+=(const basic_string& str);
template <class T>
basic_string& operator+=(const T& t); // C++17
basic_string& operator+=(const value_type* s);
basic_string& operator+=(value_type c);
basic_string& operator+=(initializer_list<value_type>);
basic_string& append(const basic_string& str);
template <class T>
basic_string& append(const T& t); // C++17
basic_string& append(const basic_string& str, size_type pos, size_type n=npos); //C++14
template <class T>
basic_string& append(const T& t, size_type pos, size_type n=npos); // C++17
basic_string& append(const value_type* s, size_type n);
basic_string& append(const value_type* s);
basic_string& append(size_type n, value_type c);
template<class InputIterator>
basic_string& append(InputIterator first, InputIterator last);
basic_string& append(initializer_list<value_type>);
void push_back(value_type c);
void pop_back();
reference front();
const_reference front() const;
reference back();
const_reference back() const;
basic_string& assign(const basic_string& str);
template <class T>
basic_string& assign(const T& t); // C++17
basic_string& assign(basic_string&& str);
basic_string& assign(const basic_string& str, size_type pos, size_type n=npos); // C++14
template <class T>
basic_string& assign(const T& t, size_type pos, size_type n=npos); // C++17
basic_string& assign(const value_type* s, size_type n);
basic_string& assign(const value_type* s);
basic_string& assign(size_type n, value_type c);
template<class InputIterator>
basic_string& assign(InputIterator first, InputIterator last);
basic_string& assign(initializer_list<value_type>);
basic_string& insert(size_type pos1, const basic_string& str);
template <class T>
basic_string& insert(size_type pos1, const T& t);
basic_string& insert(size_type pos1, const basic_string& str,
size_type pos2, size_type n);
template <class T>
basic_string& insert(size_type pos1, const T& t, size_type pos2, size_type n); // C++17
basic_string& insert(size_type pos, const value_type* s, size_type n=npos); //C++14
basic_string& insert(size_type pos, const value_type* s);
basic_string& insert(size_type pos, size_type n, value_type c);
iterator insert(const_iterator p, value_type c);
iterator insert(const_iterator p, size_type n, value_type c);
template<class InputIterator>
iterator insert(const_iterator p, InputIterator first, InputIterator last);
iterator insert(const_iterator p, initializer_list<value_type>);
basic_string& erase(size_type pos = 0, size_type n = npos);
iterator erase(const_iterator position);
iterator erase(const_iterator first, const_iterator last);
basic_string& replace(size_type pos1, size_type n1, const basic_string& str);
template <class T>
basic_string& replace(size_type pos1, size_type n1, const T& t); // C++17
basic_string& replace(size_type pos1, size_type n1, const basic_string& str,
size_type pos2, size_type n2=npos); // C++14
template <class T>
basic_string& replace(size_type pos1, size_type n1, const T& t,
size_type pos2, size_type n); // C++17
basic_string& replace(size_type pos, size_type n1, const value_type* s, size_type n2);
basic_string& replace(size_type pos, size_type n1, const value_type* s);
basic_string& replace(size_type pos, size_type n1, size_type n2, value_type c);
basic_string& replace(const_iterator i1, const_iterator i2, const basic_string& str);
template <class T>
basic_string& replace(const_iterator i1, const_iterator i2, const T& t); // C++17
basic_string& replace(const_iterator i1, const_iterator i2, const value_type* s, size_type n);
basic_string& replace(const_iterator i1, const_iterator i2, const value_type* s);
basic_string& replace(const_iterator i1, const_iterator i2, size_type n, value_type c);
template<class InputIterator>
basic_string& replace(const_iterator i1, const_iterator i2, InputIterator j1, InputIterator j2);
basic_string& replace(const_iterator i1, const_iterator i2, initializer_list<value_type>);
size_type copy(value_type* s, size_type n, size_type pos = 0) const;
basic_string substr(size_type pos = 0, size_type n = npos) const;
void swap(basic_string& str)
noexcept(allocator_traits<allocator_type>::propagate_on_container_swap::value ||
allocator_traits<allocator_type>::is_always_equal::value); // C++17
const value_type* c_str() const noexcept;
const value_type* data() const noexcept;
value_type* data() noexcept; // C++17
allocator_type get_allocator() const noexcept;
size_type find(const basic_string& str, size_type pos = 0) const noexcept;
template <class T>
size_type find(const T& t, size_type pos = 0) const; // C++17
size_type find(const value_type* s, size_type pos, size_type n) const noexcept;
size_type find(const value_type* s, size_type pos = 0) const noexcept;
size_type find(value_type c, size_type pos = 0) const noexcept;
size_type rfind(const basic_string& str, size_type pos = npos) const noexcept;
template <class T>
size_type rfind(const T& t, size_type pos = npos) const; // C++17
size_type rfind(const value_type* s, size_type pos, size_type n) const noexcept;
size_type rfind(const value_type* s, size_type pos = npos) const noexcept;
size_type rfind(value_type c, size_type pos = npos) const noexcept;
size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept;
template <class T>
size_type find_first_of(const T& t, size_type pos = 0) const; // C++17
size_type find_first_of(const value_type* s, size_type pos, size_type n) const noexcept;
size_type find_first_of(const value_type* s, size_type pos = 0) const noexcept;
size_type find_first_of(value_type c, size_type pos = 0) const noexcept;
size_type find_last_of(const basic_string& str, size_type pos = npos) const noexcept;
template <class T>
size_type find_last_of(const T& t, size_type pos = npos) const noexcept; // C++17
size_type find_last_of(const value_type* s, size_type pos, size_type n) const noexcept;
size_type find_last_of(const value_type* s, size_type pos = npos) const noexcept;
size_type find_last_of(value_type c, size_type pos = npos) const noexcept;
size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept;
template <class T>
size_type find_first_not_of(const T& t, size_type pos = 0) const; // C++17
size_type find_first_not_of(const value_type* s, size_type pos, size_type n) const noexcept;
size_type find_first_not_of(const value_type* s, size_type pos = 0) const noexcept;
size_type find_first_not_of(value_type c, size_type pos = 0) const noexcept;
size_type find_last_not_of(const basic_string& str, size_type pos = npos) const noexcept;
template <class T>
size_type find_last_not_of(const T& t, size_type pos = npos) const; // C++17
size_type find_last_not_of(const value_type* s, size_type pos, size_type n) const noexcept;
size_type find_last_not_of(const value_type* s, size_type pos = npos) const noexcept;
size_type find_last_not_of(value_type c, size_type pos = npos) const noexcept;
int compare(const basic_string& str) const noexcept;
template <class T>
int compare(const T& t) const noexcept; // C++17
int compare(size_type pos1, size_type n1, const basic_string& str) const;
template <class T>
int compare(size_type pos1, size_type n1, const T& t) const; // C++17
int compare(size_type pos1, size_type n1, const basic_string& str,
size_type pos2, size_type n2=npos) const; // C++14
template <class T>
int compare(size_type pos1, size_type n1, const T& t,
size_type pos2, size_type n2=npos) const; // C++17
int compare(const value_type* s) const noexcept;
int compare(size_type pos1, size_type n1, const value_type* s) const;
int compare(size_type pos1, size_type n1, const value_type* s, size_type n2) const;
bool starts_with(basic_string_view<charT, traits> sv) const noexcept; // C++2a
bool starts_with(charT c) const noexcept; // C++2a
bool starts_with(const charT* s) const; // C++2a
bool ends_with(basic_string_view<charT, traits> sv) const noexcept; // C++2a
bool ends_with(charT c) const noexcept; // C++2a
bool ends_with(const charT* s) const; // C++2a
bool __invariants() const;
};
template<class InputIterator,
class Allocator = allocator<typename iterator_traits<InputIterator>::value_type>>
basic_string(InputIterator, InputIterator, Allocator = Allocator())
-> basic_string<typename iterator_traits<InputIterator>::value_type,
char_traits<typename iterator_traits<InputIterator>::value_type>,
Allocator>; // C++17
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(const charT* lhs , const basic_string<charT,traits,Allocator>&rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(charT lhs, const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs);
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(const basic_string<charT, traits, Allocator>& lhs, charT rhs);
template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator==(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT,traits,Allocator>& lhs, const charT* rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator!=(const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator!=(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator!=(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator< (const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator< (const basic_string<charT, traits, Allocator>& lhs, const charT* rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator< (const charT* lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator> (const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator> (const basic_string<charT, traits, Allocator>& lhs, const charT* rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator> (const charT* lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator<=(const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator<=(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator<=(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator>=(const basic_string<charT, traits, Allocator>& lhs,
const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator>=(const basic_string<charT, traits, Allocator>& lhs, const charT* rhs) noexcept;
template<class charT, class traits, class Allocator>
bool operator>=(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs) noexcept;
template<class charT, class traits, class Allocator>
void swap(basic_string<charT, traits, Allocator>& lhs,
basic_string<charT, traits, Allocator>& rhs)
noexcept(noexcept(lhs.swap(rhs)));
template<class charT, class traits, class Allocator>
basic_istream<charT, traits>&
operator>>(basic_istream<charT, traits>& is, basic_string<charT, traits, Allocator>& str);
template<class charT, class traits, class Allocator>
basic_ostream<charT, traits>&
operator<<(basic_ostream<charT, traits>& os, const basic_string<charT, traits, Allocator>& str);
template<class charT, class traits, class Allocator>
basic_istream<charT, traits>&
getline(basic_istream<charT, traits>& is, basic_string<charT, traits, Allocator>& str,
charT delim);
template<class charT, class traits, class Allocator>
basic_istream<charT, traits>&
getline(basic_istream<charT, traits>& is, basic_string<charT, traits, Allocator>& str);
template<class charT, class traits, class Allocator, class U>
void erase(basic_string<charT, traits, Allocator>& c, const U& value); // C++20
template<class charT, class traits, class Allocator, class Predicate>
void erase_if(basic_string<charT, traits, Allocator>& c, Predicate pred); // C++20
typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
typedef basic_string<char16_t> u16string;
typedef basic_string<char32_t> u32string;
int stoi (const string& str, size_t* idx = 0, int base = 10);
long stol (const string& str, size_t* idx = 0, int base = 10);
unsigned long stoul (const string& str, size_t* idx = 0, int base = 10);
long long stoll (const string& str, size_t* idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t* idx = 0, int base = 10);
float stof (const string& str, size_t* idx = 0);
double stod (const string& str, size_t* idx = 0);
long double stold(const string& str, size_t* idx = 0);
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
long stol (const wstring& str, size_t* idx = 0, int base = 10);
unsigned long stoul (const wstring& str, size_t* idx = 0, int base = 10);
long long stoll (const wstring& str, size_t* idx = 0, int base = 10);
unsigned long long stoull(const wstring& str, size_t* idx = 0, int base = 10);
float stof (const wstring& str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);
long double stold(const wstring& str, size_t* idx = 0);
wstring to_wstring(int val);
wstring to_wstring(unsigned val);
wstring to_wstring(long val);
wstring to_wstring(unsigned long val);
wstring to_wstring(long long val);
wstring to_wstring(unsigned long long val);
wstring to_wstring(float val);
wstring to_wstring(double val);
wstring to_wstring(long double val);
template <> struct hash<string>;
template <> struct hash<u16string>;
template <> struct hash<u32string>;
template <> struct hash<wstring>;
basic_string<char> operator "" s( const char *str, size_t len ); // C++14
basic_string<wchar_t> operator "" s( const wchar_t *str, size_t len ); // C++14
basic_string<char16_t> operator "" s( const char16_t *str, size_t len ); // C++14
basic_string<char32_t> operator "" s( const char32_t *str, size_t len ); // C++14
} // std
*/
#include <__config>
#include <string_view>
#include <iosfwd>
#include <cstring>
#include <cstdio> // For EOF.
#include <cwchar>
#include <algorithm>
#include <iterator>
#include <utility>
#include <memory>
#include <stdexcept>
#include <type_traits>
#include <initializer_list>
#include <__functional_base>
#include <version>
#ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
#include <cstdint>
#endif
#include <__debug>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
_LIBCPP_PUSH_MACROS
#include <__undef_macros>
_LIBCPP_BEGIN_NAMESPACE_STD
// fpos
template <class _StateT>
class _LIBCPP_TEMPLATE_VIS fpos
{
private:
_StateT __st_;
streamoff __off_;
public:
_LIBCPP_INLINE_VISIBILITY fpos(streamoff __off = streamoff()) : __st_(), __off_(__off) {}
_LIBCPP_INLINE_VISIBILITY operator streamoff() const {return __off_;}
_LIBCPP_INLINE_VISIBILITY _StateT state() const {return __st_;}
_LIBCPP_INLINE_VISIBILITY void state(_StateT __st) {__st_ = __st;}
_LIBCPP_INLINE_VISIBILITY fpos& operator+=(streamoff __off) {__off_ += __off; return *this;}
_LIBCPP_INLINE_VISIBILITY fpos operator+ (streamoff __off) const {fpos __t(*this); __t += __off; return __t;}
_LIBCPP_INLINE_VISIBILITY fpos& operator-=(streamoff __off) {__off_ -= __off; return *this;}
_LIBCPP_INLINE_VISIBILITY fpos operator- (streamoff __off) const {fpos __t(*this); __t -= __off; return __t;}
};
template <class _StateT>
inline _LIBCPP_INLINE_VISIBILITY
streamoff operator-(const fpos<_StateT>& __x, const fpos<_StateT>& __y)
{return streamoff(__x) - streamoff(__y);}
template <class _StateT>
inline _LIBCPP_INLINE_VISIBILITY
bool operator==(const fpos<_StateT>& __x, const fpos<_StateT>& __y)
{return streamoff(__x) == streamoff(__y);}
template <class _StateT>
inline _LIBCPP_INLINE_VISIBILITY
bool operator!=(const fpos<_StateT>& __x, const fpos<_StateT>& __y)
{return streamoff(__x) != streamoff(__y);}
// basic_string
template<class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>
operator+(const basic_string<_CharT, _Traits, _Allocator>& __x,
const basic_string<_CharT, _Traits, _Allocator>& __y);
template<class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>
operator+(const _CharT* __x, const basic_string<_CharT,_Traits,_Allocator>& __y);
template<class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>
operator+(_CharT __x, const basic_string<_CharT,_Traits,_Allocator>& __y);
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_string<_CharT, _Traits, _Allocator>
operator+(const basic_string<_CharT, _Traits, _Allocator>& __x, const _CharT* __y);
template<class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>
operator+(const basic_string<_CharT, _Traits, _Allocator>& __x, _CharT __y);
_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS string operator+<char, char_traits<char>, allocator<char> >(char const*, string const&))
template <bool>
class _LIBCPP_TEMPLATE_VIS __basic_string_common
{
protected:
_LIBCPP_NORETURN void __throw_length_error() const;
_LIBCPP_NORETURN void __throw_out_of_range() const;
};
template <bool __b>
void
__basic_string_common<__b>::__throw_length_error() const
{
_VSTD::__throw_length_error("basic_string");
}
template <bool __b>
void
__basic_string_common<__b>::__throw_out_of_range() const
{
_VSTD::__throw_out_of_range("basic_string");
}
_LIBCPP_EXTERN_TEMPLATE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS __basic_string_common<true>)
#ifdef _LIBCPP_NO_EXCEPTIONS
template <class _Iter>
struct __libcpp_string_gets_noexcept_iterator_impl : public true_type {};
#elif defined(_LIBCPP_HAS_NO_NOEXCEPT)
template <class _Iter>
struct __libcpp_string_gets_noexcept_iterator_impl : public false_type {};
#else
template <class _Iter, bool = __is_forward_iterator<_Iter>::value>
struct __libcpp_string_gets_noexcept_iterator_impl : public _LIBCPP_BOOL_CONSTANT((
noexcept(++(declval<_Iter&>())) &&
is_nothrow_assignable<_Iter&, _Iter>::value &&
noexcept(declval<_Iter>() == declval<_Iter>()) &&
noexcept(*declval<_Iter>())
)) {};
template <class _Iter>
struct __libcpp_string_gets_noexcept_iterator_impl<_Iter, false> : public false_type {};
#endif
template <class _Iter>
struct __libcpp_string_gets_noexcept_iterator
: public _LIBCPP_BOOL_CONSTANT(__libcpp_is_trivial_iterator<_Iter>::value || __libcpp_string_gets_noexcept_iterator_impl<_Iter>::value) {};
template <class _CharT, class _Traits, class _Tp>
struct __can_be_converted_to_string_view : public _LIBCPP_BOOL_CONSTANT(
( is_convertible<const _Tp&, basic_string_view<_CharT, _Traits> >::value &&
!is_convertible<const _Tp&, const _CharT*>::value)) {};
#ifdef _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
template <class _CharT, size_t = sizeof(_CharT)>
struct __padding
{
unsigned char __xx[sizeof(_CharT)-1];
};
template <class _CharT>
struct __padding<_CharT, 1>
{
};
#endif // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
template<class _CharT, class _Traits, class _Allocator>
class _LIBCPP_TEMPLATE_VIS basic_string
: private __basic_string_common<true>
{
public:
typedef basic_string __self;
typedef basic_string_view<_CharT, _Traits> __self_view;
typedef _Traits traits_type;
typedef _CharT value_type;
typedef _Allocator allocator_type;
typedef allocator_traits<allocator_type> __alloc_traits;
typedef typename __alloc_traits::size_type size_type;
typedef typename __alloc_traits::difference_type difference_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef typename __alloc_traits::pointer pointer;
typedef typename __alloc_traits::const_pointer const_pointer;
static_assert((!is_array<value_type>::value), "Character type of basic_string must not be an array");
static_assert(( is_standard_layout<value_type>::value), "Character type of basic_string must be standard-layout");
static_assert(( is_trivial<value_type>::value), "Character type of basic_string must be trivial");
static_assert(( is_same<_CharT, typename traits_type::char_type>::value),
"traits_type::char_type must be the same type as CharT");
static_assert(( is_same<typename allocator_type::value_type, value_type>::value),
"Allocator::value_type must be same type as value_type");
#if defined(_LIBCPP_RAW_ITERATORS)
typedef pointer iterator;
typedef const_pointer const_iterator;
#else // defined(_LIBCPP_RAW_ITERATORS)
typedef __wrap_iter<pointer> iterator;
typedef __wrap_iter<const_pointer> const_iterator;
#endif // defined(_LIBCPP_RAW_ITERATORS)
typedef _VSTD::reverse_iterator<iterator> reverse_iterator;
typedef _VSTD::reverse_iterator<const_iterator> const_reverse_iterator;
private:
#ifdef _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
struct __long
{
pointer __data_;
size_type __size_;
size_type __cap_;
};
#ifdef _LIBCPP_BIG_ENDIAN
static const size_type __short_mask = 0x01;
static const size_type __long_mask = 0x1ul;
#else // _LIBCPP_BIG_ENDIAN
static const size_type __short_mask = 0x80;
static const size_type __long_mask = ~(size_type(~0) >> 1);
#endif // _LIBCPP_BIG_ENDIAN
enum {__min_cap = (sizeof(__long) - 1)/sizeof(value_type) > 2 ?
(sizeof(__long) - 1)/sizeof(value_type) : 2};
struct __short
{
value_type __data_[__min_cap];
struct
: __padding<value_type>
{
unsigned char __size_;
};
};
#else
struct __long
{
size_type __cap_;
size_type __size_;
pointer __data_;
};
#ifdef _LIBCPP_BIG_ENDIAN
static const size_type __short_mask = 0x80;
static const size_type __long_mask = ~(size_type(~0) >> 1);
#else // _LIBCPP_BIG_ENDIAN
static const size_type __short_mask = 0x01;
static const size_type __long_mask = 0x1ul;
#endif // _LIBCPP_BIG_ENDIAN
enum {__min_cap = (sizeof(__long) - 1)/sizeof(value_type) > 2 ?
(sizeof(__long) - 1)/sizeof(value_type) : 2};
struct __short
{
union
{
unsigned char __size_;
value_type __lx;
};
value_type __data_[__min_cap];
};
#endif // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
union __ulx{__long __lx; __short __lxx;};
enum {__n_words = sizeof(__ulx) / sizeof(size_type)};
struct __raw
{
size_type __words[__n_words];
};
struct __rep
{
union
{
__long __l;
__short __s;
__raw __r;
};
};
__compressed_pair<__rep, allocator_type> __r_;
public:
static const size_type npos = -1;
_LIBCPP_INLINE_VISIBILITY basic_string()
_NOEXCEPT_(is_nothrow_default_constructible<allocator_type>::value);
_LIBCPP_INLINE_VISIBILITY explicit basic_string(const allocator_type& __a)
#if _LIBCPP_STD_VER <= 14
_NOEXCEPT_(is_nothrow_copy_constructible<allocator_type>::value);
#else
_NOEXCEPT;
#endif
basic_string(const basic_string& __str);
basic_string(const basic_string& __str, const allocator_type& __a);
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
basic_string(basic_string&& __str)
#if _LIBCPP_STD_VER <= 14
_NOEXCEPT_(is_nothrow_move_constructible<allocator_type>::value);
#else
_NOEXCEPT;
#endif
_LIBCPP_INLINE_VISIBILITY
basic_string(basic_string&& __str, const allocator_type& __a);
#endif // _LIBCPP_CXX03_LANG
#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
template <class = typename enable_if<__is_allocator<_Allocator>::value, nullptr_t>::type>
#endif
_LIBCPP_INLINE_VISIBILITY
basic_string(const _CharT* __s) {
_LIBCPP_ASSERT(__s != nullptr, "basic_string(const char*) detected nullptr");
__init(__s, traits_type::length(__s));
# if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
# endif
}
#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
template <class = typename enable_if<__is_allocator<_Allocator>::value, nullptr_t>::type>
#endif
_LIBCPP_INLINE_VISIBILITY
basic_string(const _CharT* __s, const _Allocator& __a);
_LIBCPP_INLINE_VISIBILITY
basic_string(const _CharT* __s, size_type __n);
_LIBCPP_INLINE_VISIBILITY
basic_string(const _CharT* __s, size_type __n, const _Allocator& __a);
_LIBCPP_INLINE_VISIBILITY
basic_string(size_type __n, _CharT __c);
#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
template <class = typename enable_if<__is_allocator<_Allocator>::value, nullptr_t>::type>
#endif
_LIBCPP_INLINE_VISIBILITY
basic_string(size_type __n, _CharT __c, const _Allocator& __a);
basic_string(const basic_string& __str, size_type __pos, size_type __n,
const _Allocator& __a = _Allocator());
_LIBCPP_INLINE_VISIBILITY
basic_string(const basic_string& __str, size_type __pos,
const _Allocator& __a = _Allocator());
template<class _Tp, class = typename enable_if<__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value, void>::type>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
basic_string(const _Tp& __t, size_type __pos, size_type __n,
const allocator_type& __a = allocator_type());
template<class _Tp, class = typename enable_if<__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value, void>::type>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
explicit basic_string(const _Tp& __t);
template<class _Tp, class = typename enable_if<__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value, void>::type>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
explicit basic_string(const _Tp& __t, const allocator_type& __a);
template<class _InputIterator, class = typename enable_if<__is_input_iterator<_InputIterator>::value>::type>
_LIBCPP_INLINE_VISIBILITY
basic_string(_InputIterator __first, _InputIterator __last);
template<class _InputIterator, class = typename enable_if<__is_input_iterator<_InputIterator>::value>::type>
_LIBCPP_INLINE_VISIBILITY
basic_string(_InputIterator __first, _InputIterator __last, const allocator_type& __a);
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
basic_string(initializer_list<_CharT> __il);
_LIBCPP_INLINE_VISIBILITY
basic_string(initializer_list<_CharT> __il, const _Allocator& __a);
#endif // _LIBCPP_CXX03_LANG
inline ~basic_string();
_LIBCPP_INLINE_VISIBILITY
operator __self_view() const _NOEXCEPT { return __self_view(data(), size()); }
basic_string& operator=(const basic_string& __str);
template <class _Tp, class = typename enable_if<__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value, void>::type>
basic_string& operator=(const _Tp& __t)
{__self_view __sv = __t; return assign(__sv);}
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
basic_string& operator=(basic_string&& __str)
_NOEXCEPT_((__noexcept_move_assign_container<_Allocator, __alloc_traits>::value));
_LIBCPP_INLINE_VISIBILITY
basic_string& operator=(initializer_list<value_type> __il) {return assign(__il.begin(), __il.size());}
#endif
_LIBCPP_INLINE_VISIBILITY basic_string& operator=(const value_type* __s) {return assign(__s);}
basic_string& operator=(value_type __c);
#if _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_INLINE_VISIBILITY
iterator begin() _NOEXCEPT
{return iterator(this, __get_pointer());}
_LIBCPP_INLINE_VISIBILITY
const_iterator begin() const _NOEXCEPT
{return const_iterator(this, __get_pointer());}
_LIBCPP_INLINE_VISIBILITY
iterator end() _NOEXCEPT
{return iterator(this, __get_pointer() + size());}
_LIBCPP_INLINE_VISIBILITY
const_iterator end() const _NOEXCEPT
{return const_iterator(this, __get_pointer() + size());}
#else
_LIBCPP_INLINE_VISIBILITY
iterator begin() _NOEXCEPT
{return iterator(__get_pointer());}
_LIBCPP_INLINE_VISIBILITY
const_iterator begin() const _NOEXCEPT
{return const_iterator(__get_pointer());}
_LIBCPP_INLINE_VISIBILITY
iterator end() _NOEXCEPT
{return iterator(__get_pointer() + size());}
_LIBCPP_INLINE_VISIBILITY
const_iterator end() const _NOEXCEPT
{return const_iterator(__get_pointer() + size());}
#endif // _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_INLINE_VISIBILITY
reverse_iterator rbegin() _NOEXCEPT
{return reverse_iterator(end());}
_LIBCPP_INLINE_VISIBILITY
const_reverse_iterator rbegin() const _NOEXCEPT
{return const_reverse_iterator(end());}
_LIBCPP_INLINE_VISIBILITY
reverse_iterator rend() _NOEXCEPT
{return reverse_iterator(begin());}
_LIBCPP_INLINE_VISIBILITY
const_reverse_iterator rend() const _NOEXCEPT
{return const_reverse_iterator(begin());}
_LIBCPP_INLINE_VISIBILITY
const_iterator cbegin() const _NOEXCEPT
{return begin();}
_LIBCPP_INLINE_VISIBILITY
const_iterator cend() const _NOEXCEPT
{return end();}
_LIBCPP_INLINE_VISIBILITY
const_reverse_iterator crbegin() const _NOEXCEPT
{return rbegin();}
_LIBCPP_INLINE_VISIBILITY
const_reverse_iterator crend() const _NOEXCEPT
{return rend();}
_LIBCPP_INLINE_VISIBILITY size_type size() const _NOEXCEPT
{return __is_long() ? __get_long_size() : __get_short_size();}
_LIBCPP_INLINE_VISIBILITY size_type length() const _NOEXCEPT {return size();}
_LIBCPP_INLINE_VISIBILITY size_type max_size() const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY size_type capacity() const _NOEXCEPT
{return (__is_long() ? __get_long_cap()
: static_cast<size_type>(__min_cap)) - 1;}
void resize(size_type __n, value_type __c);
_LIBCPP_INLINE_VISIBILITY void resize(size_type __n) {resize(__n, value_type());}
void reserve(size_type __res_arg);
_LIBCPP_INLINE_VISIBILITY void __resize_default_init(size_type __n);
_LIBCPP_INLINE_VISIBILITY
void reserve() _NOEXCEPT {reserve(0);}
_LIBCPP_INLINE_VISIBILITY
void shrink_to_fit() _NOEXCEPT {reserve();}
_LIBCPP_INLINE_VISIBILITY
void clear() _NOEXCEPT;
_LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
bool empty() const _NOEXCEPT {return size() == 0;}
_LIBCPP_INLINE_VISIBILITY const_reference operator[](size_type __pos) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY reference operator[](size_type __pos) _NOEXCEPT;
const_reference at(size_type __n) const;
reference at(size_type __n);
_LIBCPP_INLINE_VISIBILITY basic_string& operator+=(const basic_string& __str) {return append(__str);}
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
operator+=(const _Tp& __t) {__self_view __sv = __t; return append(__sv);}
_LIBCPP_INLINE_VISIBILITY basic_string& operator+=(const value_type* __s) {return append(__s);}
_LIBCPP_INLINE_VISIBILITY basic_string& operator+=(value_type __c) {push_back(__c); return *this;}
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY basic_string& operator+=(initializer_list<value_type> __il) {return append(__il);}
#endif // _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
basic_string& append(const basic_string& __str);
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
append(const _Tp& __t) { __self_view __sv = __t; return append(__sv.data(), __sv.size()); }
basic_string& append(const basic_string& __str, size_type __pos, size_type __n=npos);
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
append(const _Tp& __t, size_type __pos, size_type __n=npos);
basic_string& append(const value_type* __s, size_type __n);
basic_string& append(const value_type* __s);
basic_string& append(size_type __n, value_type __c);
_LIBCPP_INLINE_VISIBILITY
void __append_default_init(size_type __n);
template <class _ForwardIterator>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
basic_string& __append_forward_unsafe(_ForwardIterator, _ForwardIterator);
template<class _InputIterator>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__is_exactly_input_iterator<_InputIterator>::value
|| !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
basic_string&
>::type
_LIBCPP_INLINE_VISIBILITY
append(_InputIterator __first, _InputIterator __last) {
const basic_string __temp (__first, __last, __alloc());
append(__temp.data(), __temp.size());
return *this;
}
template<class _ForwardIterator>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__is_forward_iterator<_ForwardIterator>::value
&& __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
basic_string&
>::type
_LIBCPP_INLINE_VISIBILITY
append(_ForwardIterator __first, _ForwardIterator __last) {
return __append_forward_unsafe(__first, __last);
}
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
basic_string& append(initializer_list<value_type> __il) {return append(__il.begin(), __il.size());}
#endif // _LIBCPP_CXX03_LANG
void push_back(value_type __c);
_LIBCPP_INLINE_VISIBILITY
void pop_back();
_LIBCPP_INLINE_VISIBILITY reference front() _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY const_reference front() const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY reference back() _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY const_reference back() const _NOEXCEPT;
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
assign(const _Tp & __t) { __self_view __sv = __t; return assign(__sv.data(), __sv.size()); }
_LIBCPP_INLINE_VISIBILITY
basic_string& assign(const basic_string& __str) { return *this = __str; }
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
basic_string& assign(basic_string&& __str)
_NOEXCEPT_((__noexcept_move_assign_container<_Allocator, __alloc_traits>::value))
{*this = _VSTD::move(__str); return *this;}
#endif
basic_string& assign(const basic_string& __str, size_type __pos, size_type __n=npos);
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
assign(const _Tp & __t, size_type __pos, size_type __n=npos);
basic_string& assign(const value_type* __s, size_type __n);
basic_string& assign(const value_type* __s);
basic_string& assign(size_type __n, value_type __c);
template<class _InputIterator>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__is_exactly_input_iterator<_InputIterator>::value
|| !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
basic_string&
>::type
assign(_InputIterator __first, _InputIterator __last);
template<class _ForwardIterator>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__is_forward_iterator<_ForwardIterator>::value
&& __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
basic_string&
>::type
assign(_ForwardIterator __first, _ForwardIterator __last);
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
basic_string& assign(initializer_list<value_type> __il) {return assign(__il.begin(), __il.size());}
#endif // _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
basic_string& insert(size_type __pos1, const basic_string& __str);
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
insert(size_type __pos1, const _Tp& __t)
{ __self_view __sv = __t; return insert(__pos1, __sv.data(), __sv.size()); }
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
insert(size_type __pos1, const _Tp& __t, size_type __pos2, size_type __n=npos);
basic_string& insert(size_type __pos1, const basic_string& __str, size_type __pos2, size_type __n=npos);
basic_string& insert(size_type __pos, const value_type* __s, size_type __n);
basic_string& insert(size_type __pos, const value_type* __s);
basic_string& insert(size_type __pos, size_type __n, value_type __c);
iterator insert(const_iterator __pos, value_type __c);
_LIBCPP_INLINE_VISIBILITY
iterator insert(const_iterator __pos, size_type __n, value_type __c);
template<class _InputIterator>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__is_exactly_input_iterator<_InputIterator>::value
|| !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
iterator
>::type
insert(const_iterator __pos, _InputIterator __first, _InputIterator __last);
template<class _ForwardIterator>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__is_forward_iterator<_ForwardIterator>::value
&& __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
iterator
>::type
insert(const_iterator __pos, _ForwardIterator __first, _ForwardIterator __last);
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
iterator insert(const_iterator __pos, initializer_list<value_type> __il)
{return insert(__pos, __il.begin(), __il.end());}
#endif // _LIBCPP_CXX03_LANG
basic_string& erase(size_type __pos = 0, size_type __n = npos);
_LIBCPP_INLINE_VISIBILITY
iterator erase(const_iterator __pos);
_LIBCPP_INLINE_VISIBILITY
iterator erase(const_iterator __first, const_iterator __last);
_LIBCPP_INLINE_VISIBILITY
basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str);
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
replace(size_type __pos1, size_type __n1, const _Tp& __t) { __self_view __sv = __t; return replace(__pos1, __n1, __sv.data(), __sv.size()); }
basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2=npos);
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
replace(size_type __pos1, size_type __n1, const _Tp& __t, size_type __pos2, size_type __n2=npos);
basic_string& replace(size_type __pos, size_type __n1, const value_type* __s, size_type __n2);
basic_string& replace(size_type __pos, size_type __n1, const value_type* __s);
basic_string& replace(size_type __pos, size_type __n1, size_type __n2, value_type __c);
_LIBCPP_INLINE_VISIBILITY
basic_string& replace(const_iterator __i1, const_iterator __i2, const basic_string& __str);
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string&
>::type
replace(const_iterator __i1, const_iterator __i2, const _Tp& __t) { __self_view __sv = __t; return replace(__i1 - begin(), __i2 - __i1, __sv); }
_LIBCPP_INLINE_VISIBILITY
basic_string& replace(const_iterator __i1, const_iterator __i2, const value_type* __s, size_type __n);
_LIBCPP_INLINE_VISIBILITY
basic_string& replace(const_iterator __i1, const_iterator __i2, const value_type* __s);
_LIBCPP_INLINE_VISIBILITY
basic_string& replace(const_iterator __i1, const_iterator __i2, size_type __n, value_type __c);
template<class _InputIterator>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__is_input_iterator<_InputIterator>::value,
basic_string&
>::type
replace(const_iterator __i1, const_iterator __i2, _InputIterator __j1, _InputIterator __j2);
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
basic_string& replace(const_iterator __i1, const_iterator __i2, initializer_list<value_type> __il)
{return replace(__i1, __i2, __il.begin(), __il.end());}
#endif // _LIBCPP_CXX03_LANG
size_type copy(value_type* __s, size_type __n, size_type __pos = 0) const;
_LIBCPP_INLINE_VISIBILITY
basic_string substr(size_type __pos = 0, size_type __n = npos) const;
_LIBCPP_INLINE_VISIBILITY
void swap(basic_string& __str)
#if _LIBCPP_STD_VER >= 14
_NOEXCEPT;
#else
_NOEXCEPT_(!__alloc_traits::propagate_on_container_swap::value ||
__is_nothrow_swappable<allocator_type>::value);
#endif
_LIBCPP_INLINE_VISIBILITY
const value_type* c_str() const _NOEXCEPT {return data();}
_LIBCPP_INLINE_VISIBILITY
const value_type* data() const _NOEXCEPT {return _VSTD::__to_raw_pointer(__get_pointer());}
#if _LIBCPP_STD_VER > 14 || defined(_LIBCPP_BUILDING_LIBRARY)
_LIBCPP_INLINE_VISIBILITY
value_type* data() _NOEXCEPT {return _VSTD::__to_raw_pointer(__get_pointer());}
#endif
_LIBCPP_INLINE_VISIBILITY
allocator_type get_allocator() const _NOEXCEPT {return __alloc();}
_LIBCPP_INLINE_VISIBILITY
size_type find(const basic_string& __str, size_type __pos = 0) const _NOEXCEPT;
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
size_type
>::type
find(const _Tp& __t, size_type __pos = 0) const;
size_type find(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find(const value_type* __s, size_type __pos = 0) const _NOEXCEPT;
size_type find(value_type __c, size_type __pos = 0) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type rfind(const basic_string& __str, size_type __pos = npos) const _NOEXCEPT;
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
size_type
>::type
rfind(const _Tp& __t, size_type __pos = npos) const;
size_type rfind(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type rfind(const value_type* __s, size_type __pos = npos) const _NOEXCEPT;
size_type rfind(value_type __c, size_type __pos = npos) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_first_of(const basic_string& __str, size_type __pos = 0) const _NOEXCEPT;
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
size_type
>::type
find_first_of(const _Tp& __t, size_type __pos = 0) const;
size_type find_first_of(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_first_of(const value_type* __s, size_type __pos = 0) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_first_of(value_type __c, size_type __pos = 0) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_last_of(const basic_string& __str, size_type __pos = npos) const _NOEXCEPT;
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
size_type
>::type
find_last_of(const _Tp& __t, size_type __pos = npos) const;
size_type find_last_of(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_last_of(const value_type* __s, size_type __pos = npos) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_last_of(value_type __c, size_type __pos = npos) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_first_not_of(const basic_string& __str, size_type __pos = 0) const _NOEXCEPT;
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
size_type
>::type
find_first_not_of(const _Tp &__t, size_type __pos = 0) const;
size_type find_first_not_of(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_first_not_of(const value_type* __s, size_type __pos = 0) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_first_not_of(value_type __c, size_type __pos = 0) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_last_not_of(const basic_string& __str, size_type __pos = npos) const _NOEXCEPT;
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
size_type
>::type
find_last_not_of(const _Tp& __t, size_type __pos = npos) const;
size_type find_last_not_of(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_last_not_of(const value_type* __s, size_type __pos = npos) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
size_type find_last_not_of(value_type __c, size_type __pos = npos) const _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
int compare(const basic_string& __str) const _NOEXCEPT;
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
int
>::type
compare(const _Tp &__t) const;
template <class _Tp>
_LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
int
>::type
compare(size_type __pos1, size_type __n1, const _Tp& __t) const;
_LIBCPP_INLINE_VISIBILITY
int compare(size_type __pos1, size_type __n1, const basic_string& __str) const;
int compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2=npos) const;
template <class _Tp>
inline _LIBCPP_INLINE_VISIBILITY
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
int
>::type
compare(size_type __pos1, size_type __n1, const _Tp& __t, size_type __pos2, size_type __n2=npos) const;
int compare(const value_type* __s) const _NOEXCEPT;
int compare(size_type __pos1, size_type __n1, const value_type* __s) const;
int compare(size_type __pos1, size_type __n1, const value_type* __s, size_type __n2) const;
#if _LIBCPP_STD_VER > 17
_LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
bool starts_with(__self_view __sv) const _NOEXCEPT
{ return __self_view(data(), size()).starts_with(__sv); }
_LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
bool starts_with(value_type __c) const _NOEXCEPT
{ return !empty() && _Traits::eq(front(), __c); }
_LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
bool starts_with(const value_type* __s) const _NOEXCEPT
{ return starts_with(__self_view(__s)); }
_LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
bool ends_with(__self_view __sv) const _NOEXCEPT
{ return __self_view(data(), size()).ends_with( __sv); }
_LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
bool ends_with(value_type __c) const _NOEXCEPT
{ return !empty() && _Traits::eq(back(), __c); }
_LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
bool ends_with(const value_type* __s) const _NOEXCEPT
{ return ends_with(__self_view(__s)); }
#endif
_LIBCPP_INLINE_VISIBILITY bool __invariants() const;
_LIBCPP_INLINE_VISIBILITY void __clear_and_shrink() _NOEXCEPT;
_LIBCPP_INLINE_VISIBILITY
bool __is_long() const _NOEXCEPT
{return bool(__r_.first().__s.__size_ & __short_mask);}
#if _LIBCPP_DEBUG_LEVEL >= 2
bool __dereferenceable(const const_iterator* __i) const;
bool __decrementable(const const_iterator* __i) const;
bool __addable(const const_iterator* __i, ptrdiff_t __n) const;
bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const;
#endif // _LIBCPP_DEBUG_LEVEL >= 2
private:
_LIBCPP_INLINE_VISIBILITY
allocator_type& __alloc() _NOEXCEPT
{return __r_.second();}
_LIBCPP_INLINE_VISIBILITY
const allocator_type& __alloc() const _NOEXCEPT
{return __r_.second();}
#ifdef _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
_LIBCPP_INLINE_VISIBILITY
void __set_short_size(size_type __s) _NOEXCEPT
# ifdef _LIBCPP_BIG_ENDIAN
{__r_.first().__s.__size_ = (unsigned char)(__s << 1);}
# else
{__r_.first().__s.__size_ = (unsigned char)(__s);}
# endif
_LIBCPP_INLINE_VISIBILITY
size_type __get_short_size() const _NOEXCEPT
# ifdef _LIBCPP_BIG_ENDIAN
{return __r_.first().__s.__size_ >> 1;}
# else
{return __r_.first().__s.__size_;}
# endif
#else // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
_LIBCPP_INLINE_VISIBILITY
void __set_short_size(size_type __s) _NOEXCEPT
# ifdef _LIBCPP_BIG_ENDIAN
{__r_.first().__s.__size_ = (unsigned char)(__s);}
# else
{__r_.first().__s.__size_ = (unsigned char)(__s << 1);}
# endif
_LIBCPP_INLINE_VISIBILITY
size_type __get_short_size() const _NOEXCEPT
# ifdef _LIBCPP_BIG_ENDIAN
{return __r_.first().__s.__size_;}
# else
{return __r_.first().__s.__size_ >> 1;}
# endif
#endif // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
_LIBCPP_INLINE_VISIBILITY
void __set_long_size(size_type __s) _NOEXCEPT
{__r_.first().__l.__size_ = __s;}
_LIBCPP_INLINE_VISIBILITY
size_type __get_long_size() const _NOEXCEPT
{return __r_.first().__l.__size_;}
_LIBCPP_INLINE_VISIBILITY
void __set_size(size_type __s) _NOEXCEPT
{if (__is_long()) __set_long_size(__s); else __set_short_size(__s);}
_LIBCPP_INLINE_VISIBILITY
void __set_long_cap(size_type __s) _NOEXCEPT
{__r_.first().__l.__cap_ = __long_mask | __s;}
_LIBCPP_INLINE_VISIBILITY
size_type __get_long_cap() const _NOEXCEPT
{return __r_.first().__l.__cap_ & size_type(~__long_mask);}
_LIBCPP_INLINE_VISIBILITY
void __set_long_pointer(pointer __p) _NOEXCEPT
{__r_.first().__l.__data_ = __p;}
_LIBCPP_INLINE_VISIBILITY
pointer __get_long_pointer() _NOEXCEPT
{return __r_.first().__l.__data_;}
_LIBCPP_INLINE_VISIBILITY
const_pointer __get_long_pointer() const _NOEXCEPT
{return __r_.first().__l.__data_;}
_LIBCPP_INLINE_VISIBILITY
pointer __get_short_pointer() _NOEXCEPT
{return pointer_traits<pointer>::pointer_to(__r_.first().__s.__data_[0]);}
_LIBCPP_INLINE_VISIBILITY
const_pointer __get_short_pointer() const _NOEXCEPT
{return pointer_traits<const_pointer>::pointer_to(__r_.first().__s.__data_[0]);}
_LIBCPP_INLINE_VISIBILITY
pointer __get_pointer() _NOEXCEPT
{return __is_long() ? __get_long_pointer() : __get_short_pointer();}
_LIBCPP_INLINE_VISIBILITY
const_pointer __get_pointer() const _NOEXCEPT
{return __is_long() ? __get_long_pointer() : __get_short_pointer();}
_LIBCPP_INLINE_VISIBILITY
void __zero() _NOEXCEPT
{
size_type (&__a)[__n_words] = __r_.first().__r.__words;
for (unsigned __i = 0; __i < __n_words; ++__i)
__a[__i] = 0;
}
template <size_type __a> static
_LIBCPP_INLINE_VISIBILITY
size_type __align_it(size_type __s) _NOEXCEPT
{return (__s + (__a-1)) & ~(__a-1);}
enum {__alignment = 16};
static _LIBCPP_INLINE_VISIBILITY
size_type __recommend(size_type __s) _NOEXCEPT
{
if (__s < __min_cap) return static_cast<size_type>(__min_cap) - 1;
size_type __guess = __align_it<sizeof(value_type) < __alignment ?
__alignment/sizeof(value_type) : 1 > (__s+1) - 1;
if (__guess == __min_cap) ++__guess;
return __guess;
}
inline
void __init(const value_type* __s, size_type __sz, size_type __reserve);
inline
void __init(const value_type* __s, size_type __sz);
inline
void __init(size_type __n, value_type __c);
template <class _InputIterator>
inline
typename enable_if
<
__is_exactly_input_iterator<_InputIterator>::value,
void
>::type
__init(_InputIterator __first, _InputIterator __last);
template <class _ForwardIterator>
inline
typename enable_if
<
__is_forward_iterator<_ForwardIterator>::value,
void
>::type
__init(_ForwardIterator __first, _ForwardIterator __last);
void __grow_by(size_type __old_cap, size_type __delta_cap, size_type __old_sz,
size_type __n_copy, size_type __n_del, size_type __n_add = 0);
void __grow_by_and_replace(size_type __old_cap, size_type __delta_cap, size_type __old_sz,
size_type __n_copy, size_type __n_del,
size_type __n_add, const value_type* __p_new_stuff);
_LIBCPP_INLINE_VISIBILITY
void __erase_to_end(size_type __pos);
_LIBCPP_INLINE_VISIBILITY
void __copy_assign_alloc(const basic_string& __str)
{__copy_assign_alloc(__str, integral_constant<bool,
__alloc_traits::propagate_on_container_copy_assignment::value>());}
_LIBCPP_INLINE_VISIBILITY
void __copy_assign_alloc(const basic_string& __str, true_type)
{
if (__alloc() == __str.__alloc())
__alloc() = __str.__alloc();
else
{
if (!__str.__is_long())
{
__clear_and_shrink();
__alloc() = __str.__alloc();
}
else
{
allocator_type __a = __str.__alloc();
pointer __p = __alloc_traits::allocate(__a, __str.__get_long_cap());
__clear_and_shrink();
__alloc() = _VSTD::move(__a);
__set_long_pointer(__p);
__set_long_cap(__str.__get_long_cap());
__set_long_size(__str.size());
}
}
}
_LIBCPP_INLINE_VISIBILITY
void __copy_assign_alloc(const basic_string&, false_type) _NOEXCEPT
{}
#ifndef _LIBCPP_CXX03_LANG
_LIBCPP_INLINE_VISIBILITY
void __move_assign(basic_string& __str, false_type)
_NOEXCEPT_(__alloc_traits::is_always_equal::value);
_LIBCPP_INLINE_VISIBILITY
void __move_assign(basic_string& __str, true_type)
#if _LIBCPP_STD_VER > 14
_NOEXCEPT;
#else
_NOEXCEPT_(is_nothrow_move_assignable<allocator_type>::value);
#endif
#endif
_LIBCPP_INLINE_VISIBILITY
void
__move_assign_alloc(basic_string& __str)
_NOEXCEPT_(
!__alloc_traits::propagate_on_container_move_assignment::value ||
is_nothrow_move_assignable<allocator_type>::value)
{__move_assign_alloc(__str, integral_constant<bool,
__alloc_traits::propagate_on_container_move_assignment::value>());}
_LIBCPP_INLINE_VISIBILITY
void __move_assign_alloc(basic_string& __c, true_type)
_NOEXCEPT_(is_nothrow_move_assignable<allocator_type>::value)
{
__alloc() = _VSTD::move(__c.__alloc());
}
_LIBCPP_INLINE_VISIBILITY
void __move_assign_alloc(basic_string&, false_type)
_NOEXCEPT
{}
_LIBCPP_INLINE_VISIBILITY void __invalidate_all_iterators();
_LIBCPP_INLINE_VISIBILITY void __invalidate_iterators_past(size_type);
friend basic_string operator+<>(const basic_string&, const basic_string&);
friend basic_string operator+<>(const value_type*, const basic_string&);
friend basic_string operator+<>(value_type, const basic_string&);
friend basic_string operator+<>(const basic_string&, const value_type*);
friend basic_string operator+<>(const basic_string&, value_type);
};
#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
template<class _InputIterator,
class _CharT = typename iterator_traits<_InputIterator>::value_type,
class _Allocator = allocator<_CharT>,
class = typename enable_if<__is_input_iterator<_InputIterator>::value, void>::type,
class = typename enable_if<__is_allocator<_Allocator>::value, void>::type
>
basic_string(_InputIterator, _InputIterator, _Allocator = _Allocator())
-> basic_string<_CharT, char_traits<_CharT>, _Allocator>;
template<class _CharT,
class _Traits,
class _Allocator = allocator<_CharT>,
class = typename enable_if<__is_allocator<_Allocator>::value, void>::type
>
explicit basic_string(basic_string_view<_CharT, _Traits>, const _Allocator& = _Allocator())
-> basic_string<_CharT, _Traits, _Allocator>;
template<class _CharT,
class _Traits,
class _Allocator = allocator<_CharT>,
class = typename enable_if<__is_allocator<_Allocator>::value, void>::type,
class _Sz = typename allocator_traits<_Allocator>::size_type
>
basic_string(basic_string_view<_CharT, _Traits>, _Sz, _Sz, const _Allocator& = _Allocator())
-> basic_string<_CharT, _Traits, _Allocator>;
#endif
template <class _CharT, class _Traits, class _Allocator>
inline
void
basic_string<_CharT, _Traits, _Allocator>::__invalidate_all_iterators()
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__invalidate_all(this);
#endif // _LIBCPP_DEBUG_LEVEL >= 2
}
template <class _CharT, class _Traits, class _Allocator>
inline
void
basic_string<_CharT, _Traits, _Allocator>::__invalidate_iterators_past(size_type
#if _LIBCPP_DEBUG_LEVEL >= 2
__pos
#endif
)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__c_node* __c = __get_db()->__find_c_and_lock(this);
if (__c)
{
const_pointer __new_last = __get_pointer() + __pos;
for (__i_node** __p = __c->end_; __p != __c->beg_; )
{
--__p;
const_iterator* __i = static_cast<const_iterator*>((*__p)->__i_);
if (__i->base() > __new_last)
{
(*__p)->__c_ = nullptr;
if (--__c->end_ != __p)
memmove(__p, __p+1, (__c->end_ - __p)*sizeof(__i_node*));
}
}
__get_db()->unlock();
}
#endif // _LIBCPP_DEBUG_LEVEL >= 2
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string()
_NOEXCEPT_(is_nothrow_default_constructible<allocator_type>::value)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__zero();
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(const allocator_type& __a)
#if _LIBCPP_STD_VER <= 14
_NOEXCEPT_(is_nothrow_copy_constructible<allocator_type>::value)
#else
_NOEXCEPT
#endif
: __r_(__second_tag(), __a)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
__zero();
}
template <class _CharT, class _Traits, class _Allocator>
void basic_string<_CharT, _Traits, _Allocator>::__init(const value_type* __s,
size_type __sz,
size_type __reserve)
{
if (__reserve > max_size())
this->__throw_length_error();
pointer __p;
if (__reserve < __min_cap)
{
__set_short_size(__sz);
__p = __get_short_pointer();
}
else
{
size_type __cap = __recommend(__reserve);
__p = __alloc_traits::allocate(__alloc(), __cap+1);
__set_long_pointer(__p);
__set_long_cap(__cap+1);
__set_long_size(__sz);
}
traits_type::copy(_VSTD::__to_raw_pointer(__p), __s, __sz);
traits_type::assign(__p[__sz], value_type());
}
template <class _CharT, class _Traits, class _Allocator>
void
basic_string<_CharT, _Traits, _Allocator>::__init(const value_type* __s, size_type __sz)
{
if (__sz > max_size())
this->__throw_length_error();
pointer __p;
if (__sz < __min_cap)
{
__set_short_size(__sz);
__p = __get_short_pointer();
}
else
{
size_type __cap = __recommend(__sz);
__p = __alloc_traits::allocate(__alloc(), __cap+1);
__set_long_pointer(__p);
__set_long_cap(__cap+1);
__set_long_size(__sz);
}
traits_type::copy(_VSTD::__to_raw_pointer(__p), __s, __sz);
traits_type::assign(__p[__sz], value_type());
}
template <class _CharT, class _Traits, class _Allocator>
#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
template <class>
#endif
basic_string<_CharT, _Traits, _Allocator>::basic_string(const _CharT* __s, const _Allocator& __a)
: __r_(__second_tag(), __a)
{
_LIBCPP_ASSERT(__s != nullptr, "basic_string(const char*, allocator) detected nullptr");
__init(__s, traits_type::length(__s));
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(const _CharT* __s, size_type __n)
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "basic_string(const char*, n) detected nullptr");
__init(__s, __n);
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(const _CharT* __s, size_type __n, const _Allocator& __a)
: __r_(__second_tag(), __a)
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "basic_string(const char*, n, allocator) detected nullptr");
__init(__s, __n);
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>::basic_string(const basic_string& __str)
: __r_(__second_tag(), __alloc_traits::select_on_container_copy_construction(__str.__alloc()))
{
if (!__str.__is_long())
__r_.first().__r = __str.__r_.first().__r;
else
__init(_VSTD::__to_raw_pointer(__str.__get_long_pointer()), __str.__get_long_size());
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>::basic_string(
const basic_string& __str, const allocator_type& __a)
: __r_(__second_tag(), __a)
{
if (!__str.__is_long())
__r_.first().__r = __str.__r_.first().__r;
else
__init(_VSTD::__to_raw_pointer(__str.__get_long_pointer()), __str.__get_long_size());
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
#ifndef _LIBCPP_CXX03_LANG
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(basic_string&& __str)
#if _LIBCPP_STD_VER <= 14
_NOEXCEPT_(is_nothrow_move_constructible<allocator_type>::value)
#else
_NOEXCEPT
#endif
: __r_(_VSTD::move(__str.__r_))
{
__str.__zero();
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
if (__is_long())
__get_db()->swap(this, &__str);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(basic_string&& __str, const allocator_type& __a)
: __r_(__second_tag(), __a)
{
if (__str.__is_long() && __a != __str.__alloc()) // copy, not move
__init(_VSTD::__to_raw_pointer(__str.__get_long_pointer()), __str.__get_long_size());
else
{
__r_.first().__r = __str.__r_.first().__r;
__str.__zero();
}
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
if (__is_long())
__get_db()->swap(this, &__str);
#endif
}
#endif // _LIBCPP_CXX03_LANG
template <class _CharT, class _Traits, class _Allocator>
void
basic_string<_CharT, _Traits, _Allocator>::__init(size_type __n, value_type __c)
{
if (__n > max_size())
this->__throw_length_error();
pointer __p;
if (__n < __min_cap)
{
__set_short_size(__n);
__p = __get_short_pointer();
}
else
{
size_type __cap = __recommend(__n);
__p = __alloc_traits::allocate(__alloc(), __cap+1);
__set_long_pointer(__p);
__set_long_cap(__cap+1);
__set_long_size(__n);
}
traits_type::assign(_VSTD::__to_raw_pointer(__p), __n, __c);
traits_type::assign(__p[__n], value_type());
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(size_type __n, _CharT __c)
{
__init(__n, __c);
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
template <class>
#endif
basic_string<_CharT, _Traits, _Allocator>::basic_string(size_type __n, _CharT __c, const _Allocator& __a)
: __r_(__second_tag(), __a)
{
__init(__n, __c);
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>::basic_string(const basic_string& __str,
size_type __pos, size_type __n,
const _Allocator& __a)
: __r_(__second_tag(), __a)
{
size_type __str_sz = __str.size();
if (__pos > __str_sz)
this->__throw_out_of_range();
__init(__str.data() + __pos, _VSTD::min(__n, __str_sz - __pos));
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(const basic_string& __str, size_type __pos,
const _Allocator& __a)
: __r_(__second_tag(), __a)
{
size_type __str_sz = __str.size();
if (__pos > __str_sz)
this->__throw_out_of_range();
__init(__str.data() + __pos, __str_sz - __pos);
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp, class>
basic_string<_CharT, _Traits, _Allocator>::basic_string(
const _Tp& __t, size_type __pos, size_type __n, const allocator_type& __a)
: __r_(__second_tag(), __a)
{
__self_view __sv0 = __t;
__self_view __sv = __sv0.substr(__pos, __n);
__init(__sv.data(), __sv.size());
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp, class>
basic_string<_CharT, _Traits, _Allocator>::basic_string(const _Tp & __t)
{
__self_view __sv = __t;
__init(__sv.data(), __sv.size());
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp, class>
basic_string<_CharT, _Traits, _Allocator>::basic_string(const _Tp & __t, const _Allocator& __a)
: __r_(__second_tag(), __a)
{
__self_view __sv = __t;
__init(__sv.data(), __sv.size());
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
template <class _InputIterator>
typename enable_if
<
__is_exactly_input_iterator<_InputIterator>::value,
void
>::type
basic_string<_CharT, _Traits, _Allocator>::__init(_InputIterator __first, _InputIterator __last)
{
__zero();
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
for (; __first != __last; ++__first)
push_back(*__first);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
if (__is_long())
__alloc_traits::deallocate(__alloc(), __get_long_pointer(), __get_long_cap());
throw;
}
#endif // _LIBCPP_NO_EXCEPTIONS
}
template <class _CharT, class _Traits, class _Allocator>
template <class _ForwardIterator>
typename enable_if
<
__is_forward_iterator<_ForwardIterator>::value,
void
>::type
basic_string<_CharT, _Traits, _Allocator>::__init(_ForwardIterator __first, _ForwardIterator __last)
{
size_type __sz = static_cast<size_type>(_VSTD::distance(__first, __last));
if (__sz > max_size())
this->__throw_length_error();
pointer __p;
if (__sz < __min_cap)
{
__set_short_size(__sz);
__p = __get_short_pointer();
}
else
{
size_type __cap = __recommend(__sz);
__p = __alloc_traits::allocate(__alloc(), __cap+1);
__set_long_pointer(__p);
__set_long_cap(__cap+1);
__set_long_size(__sz);
}
for (; __first != __last; ++__first, (void) ++__p)
traits_type::assign(*__p, *__first);
traits_type::assign(*__p, value_type());
}
template <class _CharT, class _Traits, class _Allocator>
template<class _InputIterator, class>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(_InputIterator __first, _InputIterator __last)
{
__init(__first, __last);
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
template<class _InputIterator, class>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(_InputIterator __first, _InputIterator __last,
const allocator_type& __a)
: __r_(__second_tag(), __a)
{
__init(__first, __last);
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
#ifndef _LIBCPP_CXX03_LANG
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(
initializer_list<_CharT> __il)
{
__init(__il.begin(), __il.end());
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>::basic_string(
initializer_list<_CharT> __il, const _Allocator& __a)
: __r_(__second_tag(), __a)
{
__init(__il.begin(), __il.end());
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__insert_c(this);
#endif
}
#endif // _LIBCPP_CXX03_LANG
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>::~basic_string()
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__erase_c(this);
#endif
if (__is_long())
__alloc_traits::deallocate(__alloc(), __get_long_pointer(), __get_long_cap());
}
template <class _CharT, class _Traits, class _Allocator>
void
basic_string<_CharT, _Traits, _Allocator>::__grow_by_and_replace
(size_type __old_cap, size_type __delta_cap, size_type __old_sz,
size_type __n_copy, size_type __n_del, size_type __n_add, const value_type* __p_new_stuff)
{
size_type __ms = max_size();
if (__delta_cap > __ms - __old_cap - 1)
this->__throw_length_error();
pointer __old_p = __get_pointer();
size_type __cap = __old_cap < __ms / 2 - __alignment ?
__recommend(_VSTD::max(__old_cap + __delta_cap, 2 * __old_cap)) :
__ms - 1;
pointer __p = __alloc_traits::allocate(__alloc(), __cap+1);
__invalidate_all_iterators();
if (__n_copy != 0)
traits_type::copy(_VSTD::__to_raw_pointer(__p),
_VSTD::__to_raw_pointer(__old_p), __n_copy);
if (__n_add != 0)
traits_type::copy(_VSTD::__to_raw_pointer(__p) + __n_copy, __p_new_stuff, __n_add);
size_type __sec_cp_sz = __old_sz - __n_del - __n_copy;
if (__sec_cp_sz != 0)
traits_type::copy(_VSTD::__to_raw_pointer(__p) + __n_copy + __n_add,
_VSTD::__to_raw_pointer(__old_p) + __n_copy + __n_del, __sec_cp_sz);
if (__old_cap+1 != __min_cap)
__alloc_traits::deallocate(__alloc(), __old_p, __old_cap+1);
__set_long_pointer(__p);
__set_long_cap(__cap+1);
__old_sz = __n_copy + __n_add + __sec_cp_sz;
__set_long_size(__old_sz);
traits_type::assign(__p[__old_sz], value_type());
}
template <class _CharT, class _Traits, class _Allocator>
void
basic_string<_CharT, _Traits, _Allocator>::__grow_by(size_type __old_cap, size_type __delta_cap, size_type __old_sz,
size_type __n_copy, size_type __n_del, size_type __n_add)
{
size_type __ms = max_size();
if (__delta_cap > __ms - __old_cap)
this->__throw_length_error();
pointer __old_p = __get_pointer();
size_type __cap = __old_cap < __ms / 2 - __alignment ?
__recommend(_VSTD::max(__old_cap + __delta_cap, 2 * __old_cap)) :
__ms - 1;
pointer __p = __alloc_traits::allocate(__alloc(), __cap+1);
__invalidate_all_iterators();
if (__n_copy != 0)
traits_type::copy(_VSTD::__to_raw_pointer(__p),
_VSTD::__to_raw_pointer(__old_p), __n_copy);
size_type __sec_cp_sz = __old_sz - __n_del - __n_copy;
if (__sec_cp_sz != 0)
traits_type::copy(_VSTD::__to_raw_pointer(__p) + __n_copy + __n_add,
_VSTD::__to_raw_pointer(__old_p) + __n_copy + __n_del,
__sec_cp_sz);
if (__old_cap+1 != __min_cap)
__alloc_traits::deallocate(__alloc(), __old_p, __old_cap+1);
__set_long_pointer(__p);
__set_long_cap(__cap+1);
}
// assign
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::assign(const value_type* __s, size_type __n)
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string::assign received nullptr");
size_type __cap = capacity();
if (__cap >= __n)
{
value_type* __p = _VSTD::__to_raw_pointer(__get_pointer());
traits_type::move(__p, __s, __n);
traits_type::assign(__p[__n], value_type());
__set_size(__n);
__invalidate_iterators_past(__n);
}
else
{
size_type __sz = size();
__grow_by_and_replace(__cap, __n - __cap, __sz, 0, __sz, __n, __s);
}
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::assign(size_type __n, value_type __c)
{
size_type __cap = capacity();
if (__cap < __n)
{
size_type __sz = size();
__grow_by(__cap, __n - __cap, __sz, 0, __sz);
}
else
__invalidate_iterators_past(__n);
value_type* __p = _VSTD::__to_raw_pointer(__get_pointer());
traits_type::assign(__p, __n, __c);
traits_type::assign(__p[__n], value_type());
__set_size(__n);
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::operator=(value_type __c)
{
pointer __p;
if (__is_long())
{
__p = __get_long_pointer();
__set_long_size(1);
}
else
{
__p = __get_short_pointer();
__set_short_size(1);
}
traits_type::assign(*__p, __c);
traits_type::assign(*++__p, value_type());
__invalidate_iterators_past(1);
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::operator=(const basic_string& __str)
{
if (this != &__str)
{
__copy_assign_alloc(__str);
assign(__str.data(), __str.size());
}
return *this;
}
#ifndef _LIBCPP_CXX03_LANG
template <class _CharT, class _Traits, class _Allocator>
inline
void
basic_string<_CharT, _Traits, _Allocator>::__move_assign(basic_string& __str, false_type)
_NOEXCEPT_(__alloc_traits::is_always_equal::value)
{
if (__alloc() != __str.__alloc())
assign(__str);
else
__move_assign(__str, true_type());
}
template <class _CharT, class _Traits, class _Allocator>
inline
void
basic_string<_CharT, _Traits, _Allocator>::__move_assign(basic_string& __str, true_type)
#if _LIBCPP_STD_VER > 14
_NOEXCEPT
#else
_NOEXCEPT_(is_nothrow_move_assignable<allocator_type>::value)
#endif
{
__clear_and_shrink();
__r_.first() = __str.__r_.first();
__move_assign_alloc(__str);
__str.__zero();
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::operator=(basic_string&& __str)
_NOEXCEPT_((__noexcept_move_assign_container<_Allocator, __alloc_traits>::value))
{
__move_assign(__str, integral_constant<bool,
__alloc_traits::propagate_on_container_move_assignment::value>());
return *this;
}
#endif
template <class _CharT, class _Traits, class _Allocator>
template<class _InputIterator>
typename enable_if
<
__is_exactly_input_iterator <_InputIterator>::value
|| !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
basic_string<_CharT, _Traits, _Allocator>&
>::type
basic_string<_CharT, _Traits, _Allocator>::assign(_InputIterator __first, _InputIterator __last)
{
const basic_string __temp(__first, __last, __alloc());
assign(__temp.data(), __temp.size());
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
template<class _ForwardIterator>
typename enable_if
<
__is_forward_iterator<_ForwardIterator>::value
&& __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
basic_string<_CharT, _Traits, _Allocator>&
>::type
basic_string<_CharT, _Traits, _Allocator>::assign(_ForwardIterator __first, _ForwardIterator __last)
{
size_type __n = static_cast<size_type>(_VSTD::distance(__first, __last));
size_type __cap = capacity();
if (__cap < __n)
{
size_type __sz = size();
__grow_by(__cap, __n - __cap, __sz, 0, __sz);
}
else
__invalidate_iterators_past(__n);
pointer __p = __get_pointer();
for (; __first != __last; ++__first, ++__p)
traits_type::assign(*__p, *__first);
traits_type::assign(*__p, value_type());
__set_size(__n);
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::assign(const basic_string& __str, size_type __pos, size_type __n)
{
size_type __sz = __str.size();
if (__pos > __sz)
this->__throw_out_of_range();
return assign(__str.data() + __pos, _VSTD::min(__n, __sz - __pos));
}
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string<_CharT, _Traits, _Allocator>&
>::type
basic_string<_CharT, _Traits, _Allocator>::assign(const _Tp & __t, size_type __pos, size_type __n)
{
__self_view __sv = __t;
size_type __sz = __sv.size();
if (__pos > __sz)
this->__throw_out_of_range();
return assign(__sv.data() + __pos, _VSTD::min(__n, __sz - __pos));
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::assign(const value_type* __s)
{
_LIBCPP_ASSERT(__s != nullptr, "string::assign received nullptr");
return assign(__s, traits_type::length(__s));
}
// append
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::append(const value_type* __s, size_type __n)
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string::append received nullptr");
size_type __cap = capacity();
size_type __sz = size();
if (__cap - __sz >= __n)
{
if (__n)
{
value_type* __p = _VSTD::__to_raw_pointer(__get_pointer());
traits_type::copy(__p + __sz, __s, __n);
__sz += __n;
__set_size(__sz);
traits_type::assign(__p[__sz], value_type());
}
}
else
__grow_by_and_replace(__cap, __sz + __n - __cap, __sz, __sz, 0, __n, __s);
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::append(size_type __n, value_type __c)
{
if (__n)
{
size_type __cap = capacity();
size_type __sz = size();
if (__cap - __sz < __n)
__grow_by(__cap, __sz + __n - __cap, __sz, __sz, 0);
pointer __p = __get_pointer();
traits_type::assign(_VSTD::__to_raw_pointer(__p) + __sz, __n, __c);
__sz += __n;
__set_size(__sz);
traits_type::assign(__p[__sz], value_type());
}
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
inline void
basic_string<_CharT, _Traits, _Allocator>::__append_default_init(size_type __n)
{
if (__n)
{
size_type __cap = capacity();
size_type __sz = size();
if (__cap - __sz < __n)
__grow_by(__cap, __sz + __n - __cap, __sz, __sz, 0);
pointer __p = __get_pointer();
__sz += __n;
__set_size(__sz);
traits_type::assign(__p[__sz], value_type());
}
}
template <class _CharT, class _Traits, class _Allocator>
void
basic_string<_CharT, _Traits, _Allocator>::push_back(value_type __c)
{
bool __is_short = !__is_long();
size_type __cap;
size_type __sz;
if (__is_short)
{
__cap = __min_cap - 1;
__sz = __get_short_size();
}
else
{
__cap = __get_long_cap() - 1;
__sz = __get_long_size();
}
if (__sz == __cap)
{
__grow_by(__cap, 1, __sz, __sz, 0);
__is_short = !__is_long();
}
pointer __p;
if (__is_short)
{
__p = __get_short_pointer() + __sz;
__set_short_size(__sz+1);
}
else
{
__p = __get_long_pointer() + __sz;
__set_long_size(__sz+1);
}
traits_type::assign(*__p, __c);
traits_type::assign(*++__p, value_type());
}
template <class _Tp>
bool __ptr_in_range (const _Tp* __p, const _Tp* __first, const _Tp* __last)
{
return __first <= __p && __p < __last;
}
template <class _Tp1, class _Tp2>
bool __ptr_in_range (const _Tp1*, const _Tp2*, const _Tp2*)
{
return false;
}
template <class _CharT, class _Traits, class _Allocator>
template<class _ForwardIterator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::__append_forward_unsafe(
_ForwardIterator __first, _ForwardIterator __last)
{
static_assert(__is_forward_iterator<_ForwardIterator>::value,
"function requires a ForwardIterator");
size_type __sz = size();
size_type __cap = capacity();
size_type __n = static_cast<size_type>(_VSTD::distance(__first, __last));
if (__n)
{
typedef typename iterator_traits<_ForwardIterator>::reference _CharRef;
_CharRef __tmp_ref = *__first;
if (__ptr_in_range(_VSTD::addressof(__tmp_ref), data(), data() + size()))
{
const basic_string __temp (__first, __last, __alloc());
append(__temp.data(), __temp.size());
}
else
{
if (__cap - __sz < __n)
__grow_by(__cap, __sz + __n - __cap, __sz, __sz, 0);
pointer __p = __get_pointer() + __sz;
for (; __first != __last; ++__p, ++__first)
traits_type::assign(*__p, *__first);
traits_type::assign(*__p, value_type());
__set_size(__sz + __n);
}
}
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::append(const basic_string& __str)
{
return append(__str.data(), __str.size());
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::append(const basic_string& __str, size_type __pos, size_type __n)
{
size_type __sz = __str.size();
if (__pos > __sz)
this->__throw_out_of_range();
return append(__str.data() + __pos, _VSTD::min(__n, __sz - __pos));
}
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string<_CharT, _Traits, _Allocator>&
>::type
basic_string<_CharT, _Traits, _Allocator>::append(const _Tp & __t, size_type __pos, size_type __n)
{
__self_view __sv = __t;
size_type __sz = __sv.size();
if (__pos > __sz)
this->__throw_out_of_range();
return append(__sv.data() + __pos, _VSTD::min(__n, __sz - __pos));
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::append(const value_type* __s)
{
_LIBCPP_ASSERT(__s != nullptr, "string::append received nullptr");
return append(__s, traits_type::length(__s));
}
// insert
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::insert(size_type __pos, const value_type* __s, size_type __n)
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string::insert received nullptr");
size_type __sz = size();
if (__pos > __sz)
this->__throw_out_of_range();
size_type __cap = capacity();
if (__cap - __sz >= __n)
{
if (__n)
{
value_type* __p = _VSTD::__to_raw_pointer(__get_pointer());
size_type __n_move = __sz - __pos;
if (__n_move != 0)
{
if (__p + __pos <= __s && __s < __p + __sz)
__s += __n;
traits_type::move(__p + __pos + __n, __p + __pos, __n_move);
}
traits_type::move(__p + __pos, __s, __n);
__sz += __n;
__set_size(__sz);
traits_type::assign(__p[__sz], value_type());
}
}
else
__grow_by_and_replace(__cap, __sz + __n - __cap, __sz, __pos, 0, __n, __s);
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::insert(size_type __pos, size_type __n, value_type __c)
{
size_type __sz = size();
if (__pos > __sz)
this->__throw_out_of_range();
if (__n)
{
size_type __cap = capacity();
value_type* __p;
if (__cap - __sz >= __n)
{
__p = _VSTD::__to_raw_pointer(__get_pointer());
size_type __n_move = __sz - __pos;
if (__n_move != 0)
traits_type::move(__p + __pos + __n, __p + __pos, __n_move);
}
else
{
__grow_by(__cap, __sz + __n - __cap, __sz, __pos, 0, __n);
__p = _VSTD::__to_raw_pointer(__get_long_pointer());
}
traits_type::assign(__p + __pos, __n, __c);
__sz += __n;
__set_size(__sz);
traits_type::assign(__p[__sz], value_type());
}
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
template<class _InputIterator>
typename enable_if
<
__is_exactly_input_iterator<_InputIterator>::value
|| !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
typename basic_string<_CharT, _Traits, _Allocator>::iterator
>::type
basic_string<_CharT, _Traits, _Allocator>::insert(const_iterator __pos, _InputIterator __first, _InputIterator __last)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__pos) == this,
"string::insert(iterator, range) called with an iterator not"
" referring to this string");
#endif
const basic_string __temp(__first, __last, __alloc());
return insert(__pos, __temp.data(), __temp.data() + __temp.size());
}
template <class _CharT, class _Traits, class _Allocator>
template<class _ForwardIterator>
typename enable_if
<
__is_forward_iterator<_ForwardIterator>::value
&& __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
typename basic_string<_CharT, _Traits, _Allocator>::iterator
>::type
basic_string<_CharT, _Traits, _Allocator>::insert(const_iterator __pos, _ForwardIterator __first, _ForwardIterator __last)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__pos) == this,
"string::insert(iterator, range) called with an iterator not"
" referring to this string");
#endif
size_type __ip = static_cast<size_type>(__pos - begin());
size_type __n = static_cast<size_type>(_VSTD::distance(__first, __last));
if (__n)
{
typedef typename iterator_traits<_ForwardIterator>::reference _CharRef;
_CharRef __tmp_char = *__first;
if (__ptr_in_range(_VSTD::addressof(__tmp_char), data(), data() + size()))
{
const basic_string __temp(__first, __last, __alloc());
return insert(__pos, __temp.data(), __temp.data() + __temp.size());
}
size_type __sz = size();
size_type __cap = capacity();
value_type* __p;
if (__cap - __sz >= __n)
{
__p = _VSTD::__to_raw_pointer(__get_pointer());
size_type __n_move = __sz - __ip;
if (__n_move != 0)
traits_type::move(__p + __ip + __n, __p + __ip, __n_move);
}
else
{
__grow_by(__cap, __sz + __n - __cap, __sz, __ip, 0, __n);
__p = _VSTD::__to_raw_pointer(__get_long_pointer());
}
__sz += __n;
__set_size(__sz);
traits_type::assign(__p[__sz], value_type());
for (__p += __ip; __first != __last; ++__p, ++__first)
traits_type::assign(*__p, *__first);
}
return begin() + __ip;
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::insert(size_type __pos1, const basic_string& __str)
{
return insert(__pos1, __str.data(), __str.size());
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::insert(size_type __pos1, const basic_string& __str,
size_type __pos2, size_type __n)
{
size_type __str_sz = __str.size();
if (__pos2 > __str_sz)
this->__throw_out_of_range();
return insert(__pos1, __str.data() + __pos2, _VSTD::min(__n, __str_sz - __pos2));
}
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string<_CharT, _Traits, _Allocator>&
>::type
basic_string<_CharT, _Traits, _Allocator>::insert(size_type __pos1, const _Tp& __t,
size_type __pos2, size_type __n)
{
__self_view __sv = __t;
size_type __str_sz = __sv.size();
if (__pos2 > __str_sz)
this->__throw_out_of_range();
return insert(__pos1, __sv.data() + __pos2, _VSTD::min(__n, __str_sz - __pos2));
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::insert(size_type __pos, const value_type* __s)
{
_LIBCPP_ASSERT(__s != nullptr, "string::insert received nullptr");
return insert(__pos, __s, traits_type::length(__s));
}
template <class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::iterator
basic_string<_CharT, _Traits, _Allocator>::insert(const_iterator __pos, value_type __c)
{
size_type __ip = static_cast<size_type>(__pos - begin());
size_type __sz = size();
size_type __cap = capacity();
value_type* __p;
if (__cap == __sz)
{
__grow_by(__cap, 1, __sz, __ip, 0, 1);
__p = _VSTD::__to_raw_pointer(__get_long_pointer());
}
else
{
__p = _VSTD::__to_raw_pointer(__get_pointer());
size_type __n_move = __sz - __ip;
if (__n_move != 0)
traits_type::move(__p + __ip + 1, __p + __ip, __n_move);
}
traits_type::assign(__p[__ip], __c);
traits_type::assign(__p[++__sz], value_type());
__set_size(__sz);
return begin() + static_cast<difference_type>(__ip);
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::iterator
basic_string<_CharT, _Traits, _Allocator>::insert(const_iterator __pos, size_type __n, value_type __c)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__pos) == this,
"string::insert(iterator, n, value) called with an iterator not"
" referring to this string");
#endif
difference_type __p = __pos - begin();
insert(static_cast<size_type>(__p), __n, __c);
return begin() + __p;
}
// replace
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::replace(size_type __pos, size_type __n1, const value_type* __s, size_type __n2)
_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
{
_LIBCPP_ASSERT(__n2 == 0 || __s != nullptr, "string::replace received nullptr");
size_type __sz = size();
if (__pos > __sz)
this->__throw_out_of_range();
__n1 = _VSTD::min(__n1, __sz - __pos);
size_type __cap = capacity();
if (__cap - __sz + __n1 >= __n2)
{
value_type* __p = _VSTD::__to_raw_pointer(__get_pointer());
if (__n1 != __n2)
{
size_type __n_move = __sz - __pos - __n1;
if (__n_move != 0)
{
if (__n1 > __n2)
{
traits_type::move(__p + __pos, __s, __n2);
traits_type::move(__p + __pos + __n2, __p + __pos + __n1, __n_move);
goto __finish;
}
if (__p + __pos < __s && __s < __p + __sz)
{
if (__p + __pos + __n1 <= __s)
__s += __n2 - __n1;
else // __p + __pos < __s < __p + __pos + __n1
{
traits_type::move(__p + __pos, __s, __n1);
__pos += __n1;
__s += __n2;
__n2 -= __n1;
__n1 = 0;
}
}
traits_type::move(__p + __pos + __n2, __p + __pos + __n1, __n_move);
}
}
traits_type::move(__p + __pos, __s, __n2);
__finish:
// __sz += __n2 - __n1; in this and the below function below can cause unsigned integer overflow,
// but this is a safe operation, so we disable the check.
__sz += __n2 - __n1;
__set_size(__sz);
__invalidate_iterators_past(__sz);
traits_type::assign(__p[__sz], value_type());
}
else
__grow_by_and_replace(__cap, __sz - __n1 + __n2 - __cap, __sz, __pos, __n1, __n2, __s);
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::replace(size_type __pos, size_type __n1, size_type __n2, value_type __c)
_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
{
size_type __sz = size();
if (__pos > __sz)
this->__throw_out_of_range();
__n1 = _VSTD::min(__n1, __sz - __pos);
size_type __cap = capacity();
value_type* __p;
if (__cap - __sz + __n1 >= __n2)
{
__p = _VSTD::__to_raw_pointer(__get_pointer());
if (__n1 != __n2)
{
size_type __n_move = __sz - __pos - __n1;
if (__n_move != 0)
traits_type::move(__p + __pos + __n2, __p + __pos + __n1, __n_move);
}
}
else
{
__grow_by(__cap, __sz - __n1 + __n2 - __cap, __sz, __pos, __n1, __n2);
__p = _VSTD::__to_raw_pointer(__get_long_pointer());
}
traits_type::assign(__p + __pos, __n2, __c);
__sz += __n2 - __n1;
__set_size(__sz);
__invalidate_iterators_past(__sz);
traits_type::assign(__p[__sz], value_type());
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
template<class _InputIterator>
typename enable_if
<
__is_input_iterator<_InputIterator>::value,
basic_string<_CharT, _Traits, _Allocator>&
>::type
basic_string<_CharT, _Traits, _Allocator>::replace(const_iterator __i1, const_iterator __i2,
_InputIterator __j1, _InputIterator __j2)
{
const basic_string __temp(__j1, __j2, __alloc());
return this->replace(__i1, __i2, __temp);
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::replace(size_type __pos1, size_type __n1, const basic_string& __str)
{
return replace(__pos1, __n1, __str.data(), __str.size());
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::replace(size_type __pos1, size_type __n1, const basic_string& __str,
size_type __pos2, size_type __n2)
{
size_type __str_sz = __str.size();
if (__pos2 > __str_sz)
this->__throw_out_of_range();
return replace(__pos1, __n1, __str.data() + __pos2, _VSTD::min(__n2, __str_sz - __pos2));
}
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
basic_string<_CharT, _Traits, _Allocator>&
>::type
basic_string<_CharT, _Traits, _Allocator>::replace(size_type __pos1, size_type __n1, const _Tp& __t,
size_type __pos2, size_type __n2)
{
__self_view __sv = __t;
size_type __str_sz = __sv.size();
if (__pos2 > __str_sz)
this->__throw_out_of_range();
return replace(__pos1, __n1, __sv.data() + __pos2, _VSTD::min(__n2, __str_sz - __pos2));
}
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::replace(size_type __pos, size_type __n1, const value_type* __s)
{
_LIBCPP_ASSERT(__s != nullptr, "string::replace received nullptr");
return replace(__pos, __n1, __s, traits_type::length(__s));
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::replace(const_iterator __i1, const_iterator __i2, const basic_string& __str)
{
return replace(static_cast<size_type>(__i1 - begin()), static_cast<size_type>(__i2 - __i1),
__str.data(), __str.size());
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::replace(const_iterator __i1, const_iterator __i2, const value_type* __s, size_type __n)
{
return replace(static_cast<size_type>(__i1 - begin()), static_cast<size_type>(__i2 - __i1), __s, __n);
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::replace(const_iterator __i1, const_iterator __i2, const value_type* __s)
{
return replace(static_cast<size_type>(__i1 - begin()), static_cast<size_type>(__i2 - __i1), __s);
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::replace(const_iterator __i1, const_iterator __i2, size_type __n, value_type __c)
{
return replace(static_cast<size_type>(__i1 - begin()), static_cast<size_type>(__i2 - __i1), __n, __c);
}
// erase
template <class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>&
basic_string<_CharT, _Traits, _Allocator>::erase(size_type __pos, size_type __n)
{
size_type __sz = size();
if (__pos > __sz)
this->__throw_out_of_range();
if (__n)
{
value_type* __p = _VSTD::__to_raw_pointer(__get_pointer());
__n = _VSTD::min(__n, __sz - __pos);
size_type __n_move = __sz - __pos - __n;
if (__n_move != 0)
traits_type::move(__p + __pos, __p + __pos + __n, __n_move);
__sz -= __n;
__set_size(__sz);
__invalidate_iterators_past(__sz);
traits_type::assign(__p[__sz], value_type());
}
return *this;
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::iterator
basic_string<_CharT, _Traits, _Allocator>::erase(const_iterator __pos)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__pos) == this,
"string::erase(iterator) called with an iterator not"
" referring to this string");
#endif
_LIBCPP_ASSERT(__pos != end(),
"string::erase(iterator) called with a non-dereferenceable iterator");
iterator __b = begin();
size_type __r = static_cast<size_type>(__pos - __b);
erase(__r, 1);
return __b + static_cast<difference_type>(__r);
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::iterator
basic_string<_CharT, _Traits, _Allocator>::erase(const_iterator __first, const_iterator __last)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__first) == this,
"string::erase(iterator, iterator) called with an iterator not"
" referring to this string");
#endif
_LIBCPP_ASSERT(__first <= __last, "string::erase(first, last) called with invalid range");
iterator __b = begin();
size_type __r = static_cast<size_type>(__first - __b);
erase(__r, static_cast<size_type>(__last - __first));
return __b + static_cast<difference_type>(__r);
}
template <class _CharT, class _Traits, class _Allocator>
inline
void
basic_string<_CharT, _Traits, _Allocator>::pop_back()
{
_LIBCPP_ASSERT(!empty(), "string::pop_back(): string is already empty");
size_type __sz;
if (__is_long())
{
__sz = __get_long_size() - 1;
__set_long_size(__sz);
traits_type::assign(*(__get_long_pointer() + __sz), value_type());
}
else
{
__sz = __get_short_size() - 1;
__set_short_size(__sz);
traits_type::assign(*(__get_short_pointer() + __sz), value_type());
}
__invalidate_iterators_past(__sz);
}
template <class _CharT, class _Traits, class _Allocator>
inline
void
basic_string<_CharT, _Traits, _Allocator>::clear() _NOEXCEPT
{
__invalidate_all_iterators();
if (__is_long())
{
traits_type::assign(*__get_long_pointer(), value_type());
__set_long_size(0);
}
else
{
traits_type::assign(*__get_short_pointer(), value_type());
__set_short_size(0);
}
}
template <class _CharT, class _Traits, class _Allocator>
inline
void
basic_string<_CharT, _Traits, _Allocator>::__erase_to_end(size_type __pos)
{
if (__is_long())
{
traits_type::assign(*(__get_long_pointer() + __pos), value_type());
__set_long_size(__pos);
}
else
{
traits_type::assign(*(__get_short_pointer() + __pos), value_type());
__set_short_size(__pos);
}
__invalidate_iterators_past(__pos);
}
template <class _CharT, class _Traits, class _Allocator>
void
basic_string<_CharT, _Traits, _Allocator>::resize(size_type __n, value_type __c)
{
size_type __sz = size();
if (__n > __sz)
append(__n - __sz, __c);
else
__erase_to_end(__n);
}
template <class _CharT, class _Traits, class _Allocator>
inline void
basic_string<_CharT, _Traits, _Allocator>::__resize_default_init(size_type __n)
{
size_type __sz = size();
if (__n > __sz) {
__append_default_init(__n - __sz);
} else
__erase_to_end(__n);
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::max_size() const _NOEXCEPT
{
size_type __m = __alloc_traits::max_size(__alloc());
#ifdef _LIBCPP_BIG_ENDIAN
return (__m <= ~__long_mask ? __m : __m/2) - __alignment;
#else
return __m - __alignment;
#endif
}
template <class _CharT, class _Traits, class _Allocator>
void
basic_string<_CharT, _Traits, _Allocator>::reserve(size_type __res_arg)
{
if (__res_arg > max_size())
this->__throw_length_error();
size_type __cap = capacity();
size_type __sz = size();
__res_arg = _VSTD::max(__res_arg, __sz);
__res_arg = __recommend(__res_arg);
if (__res_arg != __cap)
{
pointer __new_data, __p;
bool __was_long, __now_long;
if (__res_arg == __min_cap - 1)
{
__was_long = true;
__now_long = false;
__new_data = __get_short_pointer();
__p = __get_long_pointer();
}
else
{
if (__res_arg > __cap)
__new_data = __alloc_traits::allocate(__alloc(), __res_arg+1);
else
{
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
__new_data = __alloc_traits::allocate(__alloc(), __res_arg+1);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
return;
}
#else // _LIBCPP_NO_EXCEPTIONS
if (__new_data == nullptr)
return;
#endif // _LIBCPP_NO_EXCEPTIONS
}
__now_long = true;
__was_long = __is_long();
__p = __get_pointer();
}
traits_type::copy(_VSTD::__to_raw_pointer(__new_data),
_VSTD::__to_raw_pointer(__p), size()+1);
if (__was_long)
__alloc_traits::deallocate(__alloc(), __p, __cap+1);
if (__now_long)
{
__set_long_cap(__res_arg+1);
__set_long_size(__sz);
__set_long_pointer(__new_data);
}
else
__set_short_size(__sz);
__invalidate_all_iterators();
}
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::const_reference
basic_string<_CharT, _Traits, _Allocator>::operator[](size_type __pos) const _NOEXCEPT
{
_LIBCPP_ASSERT(__pos <= size(), "string index out of bounds");
return *(data() + __pos);
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::reference
basic_string<_CharT, _Traits, _Allocator>::operator[](size_type __pos) _NOEXCEPT
{
_LIBCPP_ASSERT(__pos <= size(), "string index out of bounds");
return *(__get_pointer() + __pos);
}
template <class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::const_reference
basic_string<_CharT, _Traits, _Allocator>::at(size_type __n) const
{
if (__n >= size())
this->__throw_out_of_range();
return (*this)[__n];
}
template <class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::reference
basic_string<_CharT, _Traits, _Allocator>::at(size_type __n)
{
if (__n >= size())
this->__throw_out_of_range();
return (*this)[__n];
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::reference
basic_string<_CharT, _Traits, _Allocator>::front() _NOEXCEPT
{
_LIBCPP_ASSERT(!empty(), "string::front(): string is empty");
return *__get_pointer();
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::const_reference
basic_string<_CharT, _Traits, _Allocator>::front() const _NOEXCEPT
{
_LIBCPP_ASSERT(!empty(), "string::front(): string is empty");
return *data();
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::reference
basic_string<_CharT, _Traits, _Allocator>::back() _NOEXCEPT
{
_LIBCPP_ASSERT(!empty(), "string::back(): string is empty");
return *(__get_pointer() + size() - 1);
}
template <class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::const_reference
basic_string<_CharT, _Traits, _Allocator>::back() const _NOEXCEPT
{
_LIBCPP_ASSERT(!empty(), "string::back(): string is empty");
return *(data() + size() - 1);
}
template <class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::copy(value_type* __s, size_type __n, size_type __pos) const
{
size_type __sz = size();
if (__pos > __sz)
this->__throw_out_of_range();
size_type __rlen = _VSTD::min(__n, __sz - __pos);
traits_type::copy(__s, data() + __pos, __rlen);
return __rlen;
}
template <class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>
basic_string<_CharT, _Traits, _Allocator>::substr(size_type __pos, size_type __n) const
{
return basic_string(*this, __pos, __n, __alloc());
}
template <class _CharT, class _Traits, class _Allocator>
inline
void
basic_string<_CharT, _Traits, _Allocator>::swap(basic_string& __str)
#if _LIBCPP_STD_VER >= 14
_NOEXCEPT
#else
_NOEXCEPT_(!__alloc_traits::propagate_on_container_swap::value ||
__is_nothrow_swappable<allocator_type>::value)
#endif
{
#if _LIBCPP_DEBUG_LEVEL >= 2
if (!__is_long())
__get_db()->__invalidate_all(this);
if (!__str.__is_long())
__get_db()->__invalidate_all(&__str);
__get_db()->swap(this, &__str);
#endif
_LIBCPP_ASSERT(
__alloc_traits::propagate_on_container_swap::value ||
__alloc_traits::is_always_equal::value ||
__alloc() == __str.__alloc(), "swapping non-equal allocators");
_VSTD::swap(__r_.first(), __str.__r_.first());
__swap_allocator(__alloc(), __str.__alloc());
}
// find
template <class _Traits>
struct _LIBCPP_HIDDEN __traits_eq
{
typedef typename _Traits::char_type char_type;
_LIBCPP_INLINE_VISIBILITY
bool operator()(const char_type& __x, const char_type& __y) _NOEXCEPT
{return _Traits::eq(__x, __y);}
};
template<class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find(const value_type* __s,
size_type __pos,
size_type __n) const _NOEXCEPT
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string::find(): received nullptr");
return __str_find<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, __n);
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find(const basic_string& __str,
size_type __pos) const _NOEXCEPT
{
return __str_find<value_type, size_type, traits_type, npos>
(data(), size(), __str.data(), __pos, __str.size());
}
template<class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
typename basic_string<_CharT, _Traits, _Allocator>::size_type
>::type
basic_string<_CharT, _Traits, _Allocator>::find(const _Tp &__t,
size_type __pos) const
{
__self_view __sv = __t;
return __str_find<value_type, size_type, traits_type, npos>
(data(), size(), __sv.data(), __pos, __sv.size());
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find(const value_type* __s,
size_type __pos) const _NOEXCEPT
{
_LIBCPP_ASSERT(__s != nullptr, "string::find(): received nullptr");
return __str_find<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, traits_type::length(__s));
}
template<class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find(value_type __c,
size_type __pos) const _NOEXCEPT
{
return __str_find<value_type, size_type, traits_type, npos>
(data(), size(), __c, __pos);
}
// rfind
template<class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::rfind(const value_type* __s,
size_type __pos,
size_type __n) const _NOEXCEPT
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string::rfind(): received nullptr");
return __str_rfind<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, __n);
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::rfind(const basic_string& __str,
size_type __pos) const _NOEXCEPT
{
return __str_rfind<value_type, size_type, traits_type, npos>
(data(), size(), __str.data(), __pos, __str.size());
}
template<class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
typename basic_string<_CharT, _Traits, _Allocator>::size_type
>::type
basic_string<_CharT, _Traits, _Allocator>::rfind(const _Tp& __t,
size_type __pos) const
{
__self_view __sv = __t;
return __str_rfind<value_type, size_type, traits_type, npos>
(data(), size(), __sv.data(), __pos, __sv.size());
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::rfind(const value_type* __s,
size_type __pos) const _NOEXCEPT
{
_LIBCPP_ASSERT(__s != nullptr, "string::rfind(): received nullptr");
return __str_rfind<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, traits_type::length(__s));
}
template<class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::rfind(value_type __c,
size_type __pos) const _NOEXCEPT
{
return __str_rfind<value_type, size_type, traits_type, npos>
(data(), size(), __c, __pos);
}
// find_first_of
template<class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_first_of(const value_type* __s,
size_type __pos,
size_type __n) const _NOEXCEPT
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string::find_first_of(): received nullptr");
return __str_find_first_of<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, __n);
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_first_of(const basic_string& __str,
size_type __pos) const _NOEXCEPT
{
return __str_find_first_of<value_type, size_type, traits_type, npos>
(data(), size(), __str.data(), __pos, __str.size());
}
template<class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
typename basic_string<_CharT, _Traits, _Allocator>::size_type
>::type
basic_string<_CharT, _Traits, _Allocator>::find_first_of(const _Tp& __t,
size_type __pos) const
{
__self_view __sv = __t;
return __str_find_first_of<value_type, size_type, traits_type, npos>
(data(), size(), __sv.data(), __pos, __sv.size());
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_first_of(const value_type* __s,
size_type __pos) const _NOEXCEPT
{
_LIBCPP_ASSERT(__s != nullptr, "string::find_first_of(): received nullptr");
return __str_find_first_of<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, traits_type::length(__s));
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_first_of(value_type __c,
size_type __pos) const _NOEXCEPT
{
return find(__c, __pos);
}
// find_last_of
template<class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_last_of(const value_type* __s,
size_type __pos,
size_type __n) const _NOEXCEPT
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string::find_last_of(): received nullptr");
return __str_find_last_of<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, __n);
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_last_of(const basic_string& __str,
size_type __pos) const _NOEXCEPT
{
return __str_find_last_of<value_type, size_type, traits_type, npos>
(data(), size(), __str.data(), __pos, __str.size());
}
template<class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
typename basic_string<_CharT, _Traits, _Allocator>::size_type
>::type
basic_string<_CharT, _Traits, _Allocator>::find_last_of(const _Tp& __t,
size_type __pos) const
{
__self_view __sv = __t;
return __str_find_last_of<value_type, size_type, traits_type, npos>
(data(), size(), __sv.data(), __pos, __sv.size());
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_last_of(const value_type* __s,
size_type __pos) const _NOEXCEPT
{
_LIBCPP_ASSERT(__s != nullptr, "string::find_last_of(): received nullptr");
return __str_find_last_of<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, traits_type::length(__s));
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_last_of(value_type __c,
size_type __pos) const _NOEXCEPT
{
return rfind(__c, __pos);
}
// find_first_not_of
template<class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_first_not_of(const value_type* __s,
size_type __pos,
size_type __n) const _NOEXCEPT
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string::find_first_not_of(): received nullptr");
return __str_find_first_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, __n);
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_first_not_of(const basic_string& __str,
size_type __pos) const _NOEXCEPT
{
return __str_find_first_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __str.data(), __pos, __str.size());
}
template<class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
typename basic_string<_CharT, _Traits, _Allocator>::size_type
>::type
basic_string<_CharT, _Traits, _Allocator>::find_first_not_of(const _Tp& __t,
size_type __pos) const
{
__self_view __sv = __t;
return __str_find_first_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __sv.data(), __pos, __sv.size());
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_first_not_of(const value_type* __s,
size_type __pos) const _NOEXCEPT
{
_LIBCPP_ASSERT(__s != nullptr, "string::find_first_not_of(): received nullptr");
return __str_find_first_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, traits_type::length(__s));
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_first_not_of(value_type __c,
size_type __pos) const _NOEXCEPT
{
return __str_find_first_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __c, __pos);
}
// find_last_not_of
template<class _CharT, class _Traits, class _Allocator>
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_last_not_of(const value_type* __s,
size_type __pos,
size_type __n) const _NOEXCEPT
{
_LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string::find_last_not_of(): received nullptr");
return __str_find_last_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, __n);
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_last_not_of(const basic_string& __str,
size_type __pos) const _NOEXCEPT
{
return __str_find_last_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __str.data(), __pos, __str.size());
}
template<class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
typename basic_string<_CharT, _Traits, _Allocator>::size_type
>::type
basic_string<_CharT, _Traits, _Allocator>::find_last_not_of(const _Tp& __t,
size_type __pos) const
{
__self_view __sv = __t;
return __str_find_last_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __sv.data(), __pos, __sv.size());
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_last_not_of(const value_type* __s,
size_type __pos) const _NOEXCEPT
{
_LIBCPP_ASSERT(__s != nullptr, "string::find_last_not_of(): received nullptr");
return __str_find_last_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __s, __pos, traits_type::length(__s));
}
template<class _CharT, class _Traits, class _Allocator>
inline
typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::find_last_not_of(value_type __c,
size_type __pos) const _NOEXCEPT
{
return __str_find_last_not_of<value_type, size_type, traits_type, npos>
(data(), size(), __c, __pos);
}
// compare
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
int
>::type
basic_string<_CharT, _Traits, _Allocator>::compare(const _Tp& __t) const
{
__self_view __sv = __t;
size_t __lhs_sz = size();
size_t __rhs_sz = __sv.size();
int __result = traits_type::compare(data(), __sv.data(),
_VSTD::min(__lhs_sz, __rhs_sz));
if (__result != 0)
return __result;
if (__lhs_sz < __rhs_sz)
return -1;
if (__lhs_sz > __rhs_sz)
return 1;
return 0;
}
template <class _CharT, class _Traits, class _Allocator>
inline
int
basic_string<_CharT, _Traits, _Allocator>::compare(const basic_string& __str) const _NOEXCEPT
{
return compare(__self_view(__str));
}
template <class _CharT, class _Traits, class _Allocator>
int
basic_string<_CharT, _Traits, _Allocator>::compare(size_type __pos1,
size_type __n1,
const value_type* __s,
size_type __n2) const
{
_LIBCPP_ASSERT(__n2 == 0 || __s != nullptr, "string::compare(): received nullptr");
size_type __sz = size();
if (__pos1 > __sz || __n2 == npos)
this->__throw_out_of_range();
size_type __rlen = _VSTD::min(__n1, __sz - __pos1);
int __r = traits_type::compare(data() + __pos1, __s, _VSTD::min(__rlen, __n2));
if (__r == 0)
{
if (__rlen < __n2)
__r = -1;
else if (__rlen > __n2)
__r = 1;
}
return __r;
}
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
int
>::type
basic_string<_CharT, _Traits, _Allocator>::compare(size_type __pos1,
size_type __n1,
const _Tp& __t) const
{
__self_view __sv = __t;
return compare(__pos1, __n1, __sv.data(), __sv.size());
}
template <class _CharT, class _Traits, class _Allocator>
inline
int
basic_string<_CharT, _Traits, _Allocator>::compare(size_type __pos1,
size_type __n1,
const basic_string& __str) const
{
return compare(__pos1, __n1, __str.data(), __str.size());
}
template <class _CharT, class _Traits, class _Allocator>
template <class _Tp>
typename enable_if
<
__can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
int
>::type
basic_string<_CharT, _Traits, _Allocator>::compare(size_type __pos1,
size_type __n1,
const _Tp& __t,
size_type __pos2,
size_type __n2) const
{
__self_view __sv = __t;
return __self_view(*this).substr(__pos1, __n1).compare(__sv.substr(__pos2, __n2));
}
template <class _CharT, class _Traits, class _Allocator>
int
basic_string<_CharT, _Traits, _Allocator>::compare(size_type __pos1,
size_type __n1,
const basic_string& __str,
size_type __pos2,
size_type __n2) const
{
return compare(__pos1, __n1, __self_view(__str), __pos2, __n2);
}
template <class _CharT, class _Traits, class _Allocator>
int
basic_string<_CharT, _Traits, _Allocator>::compare(const value_type* __s) const _NOEXCEPT
{
_LIBCPP_ASSERT(__s != nullptr, "string::compare(): received nullptr");
return compare(0, npos, __s, traits_type::length(__s));
}
template <class _CharT, class _Traits, class _Allocator>
int
basic_string<_CharT, _Traits, _Allocator>::compare(size_type __pos1,
size_type __n1,
const value_type* __s) const
{
_LIBCPP_ASSERT(__s != nullptr, "string::compare(): received nullptr");
return compare(__pos1, __n1, __s, traits_type::length(__s));
}
// __invariants
template<class _CharT, class _Traits, class _Allocator>
inline
bool
basic_string<_CharT, _Traits, _Allocator>::__invariants() const
{
if (size() > capacity())
return false;
if (capacity() < __min_cap - 1)
return false;
if (data() == 0)
return false;
if (data()[size()] != value_type(0))
return false;
return true;
}
// __clear_and_shrink
template<class _CharT, class _Traits, class _Allocator>
inline
void
basic_string<_CharT, _Traits, _Allocator>::__clear_and_shrink() _NOEXCEPT
{
clear();
if(__is_long())
{
__alloc_traits::deallocate(__alloc(), __get_long_pointer(), capacity() + 1);
__set_long_cap(0);
__set_short_size(0);
}
}
// operator==
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator==(const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
size_t __lhs_sz = __lhs.size();
return __lhs_sz == __rhs.size() && _Traits::compare(__lhs.data(),
__rhs.data(),
__lhs_sz) == 0;
}
template<class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator==(const basic_string<char, char_traits<char>, _Allocator>& __lhs,
const basic_string<char, char_traits<char>, _Allocator>& __rhs) _NOEXCEPT
{
size_t __lhs_sz = __lhs.size();
if (__lhs_sz != __rhs.size())
return false;
const char* __lp = __lhs.data();
const char* __rp = __rhs.data();
if (__lhs.__is_long())
return char_traits<char>::compare(__lp, __rp, __lhs_sz) == 0;
for (; __lhs_sz != 0; --__lhs_sz, ++__lp, ++__rp)
if (*__lp != *__rp)
return false;
return true;
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator==(const _CharT* __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
typedef basic_string<_CharT, _Traits, _Allocator> _String;
_LIBCPP_ASSERT(__lhs != nullptr, "operator==(char*, basic_string): received nullptr");
size_t __lhs_len = _Traits::length(__lhs);
if (__lhs_len != __rhs.size()) return false;
return __rhs.compare(0, _String::npos, __lhs, __lhs_len) == 0;
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator==(const basic_string<_CharT,_Traits,_Allocator>& __lhs,
const _CharT* __rhs) _NOEXCEPT
{
typedef basic_string<_CharT, _Traits, _Allocator> _String;
_LIBCPP_ASSERT(__rhs != nullptr, "operator==(basic_string, char*): received nullptr");
size_t __rhs_len = _Traits::length(__rhs);
if (__rhs_len != __lhs.size()) return false;
return __lhs.compare(0, _String::npos, __rhs, __rhs_len) == 0;
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator!=(const basic_string<_CharT,_Traits,_Allocator>& __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return !(__lhs == __rhs);
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator!=(const _CharT* __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return !(__lhs == __rhs);
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator!=(const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const _CharT* __rhs) _NOEXCEPT
{
return !(__lhs == __rhs);
}
// operator<
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator< (const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return __lhs.compare(__rhs) < 0;
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator< (const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const _CharT* __rhs) _NOEXCEPT
{
return __lhs.compare(__rhs) < 0;
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator< (const _CharT* __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return __rhs.compare(__lhs) > 0;
}
// operator>
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator> (const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return __rhs < __lhs;
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator> (const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const _CharT* __rhs) _NOEXCEPT
{
return __rhs < __lhs;
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator> (const _CharT* __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return __rhs < __lhs;
}
// operator<=
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator<=(const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return !(__rhs < __lhs);
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator<=(const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const _CharT* __rhs) _NOEXCEPT
{
return !(__rhs < __lhs);
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator<=(const _CharT* __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return !(__rhs < __lhs);
}
// operator>=
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator>=(const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return !(__lhs < __rhs);
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator>=(const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const _CharT* __rhs) _NOEXCEPT
{
return !(__lhs < __rhs);
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator>=(const _CharT* __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs) _NOEXCEPT
{
return !(__lhs < __rhs);
}
// operator +
template<class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>
operator+(const basic_string<_CharT, _Traits, _Allocator>& __lhs,
const basic_string<_CharT, _Traits, _Allocator>& __rhs)
{
basic_string<_CharT, _Traits, _Allocator> __r(__lhs.get_allocator());
typename basic_string<_CharT, _Traits, _Allocator>::size_type __lhs_sz = __lhs.size();
typename basic_string<_CharT, _Traits, _Allocator>::size_type __rhs_sz = __rhs.size();
__r.__init(__lhs.data(), __lhs_sz, __lhs_sz + __rhs_sz);
__r.append(__rhs.data(), __rhs_sz);
return __r;
}
template<class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>
operator+(const _CharT* __lhs , const basic_string<_CharT,_Traits,_Allocator>& __rhs)
{
basic_string<_CharT, _Traits, _Allocator> __r(__rhs.get_allocator());
typename basic_string<_CharT, _Traits, _Allocator>::size_type __lhs_sz = _Traits::length(__lhs);
typename basic_string<_CharT, _Traits, _Allocator>::size_type __rhs_sz = __rhs.size();
__r.__init(__lhs, __lhs_sz, __lhs_sz + __rhs_sz);
__r.append(__rhs.data(), __rhs_sz);
return __r;
}
template<class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>
operator+(_CharT __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs)
{
basic_string<_CharT, _Traits, _Allocator> __r(__rhs.get_allocator());
typename basic_string<_CharT, _Traits, _Allocator>::size_type __rhs_sz = __rhs.size();
__r.__init(&__lhs, 1, 1 + __rhs_sz);
__r.append(__rhs.data(), __rhs_sz);
return __r;
}
template<class _CharT, class _Traits, class _Allocator>
inline
basic_string<_CharT, _Traits, _Allocator>
operator+(const basic_string<_CharT, _Traits, _Allocator>& __lhs, const _CharT* __rhs)
{
basic_string<_CharT, _Traits, _Allocator> __r(__lhs.get_allocator());
typename basic_string<_CharT, _Traits, _Allocator>::size_type __lhs_sz = __lhs.size();
typename basic_string<_CharT, _Traits, _Allocator>::size_type __rhs_sz = _Traits::length(__rhs);
__r.__init(__lhs.data(), __lhs_sz, __lhs_sz + __rhs_sz);
__r.append(__rhs, __rhs_sz);
return __r;
}
template<class _CharT, class _Traits, class _Allocator>
basic_string<_CharT, _Traits, _Allocator>
operator+(const basic_string<_CharT, _Traits, _Allocator>& __lhs, _CharT __rhs)
{
basic_string<_CharT, _Traits, _Allocator> __r(__lhs.get_allocator());
typename basic_string<_CharT, _Traits, _Allocator>::size_type __lhs_sz = __lhs.size();
__r.__init(__lhs.data(), __lhs_sz, __lhs_sz + 1);
__r.push_back(__rhs);
return __r;
}
#ifndef _LIBCPP_CXX03_LANG
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_string<_CharT, _Traits, _Allocator>
operator+(basic_string<_CharT, _Traits, _Allocator>&& __lhs, const basic_string<_CharT, _Traits, _Allocator>& __rhs)
{
return _VSTD::move(__lhs.append(__rhs));
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_string<_CharT, _Traits, _Allocator>
operator+(const basic_string<_CharT, _Traits, _Allocator>& __lhs, basic_string<_CharT, _Traits, _Allocator>&& __rhs)
{
return _VSTD::move(__rhs.insert(0, __lhs));
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_string<_CharT, _Traits, _Allocator>
operator+(basic_string<_CharT, _Traits, _Allocator>&& __lhs, basic_string<_CharT, _Traits, _Allocator>&& __rhs)
{
return _VSTD::move(__lhs.append(__rhs));
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_string<_CharT, _Traits, _Allocator>
operator+(const _CharT* __lhs , basic_string<_CharT,_Traits,_Allocator>&& __rhs)
{
return _VSTD::move(__rhs.insert(0, __lhs));
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_string<_CharT, _Traits, _Allocator>
operator+(_CharT __lhs, basic_string<_CharT,_Traits,_Allocator>&& __rhs)
{
__rhs.insert(__rhs.begin(), __lhs);
return _VSTD::move(__rhs);
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_string<_CharT, _Traits, _Allocator>
operator+(basic_string<_CharT, _Traits, _Allocator>&& __lhs, const _CharT* __rhs)
{
return _VSTD::move(__lhs.append(__rhs));
}
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_string<_CharT, _Traits, _Allocator>
operator+(basic_string<_CharT, _Traits, _Allocator>&& __lhs, _CharT __rhs)
{
__lhs.push_back(__rhs);
return _VSTD::move(__lhs);
}
#endif // _LIBCPP_CXX03_LANG
// swap
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
void
swap(basic_string<_CharT, _Traits, _Allocator>& __lhs,
basic_string<_CharT, _Traits, _Allocator>& __rhs)
_NOEXCEPT_(_NOEXCEPT_(__lhs.swap(__rhs)))
{
__lhs.swap(__rhs);
}
#ifndef _LIBCPP_NO_HAS_CHAR8_T
typedef basic_string<char8_t> u8string;
#endif
#ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
typedef basic_string<char16_t> u16string;
typedef basic_string<char32_t> u32string;
#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
_LIBCPP_FUNC_VIS int stoi (const string& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS long stol (const string& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS unsigned long stoul (const string& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS long long stoll (const string& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS unsigned long long stoull(const string& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS float stof (const string& __str, size_t* __idx = 0);
_LIBCPP_FUNC_VIS double stod (const string& __str, size_t* __idx = 0);
_LIBCPP_FUNC_VIS long double stold(const string& __str, size_t* __idx = 0);
_LIBCPP_FUNC_VIS string to_string(int __val);
_LIBCPP_FUNC_VIS string to_string(unsigned __val);
_LIBCPP_FUNC_VIS string to_string(long __val);
_LIBCPP_FUNC_VIS string to_string(unsigned long __val);
_LIBCPP_FUNC_VIS string to_string(long long __val);
_LIBCPP_FUNC_VIS string to_string(unsigned long long __val);
_LIBCPP_FUNC_VIS string to_string(float __val);
_LIBCPP_FUNC_VIS string to_string(double __val);
_LIBCPP_FUNC_VIS string to_string(long double __val);
_LIBCPP_FUNC_VIS int stoi (const wstring& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS long stol (const wstring& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS unsigned long stoul (const wstring& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS long long stoll (const wstring& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS unsigned long long stoull(const wstring& __str, size_t* __idx = 0, int __base = 10);
_LIBCPP_FUNC_VIS float stof (const wstring& __str, size_t* __idx = 0);
_LIBCPP_FUNC_VIS double stod (const wstring& __str, size_t* __idx = 0);
_LIBCPP_FUNC_VIS long double stold(const wstring& __str, size_t* __idx = 0);
_LIBCPP_FUNC_VIS wstring to_wstring(int __val);
_LIBCPP_FUNC_VIS wstring to_wstring(unsigned __val);
_LIBCPP_FUNC_VIS wstring to_wstring(long __val);
_LIBCPP_FUNC_VIS wstring to_wstring(unsigned long __val);
_LIBCPP_FUNC_VIS wstring to_wstring(long long __val);
_LIBCPP_FUNC_VIS wstring to_wstring(unsigned long long __val);
_LIBCPP_FUNC_VIS wstring to_wstring(float __val);
_LIBCPP_FUNC_VIS wstring to_wstring(double __val);
_LIBCPP_FUNC_VIS wstring to_wstring(long double __val);
template<class _CharT, class _Traits, class _Allocator>
const typename basic_string<_CharT, _Traits, _Allocator>::size_type
basic_string<_CharT, _Traits, _Allocator>::npos;
template <class _CharT, class _Allocator>
struct _LIBCPP_TEMPLATE_VIS
hash<basic_string<_CharT, char_traits<_CharT>, _Allocator> >
: public unary_function<
basic_string<_CharT, char_traits<_CharT>, _Allocator>, size_t>
{
size_t
operator()(const basic_string<_CharT, char_traits<_CharT>, _Allocator>& __val) const _NOEXCEPT
{ return __do_string_hash(__val.data(), __val.data() + __val.size()); }
};
template<class _CharT, class _Traits, class _Allocator>
basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& __os,
const basic_string<_CharT, _Traits, _Allocator>& __str);
template<class _CharT, class _Traits, class _Allocator>
basic_istream<_CharT, _Traits>&
operator>>(basic_istream<_CharT, _Traits>& __is,
basic_string<_CharT, _Traits, _Allocator>& __str);
template<class _CharT, class _Traits, class _Allocator>
basic_istream<_CharT, _Traits>&
getline(basic_istream<_CharT, _Traits>& __is,
basic_string<_CharT, _Traits, _Allocator>& __str, _CharT __dlm);
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_istream<_CharT, _Traits>&
getline(basic_istream<_CharT, _Traits>& __is,
basic_string<_CharT, _Traits, _Allocator>& __str);
#ifndef _LIBCPP_CXX03_LANG
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_istream<_CharT, _Traits>&
getline(basic_istream<_CharT, _Traits>&& __is,
basic_string<_CharT, _Traits, _Allocator>& __str, _CharT __dlm);
template<class _CharT, class _Traits, class _Allocator>
inline _LIBCPP_INLINE_VISIBILITY
basic_istream<_CharT, _Traits>&
getline(basic_istream<_CharT, _Traits>&& __is,
basic_string<_CharT, _Traits, _Allocator>& __str);
#endif // _LIBCPP_CXX03_LANG
#if _LIBCPP_STD_VER > 17
template<class _CharT, class _Traits, class _Allocator, class _Up>
inline _LIBCPP_INLINE_VISIBILITY
void erase(basic_string<_CharT, _Traits, _Allocator>& __str, const _Up& __v)
{ __str.erase(_VSTD::remove(__str.begin(), __str.end(), __v), __str.end()); }
template<class _CharT, class _Traits, class _Allocator, class _Predicate>
inline _LIBCPP_INLINE_VISIBILITY
void erase_if(basic_string<_CharT, _Traits, _Allocator>& __str, _Predicate __pred)
{ __str.erase(_VSTD::remove_if(__str.begin(), __str.end(), __pred), __str.end()); }
#endif
#if _LIBCPP_DEBUG_LEVEL >= 2
template<class _CharT, class _Traits, class _Allocator>
bool
basic_string<_CharT, _Traits, _Allocator>::__dereferenceable(const const_iterator* __i) const
{
return this->data() <= _VSTD::__to_raw_pointer(__i->base()) &&
_VSTD::__to_raw_pointer(__i->base()) < this->data() + this->size();
}
template<class _CharT, class _Traits, class _Allocator>
bool
basic_string<_CharT, _Traits, _Allocator>::__decrementable(const const_iterator* __i) const
{
return this->data() < _VSTD::__to_raw_pointer(__i->base()) &&
_VSTD::__to_raw_pointer(__i->base()) <= this->data() + this->size();
}
template<class _CharT, class _Traits, class _Allocator>
bool
basic_string<_CharT, _Traits, _Allocator>::__addable(const const_iterator* __i, ptrdiff_t __n) const
{
const value_type* __p = _VSTD::__to_raw_pointer(__i->base()) + __n;
return this->data() <= __p && __p <= this->data() + this->size();
}
template<class _CharT, class _Traits, class _Allocator>
bool
basic_string<_CharT, _Traits, _Allocator>::__subscriptable(const const_iterator* __i, ptrdiff_t __n) const
{
const value_type* __p = _VSTD::__to_raw_pointer(__i->base()) + __n;
return this->data() <= __p && __p < this->data() + this->size();
}
#endif // _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_EXTERN_TEMPLATE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS basic_string<char>)
_LIBCPP_EXTERN_TEMPLATE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS basic_string<wchar_t>)
#if _LIBCPP_STD_VER > 11
// Literal suffixes for basic_string [basic.string.literals]
inline namespace literals
{
inline namespace string_literals
{
inline _LIBCPP_INLINE_VISIBILITY
basic_string<char> operator "" s( const char *__str, size_t __len )
{
return basic_string<char> (__str, __len);
}
inline _LIBCPP_INLINE_VISIBILITY
basic_string<wchar_t> operator "" s( const wchar_t *__str, size_t __len )
{
return basic_string<wchar_t> (__str, __len);
}
#ifndef _LIBCPP_NO_HAS_CHAR8_T
inline _LIBCPP_INLINE_VISIBILITY
basic_string<char8_t> operator "" s(const char8_t *__str, size_t __len) _NOEXCEPT
{
return basic_string<char8_t> (__str, __len);
}
#endif
inline _LIBCPP_INLINE_VISIBILITY
basic_string<char16_t> operator "" s( const char16_t *__str, size_t __len )
{
return basic_string<char16_t> (__str, __len);
}
inline _LIBCPP_INLINE_VISIBILITY
basic_string<char32_t> operator "" s( const char32_t *__str, size_t __len )
{
return basic_string<char32_t> (__str, __len);
}
}
}
#endif
_LIBCPP_END_NAMESPACE_STD
_LIBCPP_POP_MACROS
#endif // _LIBCPP_STRING
| [
"_@jeremy.ca"
] | _@jeremy.ca | |
03c59e7794f106e0acf809198048c94a5287470a | 0fad1e93f2a737b0f533427e6bbdd7c8a7541247 | /ldr/ldr.ino | f61f370ee62d28872f92b0fff846d4b7db4baf2d | [
"MIT"
] | permissive | shikya/arduino-automation-strip | 62fa75a0c13f3fabfc9e350f98b6b18712c4f91b | ad1ae3bd98eca37c2962ad27a64f7a0692cf5fc3 | refs/heads/master | 2020-04-13T06:08:55.242295 | 2019-01-13T19:46:18 | 2019-01-13T19:46:18 | 163,012,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 332 | ino | int ldr = A7;
int led = 6;
int value =0;
void setup() {
// put your setup code here, to run once:
pinMode(ldr, INPUT);
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
value = analogRead(ldr);
Serial.println(value);
//Serial.print(" ");
delay(100);
}
| [
"shrikantsonone@gmail.com"
] | shrikantsonone@gmail.com |
6731817a8e045fec4b89ed01233e9d3d46ee4e8b | a403d656bec65074adb17d193b8742a0b4cd60af | /1048.cpp | 19f42bde4fe69c45209e827ef2ca2d4a2bf4d9a7 | [] | no_license | LucVeloso/URI_CPP | 87835b5073e96846c170066550e33e19b8b3c927 | 5d068c274dfa77623ff6701a5900a2bc2c78444e | refs/heads/master | 2023-01-31T09:44:20.555578 | 2020-12-11T13:48:11 | 2020-12-11T13:48:11 | 320,577,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,046 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
double a, b;
cin >> a;
cout << fixed << setprecision(2);
if ( a <= 400.00 )
{
b = a*15/100;
cout << "Novo salario: " << a+b << endl;
cout << "Reajuste ganho: " << b << endl;
cout << "Em percentual: 15 %" << endl;
}
else if ( a <= 800.00 )
{
b = a*12/100;
cout << "Novo salario: " << a+b << endl;
cout << "Reajuste ganho: " << b << endl;
cout << "Em percentual: 12 %" << endl;
}
else if ( a <= 1200.00 )
{
b = a*10/100;
cout << "Novo salario: " << a+b << endl;
cout << "Reajuste ganho: " << b << endl;
cout << "Em percentual: 10 %" << endl;
}
else if ( a <= 2000.00 )
{
b = a*7/100;
cout << "Novo salario: " << a+b << endl;
cout << "Reajuste ganho: " << b << endl;
cout << "Em percentual: 7 %" << endl;
}
else
{
b = a*4/100;
cout << "Novo salario: " << a+b << endl;
cout << "Reajuste ganho: " << b << endl;
cout << "Em percentual: 4 %" << endl;
}
return 0;
} | [
"lucasvelosobp@gmail.com"
] | lucasvelosobp@gmail.com |
f8c54b9e889eb239491c063d5d3798bf12becb41 | edd6b6ee0cafee8299b4ecdc1df2b8f49f6762f5 | /src/Histogramming/Recon/HistogrammingMuonRegions.cpp | 8c4c00f8dda5af870ab3c275251172d1e2907580 | [] | no_license | leggat/tWIHEPFramework | 4512ea9a0bc798309112ac4111636e929fbf6443 | 0ad97e207dc9b41c8c989b268cd72c57f5d241c9 | refs/heads/master | 2022-02-09T20:34:22.678309 | 2021-08-24T17:33:09 | 2021-08-24T17:33:09 | 62,226,837 | 0 | 4 | null | 2021-10-05T08:04:02 | 2016-06-29T13:12:19 | C++ | UTF-8 | C++ | false | false | 18,730 | cpp | /******************************************************************************
* HistogramMuonRegions.cpp *
* *
* Books and fills histograms *
* Books histograms in different pT, eta, and phi regions *
* Only makes hists for Number of Events - used for Efficiency Calculations *
* *
* Derived from HistoCut which is in turn derived from BaseCut *
* *
* Public Member Functions of AnalysisMain class *
* HistogramMuonRegions() -- Parameterized Constructor *
* ~HistogramMuonRegions() -- Destructor *
* BookHistogram() -- Book histograms *
* Apply() -- Fill histograms only (No Cuts) *
* GetCutName() -- Returns "HistogramMuonRegions" *
* *
* Private Data Members of HistogramMuonRegions class *
* - lots of histograms of muon propreties *
* *
* History *
* 10 Dec 2007 - Created by P. Ryan *
* 22 Jan 2007 - Updated for new object definitions *
* 2 Dec 2008 - P. Ryan - added 2D rejection histograms *
*****************************************************************************/
#include "SingleTopRootAnalysis/Histogramming/Recon/HistogrammingMuonRegions.hpp"
#include<iostream>
using namespace std;
/******************************************************************************
* HistogrammingMuonRegions::HistogrammingMuonRegions(EventContainer *obj) *
* *
* Parameterized Constructor *
* *
* Input: Event container *
* Output: None *
******************************************************************************/
HistogrammingMuonRegions::HistogrammingMuonRegions(EventContainer *obj, TString muonTypePassed)
{
// Check muonType parameter
if( muonTypePassed.CompareTo("All") && muonTypePassed.CompareTo("UnIsolated") && muonTypePassed.CompareTo("Isolated") &&
muonTypePassed.CompareTo("Tight") && muonTypePassed.CompareTo("Veto") ){
std::cout << "ERROR " << "<HistogrammingMuonRegions::HistogrammingMuonRegions()> "
<< "Must pass Tight, Veto, Isolated, or UnIsolated to constructor" << std::endl;
exit(8);
} //if
muonType = muonTypePassed;
SetEventContainer(obj);
} //HistogrammingMuonRegions()
/******************************************************************************
* HistogrammingMuonRegions::~HistogrammingMuonRegions() *
* *
* Destructor *
* *
* Input: None *
* Output: None *
******************************************************************************/
HistogrammingMuonRegions::~HistogrammingMuonRegions()
{
} //HistogrammingMuonRegions
/******************************************************************************
* void HistogrammingMuonRegions::BookHistogram() *
* *
* Book Histograms *
* *
* Input: None *
* Output: None *
******************************************************************************/
void HistogrammingMuonRegions::BookHistogram(){
// Histogram bin sizes and ranges
Int_t nBin = 10;
Double_t nMin = 0.0;
Double_t nMax = 10.0;
// For histogram names
TString histName;
TString histTitle;
////////////////////////////////////////////////////////////////
// All Regions
////////////////////////////////////////////////////////////////
_hNObj = DeclareTH1F("MuN","Number of Muons", nBin, nMin, nMax);
_hNObj -> SetXAxisTitle("N");
_hNObj -> SetYAxisTitle("Events");
////////////////////////////////////////////////////////////////
// pT Divisions
////////////////////////////////////////////////////////////////
Double_t ptBase = 10.0;
Double_t ptIncrement = 5.0;
Int_t ptCutNumber = 15;
ptCutsVector.clear();
for(Int_t i = 0; i < ptCutNumber; i++) ptCutsVector.push_back(ptBase + i*ptIncrement);
// Separate pT Regions
ptHistVector.clear();
for(Int_t i = 0; i < ptCutNumber - 1; i++){
// Histogram Names
std::ostringstream histNameStream;
histNameStream << "MuN_pt" << i+1;
histName = histNameStream.str().c_str();
// Histogram Titles
std::ostringstream histTitleStream;
histTitleStream << "Number of Muons - pt" << i+1;
histTitle = histNameStream.str().c_str();
// Book Histogram
ptHistVector.push_back( (myTH1F*)(DeclareTH1F(histName.Data(), histTitle.Data(), nBin, nMin, nMax)) );
ptHistVector[i] -> SetXAxisTitle("N");
ptHistVector[i] -> SetYAxisTitle("Events");
} //for
// pT Turn-on
ptTurnOnHistVector.clear();
for(Int_t i = 0; i < ptCutNumber ; i++){
// Histogram Names
std::ostringstream histNameStream;
histNameStream << "MuN_ptTurnOn" << i+1;
histName = histNameStream.str().c_str();
// Histogram Titles
std::ostringstream histTitleStream;
histTitleStream << "Number of Muons - pt Turn On" << i+1;
histTitle = histNameStream.str().c_str();
// Book Histogram
ptTurnOnHistVector.push_back( (myTH1F*)(DeclareTH1F(histName.Data(), histTitle.Data(), nBin, nMin, nMax)) );
ptTurnOnHistVector[i] -> SetXAxisTitle("N");
ptTurnOnHistVector[i] -> SetYAxisTitle("Events");
} //for
////////////////////////////////////////////////////////////////
// Eta Divisions
////////////////////////////////////////////////////////////////
Double_t etaBase = -2.5;
Double_t etaIncrement = 0.5;
Int_t etaCutNumber = 11;
etaHistVector.clear();
etaCutsVector.clear();
for(Int_t i = 0; i < etaCutNumber; i++) etaCutsVector.push_back(etaBase + i*etaIncrement);
for(Int_t i = 0; i < etaCutNumber - 1; i++){
// Histogram Names
std::ostringstream histNameStream;
histNameStream << "MuN_eta" << i+1;
histName = histNameStream.str().c_str();
// Histogram Titles
std::ostringstream histTitleStream;
histTitleStream << "Number of Muons - eta" << i+1;
histTitle = histNameStream.str().c_str();
// Book Histogram
etaHistVector.push_back( (myTH1F*)(DeclareTH1F(histName.Data(), histTitle.Data(), nBin, nMin, nMax)) );
etaHistVector[i] -> SetXAxisTitle("N");
etaHistVector[i] -> SetYAxisTitle("Events");
} //for
////////////////////////////////////////////////////////////////
// Phi Divisions
////////////////////////////////////////////////////////////////
Double_t phiBase = 0.0;
Double_t phiIncrement = TMath::Pi() / 6.0;
Int_t phiCutNumber = 13;
phiHistVector.clear();
phiCutsVector.clear();
for(Int_t i = 0; i < phiCutNumber; i++) phiCutsVector.push_back(phiBase + i*phiIncrement - TMath::Pi());
for(Int_t i = 0; i < phiCutNumber - 1; i++){
// Histogram Names
std::ostringstream histNameStream;
histNameStream << "MuN_phi" << i+1;
histName = histNameStream.str().c_str();
// Histogram Titles
std::ostringstream histTitleStream;
histTitleStream << "Number of Muons - phi" << i+1;
histTitle = histNameStream.str().c_str();
// Book Histogram
phiHistVector.push_back( (myTH1F*)(DeclareTH1F(histName.Data(), histTitle.Data(), nBin, nMin, nMax)) );
phiHistVector[i] -> SetXAxisTitle("N");
phiHistVector[i] -> SetYAxisTitle("Events");
} //for
////////////////////////////////////////////////////////////////
// pT-Eta Divisions
////////////////////////////////////////////////////////////////
ptEtaHistVectorVector.clear();
for(Int_t i = 0; i < ptCutNumber - 1; i++){
ptEtaHistVector.clear();
for(Int_t j = 0; j < etaCutNumber - 1; j++){
// Histogram Names
std::ostringstream histNameStream;
histNameStream << "MuN_pt" << i+1 << "_eta" << j+1;
histName = histNameStream.str().c_str();
// Histogram Titles
std::ostringstream histTitleStream;
histTitleStream << "Number of Muons - pt " << i+1 << " eta " << j+1;
histTitle = histNameStream.str().c_str();
// Book Histogram
ptEtaHistVector.push_back( DeclareTH1F(histName.Data(), histTitle.Data(), nBin, nMin, nMax) );
} //for j
// Push Vectors into Vector of Vectors
ptEtaHistVectorVector.push_back( ptEtaHistVector );
} //for i
for(Int_t i = 0; i < ptCutNumber - 1; i++){
for(Int_t j = 0; j < etaCutNumber - 1; j++){
ptEtaHistVectorVector[i][j] -> SetXAxisTitle("N");
ptEtaHistVectorVector[i][j] -> SetYAxisTitle("Events");
} //for j
} //for i
////////////////////////////////////////////////////////////////
// pT-Phi Divisions
////////////////////////////////////////////////////////////////
ptPhiHistVectorVector.clear();
for(Int_t i = 0; i < ptCutNumber - 1; i++){
ptPhiHistVector.clear();
for(Int_t j = 0; j < phiCutNumber - 1; j++){
// Histogram Names
std::ostringstream histNameStream;
histNameStream << "MuN_pt" << i+1 << "_phi" << j+1;
histName = histNameStream.str().c_str();
// Histogram Titles
std::ostringstream histTitleStream;
histTitleStream << "Number of Muons - pt " << i+1 << " phi " << j+1;
histTitle = histNameStream.str().c_str();
// Book Histogram
ptPhiHistVector.push_back( DeclareTH1F(histName.Data(), histTitle.Data(), nBin, nMin, nMax) );
} //for j
// Push Vectors into Vector of Vectors
ptPhiHistVectorVector.push_back( ptPhiHistVector );
} //for i
for(Int_t i = 0; i < ptCutNumber - 1; i++){
for(Int_t j = 0; j < phiCutNumber - 1; j++){
ptPhiHistVectorVector[i][j] -> SetXAxisTitle("N");
ptPhiHistVectorVector[i][j] -> SetYAxisTitle("Events");
} //for j
} //for i
////////////////////////////////////////////////////////////////
// eta-Phi Divisions
////////////////////////////////////////////////////////////////
etaPhiHistVectorVector.clear();
for(Int_t i = 0; i < etaCutNumber - 1; i++){
etaPhiHistVector.clear();
for(Int_t j = 0; j < phiCutNumber - 1; j++){
// Histogram Names
std::ostringstream histNameStream;
histNameStream << "MuN_eta" << i+1 << "_phi" << j+1;
histName = histNameStream.str().c_str();
// Histogram Titles
std::ostringstream histTitleStream;
histTitleStream << "Number of Muons - eta " << i+1 << " phi " << j+1;
histTitle = histNameStream.str().c_str();
// Book Histogram
etaPhiHistVector.push_back( DeclareTH1F(histName.Data(), histTitle.Data(), nBin, nMin, nMax) );
} //for j
// Push Vectors into Vector of Vectors
etaPhiHistVectorVector.push_back( etaPhiHistVector );
} //for i
for(Int_t i = 0; i < etaCutNumber - 1; i++){
for(Int_t j = 0; j < phiCutNumber - 1; j++){
etaPhiHistVectorVector[i][j] -> SetXAxisTitle("N");
etaPhiHistVectorVector[i][j] -> SetYAxisTitle("Events");
} //for j
} //for i
} //BookHistogram
/******************************************************************************
* Bool_t HistogrammingMuonRegions::Apply() *
* *
* Fill histograms *
* *
* Input: None *
* Output: kTrue if successful *
******************************************************************************/
Bool_t HistogrammingMuonRegions::Apply()
{
//cout<<"Begin of HistogrammingMuonRegions::Apply()"<<endl;
// Get Event Tree
EventContainer *evc = GetEventContainer();
////////////////////////////////////////////////////////////////
// Get Multiplicity, pT, eta, phi
////////////////////////////////////////////////////////////////
Int_t multiplicity = evc -> tightMuons.size();
Double_t pt = -999.0;
Double_t eta = -999.0;
Double_t phi = -999.0;
if( multiplicity > 0 ){
//pt = evc->muons[0].Pt();
//eta = evc->muons[0].Eta();
//phi = evc->muons[0].Phi();
pt = evc->tightMuons[0].Pt();
eta = evc->tightMuons[0].Eta();
phi = evc->tightMuons[0].Phi();
} //if
////////////////////////////////////////////////////////////////
// Fill histograms according to regions
////////////////////////////////////////////////////////////////
for(Int_t i = 0; i < (ptCutsVector.size() - 1); i++) if( (pt > ptCutsVector[i]) && (pt < ptCutsVector[i+1]) ) ptHistVector[i] -> Fill(multiplicity);
for(Int_t i = 0; i < (etaCutsVector.size() - 1); i++) if( (eta > etaCutsVector[i]) && (eta < etaCutsVector[i+1]) ) etaHistVector[i] -> Fill(multiplicity);
for(Int_t i = 0; i < (phiCutsVector.size() - 1); i++) if( (phi > phiCutsVector[i]) && (phi < phiCutsVector[i+1]) ) phiHistVector[i] -> Fill(multiplicity);
// pt-eta
for(Int_t i = 0; i < (ptCutsVector.size() -1); i++){
for(Int_t j = 0; j < (etaCutsVector.size() -1); j++){
if( (pt > ptCutsVector[i]) && (pt < ptCutsVector[i+1]) && (eta > etaCutsVector[j]) && (eta < etaCutsVector[j+1]) ) ptEtaHistVectorVector[i][j] -> Fill(multiplicity);
} //for j
} //for i
// pt-phi
for(Int_t i = 0; i < (ptCutsVector.size() -1); i++){
for(Int_t j = 0; j < (phiCutsVector.size() -1); j++){
if( (pt > ptCutsVector[i]) && (pt < ptCutsVector[i+1]) && (phi > phiCutsVector[j]) && (phi < phiCutsVector[j+1]) ) ptPhiHistVectorVector[i][j] -> Fill(multiplicity);
} //for j
} //for i
// eta-phi
for(Int_t i = 0; i < (etaCutsVector.size() -1); i++){
for(Int_t j = 0; j < (phiCutsVector.size() -1); j++){
if( (eta > etaCutsVector[i]) && (eta < etaCutsVector[i+1]) && (phi > phiCutsVector[j]) && (phi < phiCutsVector[j+1]) ) etaPhiHistVectorVector[i][j] -> Fill(multiplicity);
} //for j
} //for i
////////////////////////////////////////////////////////////////
// Fill histograms for turn-on curves
////////////////////////////////////////////////////////////////
// Int_t multiplicityTurnOn = evc -> isolatedMuons.size();
Int_t multiplicityTurnOn = evc -> tightMuons.size();
Double_t ptTurnOn = -999.0;
Double_t etaTurnOn = -999.0;
Double_t phiTurnOn = -999.0;
if( multiplicityTurnOn > 0 ){
ptTurnOn = evc -> tightMuons[0].Pt();
etaTurnOn = evc -> tightMuons[0].Eta();
phiTurnOn = evc -> tightMuons[0].Phi();
} //if
// TMP
//if(evc -> L1Muons.size() > 0){
// if( evc -> L1Muons[0].GetDeltaRMuon() < 0.2 ) // DeltaR Recon
//if( evc -> L1Muons[0].GetDeltaRMCMuon() < 0.2 ) // DeltaR Truth
//if( evc -> L1Muons[0].GetDeltaRL2Muon() < 0.2 ) // DeltaR L2
//if( evc -> L1Muons[0].GetDeltaREvtFilterMuon() < 0.2 ) // DeltaR EF
// {for(Int_t i = 0; i < (ptCutsVector.size()); i++) if( (ptTurnOn > ptCutsVector[i]) ) ptTurnOnHistVector[i] -> Fill(multiplicityTurnOn);} //if DeltaR
// } //if size
//if(evc -> L2Muons.size() > 0){
//if( evc -> L2Muons[0].GetDeltaRMuon() < 0.2 ) // DeltaR Recon
//if( evc -> L2Muons[0].GetDeltaRMCMuon() < 0.2 ) // DeltaR Truth
//if( evc -> L2Muons[0].GetDeltaRL1Muon() < 0.2 ) // DeltaR L1
//if( evc -> L2Muons[0].GetDeltaREvtFilterMuon() < 0.2 ) // DeltaR EF
//{for(Int_t i = 0; i < (ptCutsVector.size()); i++) if( (ptTurnOn > ptCutsVector[i]) ) ptTurnOnHistVector[i] -> Fill(multiplicityTurnOn);} //if DeltaR
//} //if size
//if(evc -> EFMuons.size() > 0){
// if(evc -> L1Muons[0].GetDeltaRMuon() > 0.2) std::cout << "@@@@ " << evc -> L1Muons[0].GetDeltaRMuon() << std::endl;
//if( evc -> EFMuons[0].GetDeltaRMuon() < 0.2 ) // DeltaR Recon
//if( evc -> EFMuons[0].GetDeltaRMCMuon() < 0.2 ) // DeltaR Truth
//if( evc -> EFMuons[0].GetDeltaRL2Muon() < 0.2 ) // DeltaR L2
//if( evc -> EFMuons[0].GetDeltaRL1Muon() < 0.2 ) // DeltaR L1
//{for(Int_t i = 0; i < (ptCutsVector.size()); i++) if( (ptTurnOn > ptCutsVector[i]) ) ptTurnOnHistVector[i] -> Fill(multiplicityTurnOn);} //if DeltaR
//} //if size
// else{// std::cout << "#### " << evc -> L1Muons[0].GetDeltaRMuon() << std::endl; // tmp}
// Old - histograms events with 0 multiplicity
//for(Int_t i = 0; i < (ptCutsVector.size()); i++){
// if( (ptTurnOn > ptCutsVector[i]) || -999.0 == ptTurnOn ){
// ptTurnOnHistVector[i] -> Fill(multiplicityTurnOn);
// if( -999.0 == ptTurnOn) std::cout << "WARNING: <HistogrammingMuonRegions:Apply()> Muon Multiplicity is 0" << std::endl;
// } //if
//} //for
// if( -999.0 == ptTurnOn) std::cout << "WARNING: <HistogrammingMuonRegions:Apply()> Muon Multiplicity is 0. Event not histogrammed." << std::endl;
for(Int_t i = 0; i < (ptCutsVector.size()); i++){
if( (ptTurnOn > ptCutsVector[i]) && -999.0 != ptTurnOn ){
ptTurnOnHistVector[i] -> Fill(multiplicityTurnOn);
} //if
} //for
// Fill
_hNObj -> Fill(multiplicity);
////////////////tmp
//for(Int_t i = 0; i < (ptCutsVector.size() ); i++) std::cout << "Histogram " << i+1 << " pT > " << ptCutsVector[i] << std::endl;
////////////// end tmp
//cout<<"End of HistogrammingMuonRegions::Apply()"<<endl;
return kTRUE;
} //Apply
| [
"leggat@cern.ch"
] | leggat@cern.ch |
e1485d07df40425ea9049b52eadad1cb25847f8a | a8d4404dc9f8ecfbedf2af7e83bb9572ec8120f2 | /libs/ofxTwitter/src/Entities.cpp | 092a930902b899d38c74947b21d484954bfee34a | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | bakercp/ofxTwitter | 835469a57d9bfc1bdb0717a6fd572ebadcf8509f | 1a4713bbca66b978948070527d1b6b560aa5e8c2 | refs/heads/master | 2021-03-24T09:14:23.946322 | 2018-12-22T17:57:58 | 2018-12-22T17:57:58 | 14,264,957 | 18 | 7 | MIT | 2020-09-17T22:55:01 | 2013-11-09T20:59:43 | C++ | UTF-8 | C++ | false | false | 21,788 | cpp | //
// Copyright (c) 2009 Christopher Baker <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#include "ofx/Twitter/Entities.h"
#include "ofx/Twitter/User.h"
#include "ofx/Twitter/Utils.h"
#include "ofLog.h"
#include "Poco/Exception.h"
#include "Poco/URI.h"
namespace ofx {
namespace Twitter {
BaseIndexedEntity::BaseIndexedEntity()
{
}
BaseIndexedEntity::BaseIndexedEntity(std::size_t startIndex,
std::size_t endIndex):
_startIndex(startIndex),
_endIndex(endIndex)
{
}
BaseIndexedEntity::~BaseIndexedEntity()
{
}
std::size_t BaseIndexedEntity::startIndex() const
{
return _startIndex;
}
std::size_t BaseIndexedEntity::endIndex() const
{
return _endIndex;
}
SymbolEntity::SymbolEntity()
{
}
SymbolEntity::SymbolEntity(std::size_t startIndex,
std::size_t endIndex,
const std::string& symbol):
BaseIndexedEntity(startIndex, endIndex),
_symbol(symbol)
{
}
SymbolEntity::~SymbolEntity()
{
}
std::string SymbolEntity::symbol() const
{
return _symbol;
}
std::string SymbolEntity::indexedText() const
{
return _symbol;
}
SymbolEntity SymbolEntity::fromJson(const ofJson& json)
{
std::string text;
std::size_t startIndex = 0;
std::size_t endIndex = 0;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (value.is_null())
{
ofLogError("SymbolEntity::fromJson") << "Value is NULL, key = " << key;
++iter;
continue;
}
if (key == "indices")
{
if (value.size() == 2)
{
startIndex = value[0];
endIndex = value[1];
}
else ofLogError("SymbolEntity::fromJson") << "Not two indices: " << value;
}
else if (key == "text") text = value;
else ofLogWarning("SymbolEntity::fromJson") << "Unknown key: " << key;
++iter;
}
return SymbolEntity(startIndex, endIndex, text);
}
HashTagEntity::HashTagEntity(std::size_t startIndex,
std::size_t endIndex,
const std::string& hashTag):
BaseIndexedEntity(startIndex, endIndex),
_hashTag(hashTag)
{
}
HashTagEntity::~HashTagEntity()
{
}
std::string HashTagEntity::hashTag() const
{
return _hashTag;
}
std::string HashTagEntity::indexedText() const
{
return _hashTag;
}
HashTagEntity HashTagEntity::fromJson(const ofJson& json)
{
std::string text;
std::size_t startIndex = 0;
std::size_t endIndex = 0;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (value.is_null())
{
ofLogError("HashTagEntity::fromJson") << "Value is NULL, key = " << key;
++iter;
continue;
}
if (key == "indices")
{
if (value.size() == 2)
{
startIndex = value[0];
endIndex = value[1];
}
else ofLogError("HashTagEntity::fromJson") << "Not two indices: " << value;
}
else if (key == "text") text = value;
else ofLogWarning("HashTagEntity::fromJson") << "Unknown key: " << key;
++iter;
}
return HashTagEntity(startIndex, endIndex, text);
}
URLEntity::URLEntity()
{
}
URLEntity::URLEntity(std::size_t startIndex,
std::size_t endIndex,
const std::string& url,
const std::string& displayURL,
const std::string& expandedURL):
BaseIndexedEntity(startIndex, endIndex),
_url(url),
_displayURL(displayURL),
_expandedURL(expandedURL)
{
}
URLEntity::~URLEntity()
{
}
std::string URLEntity::url() const
{
return _url;
}
std::string URLEntity::displayURL() const
{
return _displayURL;
}
std::string URLEntity::expandedURL() const
{
return _expandedURL;
}
std::string URLEntity::indexedText() const
{
return _url;
}
URLEntity URLEntity::fromJson(const ofJson& json)
{
std::size_t startIndex = 0;
std::size_t endIndex = 0;
std::string url;
std::string displayUrl;
std::string expandedUrl;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (key == "indices")
{
if (value.size() == 2)
{
startIndex = value[0];
endIndex = value[1];
}
else ofLogError("URLEntity::fromJson") << "Not two indices: " << value;
}
else if (key == "url") { if (!value.is_null()) url = value; }
else if (key == "display_url") { if (!value.is_null()) displayUrl = value; }
else if (key == "expanded_url") { if (!value.is_null()) expandedUrl = value; }
else ofLogWarning("URLEntity::fromJson") << "Unknown key: " << key;
++iter;
}
return URLEntity(startIndex, endIndex, url, displayUrl, expandedUrl);
}
QuotedStatusPermalink::QuotedStatusPermalink()
{
}
QuotedStatusPermalink::QuotedStatusPermalink(const QuotedStatusPermalink& permalink):
QuotedStatusPermalink(permalink.url(),
permalink.displayURL(),
permalink.expandedURL())
{
}
QuotedStatusPermalink::QuotedStatusPermalink(const std::string& url,
const std::string& displayURL,
const std::string& expandedURL):
_url(url),
_displayURL(displayURL),
_expandedURL(expandedURL)
{
}
QuotedStatusPermalink::~QuotedStatusPermalink()
{
}
std::string QuotedStatusPermalink::url() const
{
return _url;
}
std::string QuotedStatusPermalink::displayURL() const
{
return _displayURL;
}
std::string QuotedStatusPermalink::expandedURL() const
{
return _expandedURL;
}
QuotedStatusPermalink QuotedStatusPermalink::fromJson(const ofJson& json)
{
std::string url;
std::string displayUrl;
std::string expandedUrl;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (key == "url") { if (!value.is_null()) url = value; }
else if (key == "display") { if (!value.is_null()) displayUrl = value; }
else if (key == "expanded") { if (!value.is_null()) expandedUrl = value; }
else ofLogWarning("QuotedStatusPermalink::fromJson") << "Unknown key: " << key;
++iter;
}
return QuotedStatusPermalink(url, displayUrl, expandedUrl);
}
MediaEntitySize::MediaEntitySize(Resize resize,
std::size_t width,
std::size_t height):
_resize(resize),
_width(width),
_height(height)
{
}
MediaEntitySize::~MediaEntitySize()
{
}
MediaEntitySize::Resize MediaEntitySize::resize() const
{
return _resize;
}
std::size_t MediaEntitySize::width() const
{
return _width;
}
std::size_t MediaEntitySize::height() const
{
return _height;
}
MediaEntitySize MediaEntitySize::fromJson(const ofJson& json)
{
MediaEntitySize::Resize resize = MediaEntitySize::Resize::CROP;
std::size_t width = 0;
std::size_t height = 0;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (value.is_null())
{
ofLogError("MediaEntitySize::fromJson") << "Value is NULL, key = " << key;
++iter;
continue;
}
if (key == "w") width = value;
else if (key == "h") height = value;
else if (key == "resize")
{
if (value == "crop") resize = MediaEntitySize::Resize::CROP;
else if (value == "fit") resize = MediaEntitySize::Resize::FIT;
else ofLogError("MediaEntitySize::fromJson") << "Unknown fit value: " << value;
}
else ofLogWarning("MediaEntitySize::fromJson") << "Unknown key: " << key;
++iter;
}
return MediaEntitySize(resize, width, height);
}
VideoInfo::VideoInfo()
{
}
VideoInfo::VideoInfo(AspectRatio aspectRatio,
uint64_t duration,
const std::vector<Variant>& variants):
_aspectRatio(aspectRatio),
_duration(duration),
_variants(variants)
{
}
VideoInfo::~VideoInfo()
{
}
VideoInfo::AspectRatio VideoInfo::aspectRatio() const
{
return _aspectRatio;
}
uint64_t VideoInfo::duration() const
{
return _duration;
}
std::vector<VideoInfo::Variant> VideoInfo::variants() const
{
return _variants;
}
VideoInfo VideoInfo::fromJSON(const ofJson& json)
{
VideoInfo info;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (value.is_null())
{
ofLogError("VideoInfo::fromJSON") << "Value is NULL, key = " << key;
++iter;
continue;
}
if (key == "aspect_ratio")
{
if (value.size() == 2)
{
info._aspectRatio.x = value[0];
info._aspectRatio.y = value[1];
}
else ofLogError("VideoInfo::fromJSON") << "Not two values: " << value;
}
else if (key == "duration_millis") info._duration = value;
else if (key == "variants")
{
for (auto variant: value)
{
VideoInfo::Variant v;
auto _iter = variant.cbegin();
while (_iter != variant.cend())
{
const auto& _key = _iter.key();
const auto& _value = _iter.value();
if (_key == "bitrate") v.bitrate = _value;
else if (_key == "content_type") v.contentType = _value;
else if (_key == "url") v.url = _value;
else ofLogError("VideoInfo::fromJSON") << "VideoInfo::Variant unknon key: " << _value;
++_iter;
}
info._variants.push_back(v);
}
}
else ofLogWarning("VideoInfo::fromJSON") << "Unknown key: " << key;
++iter;
}
return info;
}
bool AdditionalMediaInfo::monetizable() const
{
return _montetizable;
}
std::string AdditionalMediaInfo::description() const
{
return _description;
}
bool AdditionalMediaInfo::embeddable() const
{
return _embeddable;
}
std::string AdditionalMediaInfo::title() const
{
return _title;
}
std::shared_ptr<User> AdditionalMediaInfo::sourceUser() const
{
return _sourceUser;
}
AdditionalMediaInfo AdditionalMediaInfo::fromJSON(const ofJson& json)
{
AdditionalMediaInfo info;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (Utils::endsWith(key, "_str")) { /* skip */ }
else if (key == "monetizable")
{
info._montetizable = value;
}
else if (key == "source_user")
{
info._sourceUser = std::make_shared<User>(User::fromJSON(value));
}
else if (key == "description")
{
info._description = value;
}
else if (key == "embeddable")
{
info._embeddable = value;
}
else if (key == "title")
{
info._title = value;
}
else ofLogWarning("AdditionalMediaInfo::fromJson") << "Unknown key: " << key << " : " << value.dump(4);
++iter;
}
return info;
}
MediaEntity::MediaEntity()
{
}
MediaEntity::MediaEntity(std::size_t startIndex,
std::size_t endIndex,
const std::string& url,
const std::string& displayURL,
const std::string& expandedURL,
const std::string& mediaURL,
const std::string& secureMediaURL,
int64_t mediaID,
Type type,
const Sizes& sizes,
int64_t sourceStatusID,
int64_t sourceUserID,
const VideoInfo& videoInfo):
URLEntity(startIndex, endIndex, url, displayURL, expandedURL),
_mediaURL(mediaURL),
_secureMediaURL(secureMediaURL),
_mediaID(mediaID),
_type(type),
_sizes(sizes),
_sourceStatusID(sourceStatusID),
_sourceUserID(sourceUserID),
_videoInfo(videoInfo)
{
}
MediaEntity::~MediaEntity()
{
}
std::string MediaEntity::mediaURL() const
{
return _mediaURL;
}
std::string MediaEntity::secureMediaURL() const
{
return _secureMediaURL;
}
int64_t MediaEntity::mediaID() const
{
return _mediaID;
}
std::string MediaEntity::mediaFilename() const
{
try
{
Poco::URI uri(mediaURL());
std::filesystem::path path(uri.getPathEtc());
return path.filename().string();
}
catch (const Poco::SyntaxException& exc)
{
ofLogError("MediaEntity::mediaFilename") << "Unable to parse URL " << mediaURL();
return "";
}
}
std::string MediaEntity::mediaFileExtension() const
{
return std::filesystem::path(mediaFilename()).extension().string();
}
MediaEntity::Sizes MediaEntity::sizes() const
{
return _sizes;
}
MediaEntity::Type MediaEntity::type() const
{
return _type;
}
int64_t MediaEntity::sourceStatusID() const
{
return _sourceStatusID;
}
int64_t MediaEntity::sourceUserID() const
{
return _sourceUserID;
}
VideoInfo MediaEntity::videoInfo() const
{
return _videoInfo;
}
AdditionalMediaInfo MediaEntity::additionalMediaEntity() const
{
return _additionalMediaInfo;
}
MediaEntity MediaEntity::fromJson(const ofJson& json)
{
MediaEntity entity;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (Utils::endsWith(key, "_str")) { /* skip */ }
else if (key == "indices")
{
if (value.size() == 2)
{
entity._startIndex = value[0];
entity._endIndex = value[1];
}
else ofLogError("MediaEntity::fromJson") << "Not two indices: " << value;
}
else if (key == "type")
{
if (value == "photo") entity._type = Type::PHOTO;
else if (value == "animated_gif") entity._type = Type::ANIMATED_GIF;
else if (value == "video") entity._type = Type::VIDEO;
else if (value == "multi_photo") entity._type = Type::MULTI_PHOTO;
else ofLogError("MediaEntity::fromJson") << "Unknown type: " << value;
}
else if (key == "video_info") entity._videoInfo = VideoInfo::fromJSON(value);
else if (key == "source_status_id") entity._sourceStatusID = value;
else if (key == "source_user_id") entity._sourceUserID = value;
else if (key == "url") entity._url = value;
else if (key == "display_url") entity._displayURL = value;
else if (key == "expanded_url") entity._expandedURL = value;
else if (key == "media_url") entity._mediaURL = value;
else if (key == "media_url_https") entity._secureMediaURL = value;
else if (key == "sizes") entity._sizes = _sizesFromJson(value);
else if (key == "id") entity._mediaID = value;
else if (key == "additional_media_info") entity._additionalMediaInfo = AdditionalMediaInfo::fromJSON(value);
else ofLogWarning("MediaEntity::fromJson") << "Unknown key: " << key << " : " << value.dump(4);
++iter;
}
return entity;
}
MediaEntity::Sizes MediaEntity::_sizesFromJson(const ofJson& json)
{
MediaEntity::Sizes sizes;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (key == "thumb")
{
auto size = MediaEntitySize::fromJson(value);
sizes.insert(std::make_pair(MediaEntitySize::Type::THUMB, size));
}
else if (key == "small")
{
auto size = MediaEntitySize::fromJson(value);
sizes.insert(std::make_pair(MediaEntitySize::Type::SMALL, size));
}
else if (key == "medium")
{
auto size = MediaEntitySize::fromJson(value);
sizes.insert(std::make_pair(MediaEntitySize::Type::MEDIUM, size));
}
else if (key == "large")
{
auto size = MediaEntitySize::fromJson(value);
sizes.insert(std::make_pair(MediaEntitySize::Type::LARGE, size));
}
else ofLogWarning("MediaEntity::_sizesFromJson") << "Unknown key: " << key;
++iter;
}
return sizes;
}
UserMentionEntity::UserMentionEntity()
{
}
UserMentionEntity::UserMentionEntity(std::size_t startIndex,
std::size_t endIndex,
int64_t id,
const std::string& screenName,
const std::string& name):
BaseIndexedEntity(startIndex, endIndex),
BaseNamedUser(id, screenName, name)
{
}
UserMentionEntity::~UserMentionEntity()
{
}
std::string UserMentionEntity::indexedText() const
{
return screenName();
}
UserMentionEntity UserMentionEntity::fromJson(const ofJson& json)
{
UserMentionEntity entity;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (Utils::endsWith(key, "_str")) { /* skip */ }
else if (key == "indices")
{
if (value.size() == 2)
{
entity._startIndex = value[0];
entity._endIndex = value[1];
}
else ofLogError("URLEntity::fromJson") << "Not two indices: " << value;
}
else if (key == "id") entity._id = value;
else if (key == "name") entity._name = value;
else if (key == "screen_name") entity._screenName = value;
else ofLogWarning("UserMentionEntity::fromJson") << "Unknown key: " << key;
++iter;
}
return entity;
}
Entities::Entities()
{
}
Entities::Entities(const HashTagEntities& hashTagEntities,
const SymbolEntities& symbolEntities,
const MediaEntities& mediaEntities,
const URLEntities& URLEntities,
const UserMentionEntities& userMentionEntities):
_hashTagEntities(hashTagEntities),
_symbolEntities(symbolEntities),
_mediaEntities(mediaEntities),
_URLEntities(URLEntities),
_userMentionEntities(userMentionEntities)
{
}
Entities::~Entities()
{
}
Entities::HashTagEntities Entities::hashTagEntities() const
{
return _hashTagEntities;
}
Entities::SymbolEntities Entities::symbolEntities() const
{
return _symbolEntities;
}
Entities::MediaEntities Entities::mediaEntities() const
{
return _mediaEntities;
}
Entities::URLEntities Entities::urlEntities() const
{
return _URLEntities;
}
Entities::UserMentionEntities Entities::userMentionEntities() const
{
return _userMentionEntities;
}
Entities Entities::fromJSON(const ofJson& json)
{
Entities entities;
auto iter = json.cbegin();
while (iter != json.cend())
{
const auto& key = iter.key();
const auto& value = iter.value();
if (key == "hashtags")
{
for (auto hashtag: value)
{
auto entity = HashTagEntity::fromJson(hashtag);
entities._hashTagEntities.push_back(entity);
}
}
else if (key == "symbols")
{
for (auto hashtag: value)
{
auto entity = SymbolEntity::fromJson(hashtag);
entities._symbolEntities.push_back(entity);
}
}
else if (key == "urls")
{
for (auto url: value)
{
auto entity = URLEntity::fromJson(url);
if (!entity.url().empty())
{
entities._URLEntities.push_back(entity);
}
}
}
else if (key == "url" || key == "description")
{
for (auto url: value["urls"])
{
auto entity = URLEntity::fromJson(url);
if (!entity.url().empty())
{
entities._URLEntities.push_back(entity);
}
}
}
else if (key == "user_mentions")
{
for (auto user: value)
{
auto entity = UserMentionEntity::fromJson(user);
entities._userMentionEntities.push_back(entity);
}
}
else if (key == "media")
{
for (auto media: value)
{
auto entity = MediaEntity::fromJson(media);
entities._mediaEntities.push_back(entity);
}
}
else ofLogWarning("Entities::fromJSON") << "Unknown key: " << key;
++iter;
}
return entities;
}
} } // namespace ofx::Twitter
| [
"me@christopherbaker.net"
] | me@christopherbaker.net |
0261bac3aa65f62afb10613529fd105b7209542a | 260e5dec446d12a7dd3f32e331c1fde8157e5cea | /Indi/SDK/Indi_Spell_PerkEffect_Resilient_2_classes.hpp | 4b3574fdfbbb2bfc2fa9acd4f5964b2c71d61037 | [] | no_license | jfmherokiller/TheOuterWorldsSdkDump | 6e140fde4fcd1cade94ce0d7ea69f8a3f769e1c0 | 18a8c6b1f5d87bb1ad4334be4a9f22c52897f640 | refs/heads/main | 2023-08-30T09:27:17.723265 | 2021-09-17T00:24:52 | 2021-09-17T00:24:52 | 407,437,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | hpp | #pragma once
// TheOuterWorlds SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "Indi_Spell_PerkEffect_Resilient_2_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Spell_PerkEffect_Resilient_2.Spell_PerkEffect_Resilient_1_C
// 0x0000 (0x01A0 - 0x01A0)
class USpell_PerkEffect_Resilient_1_C : public USpell
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Spell_PerkEffect_Resilient_2.Spell_PerkEffect_Resilient_1_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"peterpan0413@live.com"
] | peterpan0413@live.com |
63aacfc2f2e4f568890e6b6efafbaddd5ad82c68 | 5fdd476476fbaf3b6ea859691c3afcd17eab5001 | /Системное программирование/Win32Project - обработчик событий/Win32Project1/Win32Project1.cpp | 886525afddfc3e2969434febd9435ec78b7d1ab5 | [] | no_license | itstepP21014/PirozhnikDZ | 9c9e854a2a7cf757016161de982227e5fafcc6d8 | 94f52c304923bd6d2f47531592368135ab2c2541 | refs/heads/master | 2021-01-23T19:13:23.408395 | 2016-11-19T09:41:15 | 2016-11-19T09:41:15 | 27,079,112 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 5,854 | cpp | // Win32Project1.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "Win32Project1.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
// hook point - место где обрабатываются\перехватываются события
// hook chain - цепочка таких обработчиков
KBDLLHOOKSTRUCT kbdStruct; // структура для хранения инфы о собитии
HHOOK _hook; // хранит сам наш hook при событии
LRESULT __stdcall HookCallBack(int nCode, WPARAM wParam, LPARAM LParam)
{
if (nCode >= 0)
{
if (wParam == WM_KEYDOWN)
{
kbdStruct = *((KBDLLHOOKSTRUCT*)LParam);
if (kbdStruct.vkCode == VK_F1)
{
MessageBox(NULL, L"F1 is pressed!", L"la-la", MB_ICONINFORMATION);
}
}
}
return CallNextHookEx(_hook, nCode, wParam, LParam);
}
LRESULT __stdcall HookCallBack_2(int nCode, WPARAM wParam, LPARAM LParam)
{
if (nCode >= 0)
{
if (wParam == WM_KEYDOWN)
{
kbdStruct = *((KBDLLHOOKSTRUCT*)LParam);
if (kbdStruct.vkCode == VK_F2)
{
MessageBox(NULL, L"222", L"222", MB_ICONINFORMATION);
}
}
}
return CallNextHookEx(NULL, nCode, wParam, LParam);
}
void sethook()
{
_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallBack, NULL, 0);
//SetWindowsHookEx(WH_KEYBOARD_LL, HookCallBack_2, NULL, 0);
}
void ReleaseHook()
{
UnhookWindowsHookEx(_hook);
}
void WriteCounter(DWORD dwCounter) {
DWORD dwTemp;
HANDLE hFile = CreateFile(L"2.txt", GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == hFile) {
return;
}
WriteFile(hFile, &dwCounter, sizeof(dwCounter), &dwTemp, NULL);
CloseHandle(hFile);
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_WIN32PROJECT1, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32PROJECT1));
sethook();
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WIN32PROJECT1));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WIN32PROJECT1);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| [
"pirozhenka@yandex.ru"
] | pirozhenka@yandex.ru |
ceec6109664c8771797934415dd04741446fbf07 | 7926bafb7e46fca5ad0ff1a5ed4235746b51f086 | /src/cryptonote_core/cryptonote_tx_utils.cpp | 54d73cfe2f318b6fc8c7ae400b6312c42e336619 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | btmdteam/bitcoinmedal | 40253796139ed029832d2720d28a200e136407da | 7688ce1b30cf0a728bd590841b02c772b606e43f | refs/heads/master | 2020-04-10T10:22:36.919475 | 2018-12-08T17:53:55 | 2018-12-08T17:53:55 | 160,963,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,798 | cpp | // Copyrights(c) 2017-2018, The BitcoinMedal Project
// Copyrights(c) 2014-2017, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include "include_base_utils.h"
using namespace epee;
#include "cryptonote_tx_utils.h"
#include "cryptonote_config.h"
#include "cryptonote_basic/miner.h"
#include "crypto/crypto.h"
#include "crypto/hash.h"
#include "ringct/rctSigs.h"
namespace cryptonote
{
//---------------------------------------------------------------
bool construct_miner_tx(size_t height, size_t median_size, uint64_t already_generated_coins, size_t current_block_size, uint64_t fee, const account_public_address &miner_address, transaction& tx, const blobdata& extra_nonce, size_t max_outs, uint8_t hard_fork_version) {
tx.vin.clear();
tx.vout.clear();
tx.extra.clear();
keypair txkey = keypair::generate();
add_tx_pub_key_to_extra(tx, txkey.pub);
if(!extra_nonce.empty())
if(!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce))
return false;
txin_gen in;
in.height = height;
uint64_t block_reward;
if(!get_block_reward(median_size, current_block_size, already_generated_coins, block_reward, hard_fork_version))
{
LOG_PRINT_L0("Block is too big");
return false;
}
#if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
LOG_PRINT_L1("Creating block template: reward " << block_reward <<
", fee " << fee);
#endif
block_reward += fee;
// from hard fork 2, we cut out the low significant digits. This makes the tx smaller, and
// keeps the paid amount almost the same. The unpaid remainder gets pushed back to the
// emission schedule
// from hard fork 4, we use a single "dusty" output. This makes the tx even smaller,
// and avoids the quantization. These outputs will be added as rct outputs with identity
// masks, to they can be used as rct inputs.
if (hard_fork_version >= 2 && hard_fork_version < 4) {
block_reward = block_reward - block_reward % ::config::BASE_REWARD_CLAMP_THRESHOLD;
}
std::vector<uint64_t> out_amounts;
decompose_amount_into_digits(block_reward, hard_fork_version >= 2 ? 0 : ::config::DEFAULT_DUST_THRESHOLD,
[&out_amounts](uint64_t a_chunk) { out_amounts.push_back(a_chunk); },
[&out_amounts](uint64_t a_dust) { out_amounts.push_back(a_dust); });
CHECK_AND_ASSERT_MES(1 <= max_outs, false, "max_out must be non-zero");
if (height == 0 || hard_fork_version >= 4)
{
// the genesis block was not decomposed, for unknown reasons
while (max_outs < out_amounts.size())
{
//out_amounts[out_amounts.size() - 2] += out_amounts.back();
//out_amounts.resize(out_amounts.size() - 1);
out_amounts[1] += out_amounts[0];
for (size_t n = 1; n < out_amounts.size(); ++n)
out_amounts[n - 1] = out_amounts[n];
out_amounts.resize(out_amounts.size() - 1);
}
}
else
{
CHECK_AND_ASSERT_MES(max_outs >= out_amounts.size(), false, "max_out exceeded");
}
uint64_t summary_amounts = 0;
for (size_t no = 0; no < out_amounts.size(); no++)
{
crypto::key_derivation derivation = AUTO_VAL_INIT(derivation);;
crypto::public_key out_eph_public_key = AUTO_VAL_INIT(out_eph_public_key);
bool r = crypto::generate_key_derivation(miner_address.m_view_public_key, txkey.sec, derivation);
CHECK_AND_ASSERT_MES(r, false, "while creating outs: failed to generate_key_derivation(" << miner_address.m_view_public_key << ", " << txkey.sec << ")");
r = crypto::derive_public_key(derivation, no, miner_address.m_spend_public_key, out_eph_public_key);
CHECK_AND_ASSERT_MES(r, false, "while creating outs: failed to derive_public_key(" << derivation << ", " << no << ", "<< miner_address.m_spend_public_key << ")");
txout_to_key tk;
tk.key = out_eph_public_key;
tx_out out;
summary_amounts += out.amount = out_amounts[no];
out.target = tk;
tx.vout.push_back(out);
}
CHECK_AND_ASSERT_MES(summary_amounts == block_reward, false, "Failed to construct miner tx, summary_amounts = " << summary_amounts << " not equal block_reward = " << block_reward);
if (hard_fork_version >= HF_VERSION_ENABLE_RCT)
tx.version = 2;
else
tx.version = 1;
//lock
tx.unlock_time = height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW;
tx.vin.push_back(in);
tx.invalidate_hashes();
//LOG_PRINT("MINER_TX generated ok, block_reward=" << print_money(block_reward) << "(" << print_money(block_reward - fee) << "+" << print_money(fee)
// << "), current_block_size=" << current_block_size << ", already_generated_coins=" << already_generated_coins << ", tx_id=" << get_transaction_hash(tx), LOG_LEVEL_2);
return true;
}
//---------------------------------------------------------------
crypto::public_key get_destination_view_key_pub(const std::vector<tx_destination_entry> &destinations, const account_keys &sender_keys)
{
if (destinations.empty())
return null_pkey;
for (size_t n = 1; n < destinations.size(); ++n)
{
if (!memcmp(&destinations[n].addr, &sender_keys.m_account_address, sizeof(destinations[0].addr)))
continue;
if (destinations[n].amount == 0)
continue;
if (memcmp(&destinations[n].addr, &destinations[0].addr, sizeof(destinations[0].addr)))
return null_pkey;
}
return destinations[0].addr.m_view_public_key;
}
//---------------------------------------------------------------
bool construct_tx_and_get_tx_key(const account_keys& sender_account_keys, const std::vector<tx_source_entry>& sources, const std::vector<tx_destination_entry>& destinations, std::vector<uint8_t> extra, transaction& tx, uint64_t unlock_time, crypto::secret_key &tx_key, bool rct)
{
std::vector<rct::key> amount_keys;
tx.set_null();
amount_keys.clear();
tx.version = 1;
tx.unlock_time = unlock_time;
tx.extra = extra;
keypair txkey = keypair::generate();
remove_field_from_tx_extra(tx.extra, typeid(tx_extra_pub_key));
add_tx_pub_key_to_extra(tx, txkey.pub);
tx_key = txkey.sec;
// if we have a stealth payment id, find it and encrypt it with the tx key now
std::vector<tx_extra_field> tx_extra_fields;
if (parse_tx_extra(tx.extra, tx_extra_fields))
{
tx_extra_nonce extra_nonce;
if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
{
crypto::hash8 payment_id = null_hash8;
if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
{
LOG_PRINT_L2("Encrypting payment id " << payment_id);
crypto::public_key view_key_pub = get_destination_view_key_pub(destinations, sender_account_keys);
if (view_key_pub == null_pkey)
{
LOG_ERROR("Destinations have to have exactly one output to support encrypted payment ids");
return false;
}
if (!encrypt_payment_id(payment_id, view_key_pub, txkey.sec))
{
LOG_ERROR("Failed to encrypt payment id");
return false;
}
std::string extra_nonce;
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id);
remove_field_from_tx_extra(tx.extra, typeid(tx_extra_nonce));
if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce))
{
LOG_ERROR("Failed to add encrypted payment id to tx extra");
return false;
}
LOG_PRINT_L1("Encrypted payment ID: " << payment_id);
}
}
}
else
{
LOG_ERROR("Failed to parse tx extra");
return false;
}
struct input_generation_context_data
{
keypair in_ephemeral;
};
std::vector<input_generation_context_data> in_contexts;
uint64_t summary_inputs_money = 0;
//fill inputs
int idx = -1;
for(const tx_source_entry& src_entr: sources)
{
++idx;
if(src_entr.real_output >= src_entr.outputs.size())
{
LOG_ERROR("real_output index (" << src_entr.real_output << ")bigger than output_keys.size()=" << src_entr.outputs.size());
return false;
}
summary_inputs_money += src_entr.amount;
//key_derivation recv_derivation;
in_contexts.push_back(input_generation_context_data());
keypair& in_ephemeral = in_contexts.back().in_ephemeral;
crypto::key_image img;
if(!generate_key_image_helper(sender_account_keys, src_entr.real_out_tx_key, src_entr.real_output_in_tx_index, in_ephemeral, img))
return false;
//check that derivated key is equal with real output key
if( !(in_ephemeral.pub == src_entr.outputs[src_entr.real_output].second.dest) )
{
LOG_ERROR("derived public key mismatch with output public key at index " << idx << ", real out " << src_entr.real_output << "! "<< ENDL << "derived_key:"
<< string_tools::pod_to_hex(in_ephemeral.pub) << ENDL << "real output_public_key:"
<< string_tools::pod_to_hex(src_entr.outputs[src_entr.real_output].second) );
LOG_ERROR("amount " << src_entr.amount << ", rct " << src_entr.rct);
LOG_ERROR("tx pubkey " << src_entr.real_out_tx_key << ", real_output_in_tx_index " << src_entr.real_output_in_tx_index);
return false;
}
//put key image into tx input
txin_to_key input_to_key;
input_to_key.amount = src_entr.amount;
input_to_key.k_image = img;
//fill outputs array and use relative offsets
for(const tx_source_entry::output_entry& out_entry: src_entr.outputs)
input_to_key.key_offsets.push_back(out_entry.first);
input_to_key.key_offsets = absolute_output_offsets_to_relative(input_to_key.key_offsets);
tx.vin.push_back(input_to_key);
}
// "Shuffle" outs
std::vector<tx_destination_entry> shuffled_dsts(destinations);
std::random_shuffle(shuffled_dsts.begin(), shuffled_dsts.end(), [](unsigned int i) { return crypto::rand<unsigned int>() % i; });
uint64_t summary_outs_money = 0;
//fill outputs
size_t output_index = 0;
for(const tx_destination_entry& dst_entr: shuffled_dsts)
{
CHECK_AND_ASSERT_MES(dst_entr.amount > 0 || tx.version > 1, false, "Destination with wrong amount: " << dst_entr.amount);
crypto::key_derivation derivation;
crypto::public_key out_eph_public_key;
bool r = crypto::generate_key_derivation(dst_entr.addr.m_view_public_key, txkey.sec, derivation);
CHECK_AND_ASSERT_MES(r, false, "at creation outs: failed to generate_key_derivation(" << dst_entr.addr.m_view_public_key << ", " << txkey.sec << ")");
if (tx.version > 1)
{
crypto::secret_key scalar1;
crypto::derivation_to_scalar(derivation, output_index, scalar1);
amount_keys.push_back(rct::sk2rct(scalar1));
}
r = crypto::derive_public_key(derivation, output_index, dst_entr.addr.m_spend_public_key, out_eph_public_key);
CHECK_AND_ASSERT_MES(r, false, "at creation outs: failed to derive_public_key(" << derivation << ", " << output_index << ", "<< dst_entr.addr.m_spend_public_key << ")");
tx_out out;
out.amount = dst_entr.amount;
txout_to_key tk;
tk.key = out_eph_public_key;
out.target = tk;
tx.vout.push_back(out);
output_index++;
summary_outs_money += dst_entr.amount;
}
//check money
if(summary_outs_money > summary_inputs_money )
{
LOG_ERROR("Transaction inputs money ("<< summary_inputs_money << ") less than outputs money (" << summary_outs_money << ")");
return false;
}
// check for watch only wallet
bool zero_secret_key = true;
for (size_t i = 0; i < sizeof(sender_account_keys.m_spend_secret_key); ++i)
zero_secret_key &= (sender_account_keys.m_spend_secret_key.data[i] == 0);
if (zero_secret_key)
{
MDEBUG("Null secret key, skipping signatures");
}
if (tx.version == 1)
{
//generate ring signatures
crypto::hash tx_prefix_hash;
get_transaction_prefix_hash(tx, tx_prefix_hash);
std::stringstream ss_ring_s;
size_t i = 0;
for(const tx_source_entry& src_entr: sources)
{
ss_ring_s << "pub_keys:" << ENDL;
std::vector<const crypto::public_key*> keys_ptrs;
std::vector<crypto::public_key> keys(src_entr.outputs.size());
size_t ii = 0;
for(const tx_source_entry::output_entry& o: src_entr.outputs)
{
keys[ii] = rct2pk(o.second.dest);
keys_ptrs.push_back(&keys[ii]);
ss_ring_s << o.second.dest << ENDL;
++ii;
}
tx.signatures.push_back(std::vector<crypto::signature>());
std::vector<crypto::signature>& sigs = tx.signatures.back();
sigs.resize(src_entr.outputs.size());
if (!zero_secret_key)
crypto::generate_ring_signature(tx_prefix_hash, boost::get<txin_to_key>(tx.vin[i]).k_image, keys_ptrs, in_contexts[i].in_ephemeral.sec, src_entr.real_output, sigs.data());
ss_ring_s << "signatures:" << ENDL;
std::for_each(sigs.begin(), sigs.end(), [&](const crypto::signature& s){ss_ring_s << s << ENDL;});
ss_ring_s << "prefix_hash:" << tx_prefix_hash << ENDL << "in_ephemeral_key: " << in_contexts[i].in_ephemeral.sec << ENDL << "real_output: " << src_entr.real_output << ENDL;
i++;
}
MCINFO("construct_tx", "transaction_created: " << get_transaction_hash(tx) << ENDL << obj_to_json_str(tx) << ENDL << ss_ring_s.str());
}
else
{
size_t n_total_outs = sources[0].outputs.size(); // only for non-simple rct
// the non-simple version is slightly smaller, but assumes all real inputs
// are on the same index, so can only be used if there just one ring.
bool use_simple_rct = sources.size() > 1;
if (!use_simple_rct)
{
// non simple ringct requires all real inputs to be at the same index for all inputs
for(const tx_source_entry& src_entr: sources)
{
if(src_entr.real_output != sources.begin()->real_output)
{
LOG_ERROR("All inputs must have the same index for non-simple ringct");
return false;
}
}
// enforce same mixin for all outputs
for (size_t i = 1; i < sources.size(); ++i) {
if (n_total_outs != sources[i].outputs.size()) {
LOG_ERROR("Non-simple ringct transaction has varying ring size");
return false;
}
}
}
uint64_t amount_in = 0, amount_out = 0;
rct::ctkeyV inSk;
// mixRing indexing is done the other way round for simple
rct::ctkeyM mixRing(use_simple_rct ? sources.size() : n_total_outs);
rct::keyV destinations;
std::vector<uint64_t> inamounts, outamounts;
std::vector<unsigned int> index;
for (size_t i = 0; i < sources.size(); ++i)
{
rct::ctkey ctkey;
amount_in += sources[i].amount;
inamounts.push_back(sources[i].amount);
index.push_back(sources[i].real_output);
// inSk: (secret key, mask)
ctkey.dest = rct::sk2rct(in_contexts[i].in_ephemeral.sec);
ctkey.mask = sources[i].mask;
inSk.push_back(ctkey);
// inPk: (public key, commitment)
// will be done when filling in mixRing
}
for (size_t i = 0; i < tx.vout.size(); ++i)
{
destinations.push_back(rct::pk2rct(boost::get<txout_to_key>(tx.vout[i].target).key));
outamounts.push_back(tx.vout[i].amount);
amount_out += tx.vout[i].amount;
}
if (use_simple_rct)
{
// mixRing indexing is done the other way round for simple
for (size_t i = 0; i < sources.size(); ++i)
{
mixRing[i].resize(sources[i].outputs.size());
for (size_t n = 0; n < sources[i].outputs.size(); ++n)
{
mixRing[i][n] = sources[i].outputs[n].second;
}
}
}
else
{
for (size_t i = 0; i < n_total_outs; ++i) // same index assumption
{
mixRing[i].resize(sources.size());
for (size_t n = 0; n < sources.size(); ++n)
{
mixRing[i][n] = sources[n].outputs[i].second;
}
}
}
// fee
if (!use_simple_rct && amount_in > amount_out)
outamounts.push_back(amount_in - amount_out);
// zero out all amounts to mask rct outputs, real amounts are now encrypted
for (size_t i = 0; i < tx.vin.size(); ++i)
{
if (sources[i].rct)
boost::get<txin_to_key>(tx.vin[i]).amount = 0;
}
for (size_t i = 0; i < tx.vout.size(); ++i)
tx.vout[i].amount = 0;
crypto::hash tx_prefix_hash;
get_transaction_prefix_hash(tx, tx_prefix_hash);
rct::ctkeyV outSk;
if (use_simple_rct)
tx.rct_signatures = rct::genRctSimple(rct::hash2rct(tx_prefix_hash), inSk, destinations, inamounts, outamounts, amount_in - amount_out, mixRing, amount_keys, index, outSk);
else
tx.rct_signatures = rct::genRct(rct::hash2rct(tx_prefix_hash), inSk, destinations, outamounts, mixRing, amount_keys, sources[0].real_output, outSk); // same index assumption
CHECK_AND_ASSERT_MES(tx.vout.size() == outSk.size(), false, "outSk size does not match vout");
MCINFO("construct_tx", "transaction_created: " << get_transaction_hash(tx) << ENDL << obj_to_json_str(tx) << ENDL);
}
tx.invalidate_hashes();
return true;
}
//---------------------------------------------------------------
bool construct_tx(const account_keys& sender_account_keys, const std::vector<tx_source_entry>& sources, const std::vector<tx_destination_entry>& destinations, std::vector<uint8_t> extra, transaction& tx, uint64_t unlock_time)
{
crypto::secret_key tx_key;
return construct_tx_and_get_tx_key(sender_account_keys, sources, destinations, extra, tx, unlock_time, tx_key);
}
//---------------------------------------------------------------
bool generate_genesis_block(
block& bl
, std::string const & genesis_tx
, uint32_t nonce
)
{
//genesis block
bl = boost::value_initialized<block>();
account_public_address ac = boost::value_initialized<account_public_address>();
std::vector<size_t> sz;
construct_miner_tx(0, 0, 0, 0, 0, ac, bl.miner_tx); // zero fee in genesis
blobdata txb = tx_to_blob(bl.miner_tx);
std::string hex_tx_represent = string_tools::buff_to_hex_nodelimer(txb);
std::string genesis_coinbase_tx_hex = genesis_tx;
blobdata tx_bl;
string_tools::parse_hexstr_to_binbuff(genesis_coinbase_tx_hex, tx_bl);
bool r = parse_and_validate_tx_from_blob(tx_bl, bl.miner_tx);
CHECK_AND_ASSERT_MES(r, false, "failed to parse coinbase tx from hard coded blob");
bl.major_version = CURRENT_BLOCK_MAJOR_VERSION;
bl.minor_version = CURRENT_BLOCK_MINOR_VERSION;
bl.timestamp = 0;
bl.nonce = nonce;
miner::find_nonce_for_given_block(bl, 1, 0);
bl.invalidate_hashes();
return true;
}
//---------------------------------------------------------------
}
| [
"btmdteam@gmail.com"
] | btmdteam@gmail.com |
737b8d7bf652de7c6220777eb2df8d60f13a53cf | 94bd295572de3f4934a3896ce1bb882fb4d35edc | /ash/shell/example_session_controller_client.h | 1cdbd2f8343d5fc034a5996a9fd3421145bd1756 | [
"BSD-3-Clause"
] | permissive | WebGameLinux/chromium | 06109b62d6019b051474cd479f3d577e0eec4463 | a35a1e2ce2ab74eccc467aa390eda1a8e29e3e09 | refs/heads/master | 2023-03-07T14:07:56.342758 | 2017-04-08T02:33:08 | 2017-04-08T03:38:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_SHELL_EXAMPLE_SESSION_CONTROLLER_CLIENT_H_
#define ASH_SHELL_EXAMPLE_SESSION_CONTROLLER_CLIENT_H_
#include "ash/common/test/test_session_controller_client.h"
#include "base/macros.h"
namespace ash {
class SessionController;
namespace shell {
class ExampleSessionControllerClient
: public test::TestSessionControllerClient {
public:
explicit ExampleSessionControllerClient(SessionController* controller);
~ExampleSessionControllerClient() override;
static ExampleSessionControllerClient* Get();
void Initialize();
// TestSessionControllerClient
void RequestLockScreen() override;
void UnlockScreen() override;
private:
DISALLOW_COPY_AND_ASSIGN(ExampleSessionControllerClient);
};
} // namespace shell
} // namespace ash
#endif // ASH_SHELL_EXAMPLE_SESSION_CONTROLLER_CLIENT_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
911d84568996387472cb8ceca5ce577dea38c312 | bec0383f2afd255a72afeb9049a898615e547327 | /src/test/fuzz/message.cpp | 3aaddd8547f0075fbe40bf850ee922ffcb9c1924 | [
"MIT"
] | permissive | Bitcoin-ABC/bitcoin-abc | a73024a513be2c9c419f8bece06dbadde2af3fb7 | 57176a00e4d660487c41b92207da4bf27e5c0026 | refs/heads/master | 2023-09-04T11:26:24.295624 | 2023-09-01T14:24:40 | 2023-09-04T05:20:03 | 89,913,655 | 1,359 | 768 | MIT | 2023-07-19T16:41:26 | 2017-05-01T09:58:15 | C++ | UTF-8 | C++ | false | false | 2,276 | cpp | // Copyright (c) 2020 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 <chainparams.h>
#include <config.h>
#include <key_io.h>
#include <util/message.h>
#include <util/strencodings.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <cassert>
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
void initialize() {
static const ECCVerifyHandle ecc_verify_handle;
ECC_Start();
SelectParams(CBaseChainParams::REGTEST);
}
void test_one_input(const std::vector<uint8_t> &buffer) {
const Config &config = GetConfig();
const CChainParams &chainparams = config.GetChainParams();
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const std::string random_message =
fuzzed_data_provider.ConsumeRandomLengthString(1024);
{
const std::vector<uint8_t> random_bytes =
ConsumeRandomLengthByteVector(fuzzed_data_provider);
CKey private_key;
private_key.Set(random_bytes.begin(), random_bytes.end(),
fuzzed_data_provider.ConsumeBool());
std::string signature;
const bool message_signed =
MessageSign(private_key, random_message, signature);
if (private_key.IsValid()) {
assert(message_signed);
const MessageVerificationResult verification_result = MessageVerify(
chainparams,
EncodeDestination(PKHash(private_key.GetPubKey().GetID()),
config),
signature, random_message);
assert(verification_result == MessageVerificationResult::OK);
}
}
{
(void)MessageHash(random_message);
(void)MessageVerify(
chainparams, fuzzed_data_provider.ConsumeRandomLengthString(1024),
fuzzed_data_provider.ConsumeRandomLengthString(1024),
random_message);
(void)SigningResultString(fuzzed_data_provider.PickValueInArray(
{SigningResult::OK, SigningResult::PRIVATE_KEY_NOT_AVAILABLE,
SigningResult::SIGNING_FAILED}));
}
}
| [
"fabcien@gmail.com"
] | fabcien@gmail.com |
d982735413a93d810139ccbea4b1e94afd3a1e22 | 11856d165da17c57f463754092c90d50b7ef2bb6 | /src/Mapper.h | 33d7357b48bee45353071c6fe3b3d017b78f7ef0 | [] | no_license | dempo93/png-mapper | a792e32ba1ec16fd51ad0d5ec3900af65d2b580e | 08e04cef1708841f70d0737297a0b7198d1eb7da | refs/heads/master | 2020-04-21T13:57:26.502985 | 2019-02-10T18:29:11 | 2019-02-10T18:29:11 | 169,618,175 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | //
// Created by simone on 10.02.19.
//
#ifndef PNG_MAPPER_MAPPER_H
#define PNG_MAPPER_MAPPER_H
#include <memory>
#include "Png.h"
#include "Io.h"
class Mapper
{
public:
static void HankaSimoneTransformation(double scale, const std::filesystem::path& input,
const std::filesystem::path& output);
private:
explicit Mapper(std::unique_ptr<Png>& input_png);
std::unique_ptr<Png> map(double scale);
std::unique_ptr<Png> input_png;
std::unique_ptr<Png> output_png;
double scale{1.f};
ulong get_transformed_pixel_index(ulong pixel_index) const;
void transform_pixel_coords(Vector2& vec) const;
void copy_pixel_data(ulong pixel_index, ulong output_pixel_index) const;
};
#endif // PNG_MAPPER_MAPPER_H
| [
"sdp@3yourmind.com"
] | sdp@3yourmind.com |
b6cf34d7ffacf447f527ac5a83ee1d78f9788652 | c401c09363701619100a6b99bfa9543417c9e20c | /Linear DS/stack_using_array.cpp | b806c798942f2ff0782e0af4b55e090cdd62222c | [] | no_license | ksatyendra/DS-Algo | 22a2b6c975268c697048ad761c86b030a3f0b444 | 0b6673ce8d60b3d41a45b0dbeaf014cdb6095686 | refs/heads/master | 2020-04-10T10:15:52.594044 | 2018-12-08T17:08:34 | 2018-12-08T17:08:34 | 160,960,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,556 | cpp | #include<iostream>
#include<conio.h>
using namespace std;
int *a;
int top,n;
bool isempty()
{
if(top==-1)
{
cout<<"\nStack is EMPTY!\n";
return true;
}
return false;
}
bool isfull()
{
if(top==n-1)
{
cout<<"\nStack is FULL!\n";
return true;
}
return false;
}
void display()
{
if(!isempty())
{
cout<<"\nStack is : ";
for(int i=0;i<=top;i++)
cout<<a[i]<<" ";
}
}
void push()
{
if(!isfull())
{
cout<<"\nEnter element to push : ";
cin>>a[++top];
display();
}
}
void pop()
{
if(!isempty())
{
cout<<"\nPopped element : "<<a[top--]<<endl;
display();
}
}
int main()
{
int ch=1;
top=-1;
cout<<"Enter no. of elements to initialize the stack : ";
cin>>n;
a=new int[n];
while(ch)
{
cout<<"\n\nOptions :\n=>1 to Display the Stack\n=>2 to Find the current status ofStack\n=>3 to Push an element in Stack\n=>4 to Pop an element from Stack\n";
cout<<"=>5 to check if Stack is Empty\n=>6 to check if Stack is Full\n=>0 to Terminate the Program\n\nEnter choice from above options : ";
cin>>ch;
if(!ch)
break;
else if(ch==1)
display();
else if(ch==2)
cout<<"\nStack has "<<top+1<<"elements.\nAnd current position of Top is "<<top<<endl;
else if(ch==3)
push();
else if(ch==4)
pop();
else if(ch==5)
{
if(!isempty())
cout<<"\nStack is not Empty.\n";
}
else if(ch==6)
{
if(!isfull())
cout<<"\nStack is not Full.\n";
}
else
cout<<"*\nWRONG CHOICE! Try Again...*\n";
}
return 0;
}
| [
"ksatyendra218@gmail.com"
] | ksatyendra218@gmail.com |
5db1a23400a828c822f106e21faca6613c8be3ca | 5789692527454dbafd354ab496522c0615beb6bf | /Diem.h | 032222ceb3989dcee51f2c8bd59761aa8e86ff40 | [] | no_license | nhatquan1702/ThiTracNghiem | aadb43f28071b60e71a32ee43e051154e98a1635 | 04a710a829e60aac4239845f3d3098d5a8728896 | refs/heads/master | 2022-12-05T23:26:37.545296 | 2020-08-24T15:06:56 | 2020-08-24T15:06:56 | 289,959,046 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | h | #ifndef DIEM_H
#define DIEM_H
#include "MyFunction.h"
class Diem
{
public:
Diem();
void inMaMH();
void inD();
void inDiem();
void setMaMH(char ma[]);
void setDiem(float d);
float getDiem();
char *getMaMH();
void setDiemNext(Diem* d);
Diem* getDiemNext();
private:
char maMh[size_ma];
float diem;
Diem* diemNext;
};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
06043d1e0dac5774e968c241e635c8b8f2bbbed2 | 976879c57fdc14ca8c3aa02dc87e8a165889e4c0 | /cs211/hw9.cpp | c7555b1a1dec3f7045dad574cf9a82c2b8dbc296 | [] | no_license | avanwest/C-plus-plus | 18c126f9a48a5f7b01a963d9a34f2136bb4b8850 | 2068d03dc91f960d6734b25182d276c49591b13a | refs/heads/master | 2021-02-09T01:06:40.558056 | 2020-03-01T23:03:12 | 2020-03-01T23:03:12 | 244,220,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | cpp | // Adam vanWestrienen
// HW#9 - Integration
#include <iostream>
using namespace std;
typedef double (*FUNC)(double);
double integrate(FUNC f, double a, double b);
double line(double x);
double square(double x);
double cube(double x);
int main() {
cout << "The integral of f(x)=x between 1 and 5 is: " << integrate(line, 1, 5) << endl;
cout << "The integral of f(x)=x^2 between 1 and 5 is: " << integrate(square, 1, 5) << endl;
cout << "The integral of f(x)=x^3 between 1 and 5 is: " << integrate(cube, 1, 5) << endl;
}
double integrate(FUNC f, double a, double b) {
double sum;
for (double i = a; i <= b; i += 0.0001) {
sum = sum + (0.0001 * f(i));
}
return sum;
}
double line(double x){
return x;
}
double square(double x){
return x*x;
}
double cube(double x){
return x*x*x;
} | [
"noreply@github.com"
] | noreply@github.com |
9aeeed9e5dcf6008a4b08cd22d63a2d56bd74afc | d56dce868785cdfb0414fc65311f7897c29570e6 | /面向对象四则运算/面向对象四则运算/allclass.cpp | b46e364a9c65057528c27752ae3c033119d05fb1 | [] | no_license | LineseWorld/ExerciseProgram | 8e56dc694209a9aab2b3c6f888aa0a6f9052b889 | 637a343a749ad51fad3b3f221de05d3994675a1d | refs/heads/master | 2022-12-22T11:53:36.641726 | 2017-06-13T13:29:42 | 2017-06-13T13:29:42 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,490 | cpp | #include "allclass.h"
template <class T>
void StackClear(stack<T> &s) //清空栈
{
while (!s.empty())
s.pop();
}
int expresses::IsOperator(char c)//判断是否为运算符
{
switch (c)
{
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
case '=':
return 1;
break;
default:
return 0;
break;
}
}
int expresses::Priority(char oper1, char oper2)
{
int pri;
switch (oper2)
{
case '+':
case '-':
if (oper1 == '(' || oper1 == '=')
pri = -1;
else
pri = 1;
break;
case '*':
case '/':
if (oper1 == '*' || oper1 == '/' || oper1 == ')')
pri = 1;
else
pri = -1;
break;
case '('://优先级小
pri = -1;
break;
case ')':
if (oper1 == '(')
pri = 0; //左右括号配对
else
pri = 1;
break;
case '=':
if (oper1 == '=')
pri = 0; //等号配对,返回0
else
pri = 1;
break;
}
return pri;
}
double expresses::calculate(double a, int oper, double b)
{
switch (oper)
{
case '+':return a + b;
case '-':return a - b;
case '*':return a * b;
case '/':
if (b != 0)
return a / b;
else
return 0.1;
}
return 0;
}
double expresses::calculateResult(char * express)
{
double a, b; //两个操作数
char opera; //运算符
char c; //字符变量
char x = ' '; //x用来获取运算符栈栈顶的运算符
stack<char> oper;
stack<double> data; //运算符栈栈顶的运算符,操作数栈
int j = 0;
int i = 0;
oper.push('='); //先将定界符(=)推入操作符栈
c = express[i++];
double num = 0;
while (c != '=' || x != '=') //循环处理表达式中的每个字符
{
if (IsOperator(c)) //若是运算符
{
num = 0; //入栈之后清空某一个操作数的暂存值
switch (Priority(x, c))
{
case -1: //当前运算符c大于前一运算符x
//cout << "o----" << c << endl;
oper.push(c); //当前运算符进栈
c = express[i++]; //取表达式下一字符
break;
case 0: //括号(等号)配对
oper.pop(); //运算符左半部分出栈(抛弃)
c = express[i++]; //取表达式下一字符
break;
case 1: //当前运算符c小于等于前一运算符x
opera = oper.top(); //出栈之前取得栈顶元素
oper.pop(); //运算符出栈
b = data.top();
data.pop();
a = data.top();
data.pop(); //两个操作数出栈
double t = calculate(a, opera, b); //计算结果
if (t != (int)t) //解决除0再乘零的情况
return 0.1;
else
data.push(t); //将结算结果入栈
break;
}
}
else if (c >= '0' && c <= '9') //若输入的是数字字符 入栈
{
num = c - '0';
data.push(num);
c = express[i++];
}
x = oper.top(); //获取运算符栈顶的元素
}
num = data.top();
StackClear(oper);
StackClear(data); //清空两个栈
return num; //返回数字栈栈顶元素,即为计算结果
}
bool expresses::IsInt(double answer)
{
if (answer == (int)answer) return true;
else return false;
}
char * expresses:: generateExpression()
{
RandomFactory * fptr = new RandomFactory();
srand((unsigned)time(NULL));//不出现相同的随机数
for (int i = 0; i < 4; i++)
{
Random * rand_ptr = fptr->produce(1);
a[i] = rand_ptr->get_rand(rand_ptr->create());
delete rand_ptr;
}
for (int i = 0; i < 3; i++)
{
Random * rand_ptr = fptr->produce(2);
o[i] = rand_ptr->get_rand(rand_ptr->create());
delete rand_ptr;
}
int casenum;//有无括号的随机情况
char * express = new char[18];//表达式
for (int j = 0; j<15; j++)
{
express[j] = '\0';
}
casenum = rand() % 6;//六种情况
switch (casenum)
{
case 0://无括号情况
express[0] = a[0];
express[1] = o[0];
express[2] = a[1];
express[3] = o[1];
express[4] = a[2];
express[5] = o[2];
express[6] = a[3];
express[7] = '=';
break;
case 1://(a o1 b)o2 c o3 g = ?
express[0] = '(';
express[1] = a[0];
express[2] = o[0];
express[3] = a[1];
express[4] = ')';
express[5] = o[1];
express[6] = a[2];
express[7] = o[2];
express[8] = a[3];
express[9] = '='; break;
case 2://(a o1 b o2 c) o3 d = ?
express[0] = '(';
express[1] = a[0];
express[2] = o[0];
express[3] = a[1];
express[4] = o[1];
express[5] = a[2];
express[6] = ')';
express[7] = o[2];
express[8] = a[3];
express[9] = '=';
break;
case 3://a o1 ( b o2 c) o3 d = ?
express[0] = a[0];
express[1] = o[0];
express[2] = '(';
express[3] = a[1];
express[4] = o[1];
express[5] = a[2];
express[6] = ')';
express[7] = o[2];
express[8] = a[3];
express[9] = '=';
break;
case 4://a o1 (b o2 c o3 d) = ?
express[0] = a[0];
express[1] = o[0];
express[2] = '(';
express[3] = a[1];
express[4] = o[1];
express[5] = a[2];
express[6] = o[2];
express[7] = a[3];
express[8] = ')';
express[9] = '=';
break;
default://a o1 b o2 (c o3 d) =?
express[0] = a[0];
express[1] = o[0];
express[2] = a[1];
express[3] = o[1];
express[4] = '(';
express[5] = a[2];
express[6] = o[2];
express[7] = a[3];
express[8] = ')';
express[9] = '=';
}
return express;
}
void Language::set(char c)
{
language = c;
Choose(1);
}
void Language::scanf() {
cout << "请选择语言类:" << endl;
cout << "C.中文 E.英语 J.日语 F.法语 G.德语" << endl;
}
void Language::scanf2(char * p, int i)
{
cout << i + 1 << ". " << p;
}
void Language::Choose(int a)
{
string s;
int sb;
//ifstream inf; //读取文件
if (language == 'C')
inf.open("e://CAL//Chinese.txt");//语言资源路径
if (language == 'E')
inf.open("e://CAL//English.txt");
if (language == 'J')
inf.open("e://CAL//Japanese.txt");
if (language == 'F')
inf.open("e://CAL//French.txt");
if (language == 'G')
inf.open("e://CAL//German.txt");
switch (a)//判断需输出的文本行
{
case 1: getline(inf, s, '\n');
cout << s << endl;
getline(inf, s, '\n');
cout << s << endl;
getline(inf, s, '\n');
cout << s;
break;
case 2: for (sb = 0; sb<4; sb++)
getline(inf, s, '\n');
cout << s;
break;
case 3: for (sb = 0; sb<5; sb++)
getline(inf, s, '\n');
cout << s << endl;
break;
case 4: for (sb = 0; sb<6; sb++)
getline(inf, s, '\n');
cout << s;
break;
}
inf.close();//关闭文件
}
void Language::print(double r, double sum)
{
Choose(4);
cout << r / sum << endl;
}
void R_and_W::set(double ans )
{
inputanswer = ans;
}
int R_and_W::readFile(char * s)
{
fin.open(s, ios::in);
int n;
fin >> n;
fin.close();
return n;
}
void R_and_W::writeFile1(char *s, char * p, double rans, double inans)
{
fout.open(s, ios::app);
fout << "表达式:" << p << endl;
fout << "正确答案:" << rans << endl;
fout << "输入的答案:" << inans << endl << endl;
fout.close();
}
void R_and_W::writeFile2(char *s,double right)
{
fout.open(s, ios::app);
fout << "\n以上总题数为: " << n << endl;
fout << "答对题数:" << right << endl;
fout << "正确率为:" << right / n << endl << endl;
fout.close();
}
int R_and_W::Countright(double answers,double inputanswer,Language &l)
{
if (inputanswer == answers)
{
l.Choose(3);
return 1;
}
else
{
l.Choose(2);
cout << answers << endl;
return 0;
}
}
int randomNumber::create()
{
return rand() % 10;
}
int randomOperator::create()
{
return rand() % 4;
}
char randomOperator::get_rand(int k)
{
switch (k)
{
case 0:return '+';
case 1:return '-';
case 2:return '*';
case 3:return '/';
default:return ' ';
}
}
char randomNumber::get_rand(int k)
{
return k + 48;
} | [
"1076452761@qq.com"
] | 1076452761@qq.com |
319e389c8f811281ab9abb538d35b38fa0e3646d | e36e8f998e14711fedb616818587fdd19e5061f5 | /v1.0/module/lz_db/src/daotunnel.cpp | f8e2b58a26bedf51fbd488c249811492d18559a3 | [] | no_license | fanxiang090909/Railway-Tunnel-Construction-Dlearance-Measure-LanZhou | af07dbbccbc563da2f91a0aba11a564fded525f9 | 745e3049839be0532bc1214bf494730d2c7df156 | refs/heads/master | 2016-09-10T13:37:05.093754 | 2015-11-22T10:04:02 | 2015-11-22T10:04:02 | 38,955,294 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 12,845 | cpp | #include <QStandardItemModel>
#include <QStringListModel>
#include <QSqlQuery>
#include <QDebug>
#include "daotunnel.h"
#include "daoline.h"
/**
* 隧道数据访问对象类实现
*
* @author fanxiang
* @version 1.0.0
* @date 2013-8-8
*/
// singleton设计模式,静态私有实例变量
TunnelDAO * TunnelDAO::tunnelDAOInstance = NULL;
/**
* singleton设计模式,公有静态方法返回单一实例
* @return 单一实例
*/
TunnelDAO * TunnelDAO::getTunnelDAOInstance()
{
if (tunnelDAOInstance == NULL)
{
tunnelDAOInstance = new TunnelDAO();
}
return tunnelDAOInstance;
}
// singleton单一设计模式,构造函数私有
TunnelDAO::TunnelDAO(QObject *parent) : QObject(parent)
{
tunnelsModel = new QSqlRelationalTableModel(this);
tunnelsModel_2 = new QSqlRelationalTableModel(this);
tunnelNamesModel = new QStringListModel(this);
exactTunnelModel = new QSqlQueryModel(this);
}
TunnelDAO::~TunnelDAO()
{
delete tunnelsModel;
delete tunnelsModel_2;
delete tunnelNamesModel;
delete exactTunnelModel;
}
/**
* 根据隧道ID得到隧道名
*/
QString TunnelDAO::getOneTunnelName(int tunnelid)
{
QSqlQuery query;
query.exec(QObject::tr("SELECT DISTINCT t.tunnel_name_std "
"FROM tunnel t WHERE t.tunnel_id = %1 ").arg(tunnelid));
QStringList strings;
while (query.next()) {
return query.value(0).toString();
}
return "";
}
/**
* 某一线路上的隧道模型,排序
*/
QSqlRelationalTableModel * TunnelDAO::getTunnels(int lineid)
{
tunnelsModel->setTable("tunnel");
tunnelsModel->setRelation(Tunnel_line_ID,
QSqlRelation("railway_line", "line_id", "line_name_std"));
// 【注意】!!!
// 当使用了SqlRelationalTableModel的setRelation()后,再使用setFilter时就要注意了,
// 因为SqlRelationalTableModel类中已经包含了多张表,所以在写过滤规则时,必须加上表名
tunnelsModel->setFilter(QString("tunnel.line_id = %1 AND tunnel.is_valid = TRUE").arg(lineid));
tunnelsModel->setSort(Tunnel_start_point_std, Qt::AscendingOrder);
tunnelsModel->setHeaderData(Tunnel_ID, Qt::Horizontal, tr("隧道ID"));
tunnelsModel->setHeaderData(Tunnel_name_std, Qt::Horizontal, tr("隧道名称"));
tunnelsModel->setHeaderData(Tunnel_is_valid, Qt::Horizontal, tr("是否被删除作废"));
tunnelsModel->setHeaderData(Tunnel_ID_std, Qt::Horizontal, tr("隧道编号"));
tunnelsModel->setHeaderData(Tunnel_start_point_std, Qt::Horizontal, tr("起始里程"));
tunnelsModel->setHeaderData(Tunnel_end_point_std, Qt::Horizontal, tr("终止里程"));
tunnelsModel->setHeaderData(Tunnel_is_new_std, Qt::Horizontal, tr("是否为新线"));
tunnelsModel->setHeaderData(Tunnel_line_type_std, Qt::Horizontal, tr("线路类型"));
tunnelsModel->setHeaderData(Tunnel_is_double_line, Qt::Horizontal, tr("是否为双线"));
tunnelsModel->setHeaderData(Tunnel_is_downlink, Qt::Horizontal, tr("是否为下行(双线)"));
tunnelsModel->setHeaderData(Tunnel_line_ID, Qt::Horizontal, tr("所在线路"));
tunnelsModel->setHeaderData(Tunnel_is_bridge, Qt::Horizontal, tr("是否是桥梁"));
tunnelsModel->select();
return tunnelsModel;
}
/**
* 【只为上层需要提供】与上面函数指向两个不同的地址空间
* 某一线路上的隧道模型,排序
*/
QSqlRelationalTableModel * TunnelDAO::getTunnels_CannotModify(int lineid) const
{
tunnelsModel_2->setTable("tunnel");
tunnelsModel_2->setRelation(Tunnel_line_ID,
QSqlRelation("railway_line", "line_id", "line_name_std"));
// 【注意】!!!
// 当使用了SqlRelationalTableModel的setRelation()后,再使用setFilter时就要注意了,
// 因为SqlRelationalTableModel类中已经包含了多张表,所以在写过滤规则时,必须加上表名
tunnelsModel_2->setFilter(QString("tunnel.line_id = %1 AND tunnel.is_valid = TRUE").arg(lineid));
tunnelsModel_2->setSort(Tunnel_start_point_std, Qt::AscendingOrder);
tunnelsModel_2->setHeaderData(Tunnel_ID, Qt::Horizontal, tr("隧道ID"));
tunnelsModel_2->setHeaderData(Tunnel_name_std, Qt::Horizontal, tr("隧道名称"));
tunnelsModel_2->setHeaderData(Tunnel_is_valid, Qt::Horizontal, tr("是否被删除作废"));
tunnelsModel_2->setHeaderData(Tunnel_ID_std, Qt::Horizontal, tr("隧道编号"));
tunnelsModel_2->setHeaderData(Tunnel_start_point_std, Qt::Horizontal, tr("起始里程"));
tunnelsModel_2->setHeaderData(Tunnel_end_point_std, Qt::Horizontal, tr("终止里程"));
tunnelsModel_2->setHeaderData(Tunnel_is_new_std, Qt::Horizontal, tr("是否为新线"));
tunnelsModel_2->setHeaderData(Tunnel_line_type_std, Qt::Horizontal, tr("线路类型"));
tunnelsModel_2->setHeaderData(Tunnel_is_double_line, Qt::Horizontal, tr("是否为双线"));
tunnelsModel_2->setHeaderData(Tunnel_is_downlink, Qt::Horizontal, tr("是否为下行(双线)"));
tunnelsModel_2->setHeaderData(Tunnel_line_ID, Qt::Horizontal, tr("所在线路"));
tunnelsModel_2->setHeaderData(Tunnel_is_bridge, Qt::Horizontal, tr("是否是桥梁"));
tunnelsModel_2->select();
return tunnelsModel_2;
}
/**
* 某一线路上的隧道名称,排序
*/
QStringListModel * TunnelDAO::getTunnelNames(int lineid)
{
QSqlQuery query;
query.exec(QObject::tr("SELECT DISTINCT t.tunnel_name_std "
"FROM tunnel t WHERE t.line_id = %1 "
"WHERE t.is_valid = TRUE "
"ORDER BY t.start_point_std ASC").arg(lineid));
QStringList strings;
while (query.next()) {
QString line = query.value(0).toString();
strings << line;
}
tunnelNamesModel->setStringList(strings);
return tunnelNamesModel;
}
/**
* 判断是否为桥梁
*/
bool TunnelDAO::getTunnelIsBriage(int tunnelid)
{
QSqlQuery query;
query.exec(QObject::tr("SELECT t.is_bridge "
"FROM tunnel t WHERE t.tunnel_id = %1").arg(tunnelid));
while (query.next()) {
bool isbridge = query.value(0).toBool();
return isbridge;
}
return false;
}
/**
* 某条隧道
* @param tunnelid 隧道ID
*/
QSqlQueryModel * TunnelDAO::getExactTunnel(int tunnelid)
{
QSqlQuery query;
bool ret = query.exec(QObject::tr("SELECT t.*, l.line_name_std, ss.station_name_std AS start_station, se.station_name_std AS end_station FROM tunnel t "
"JOIN railway_line l ON t.line_id = l.line_id "
"JOIN railway_station ss ON l.start_station_id = ss.station_id "
"JOIN railway_station se ON l.end_station_id = se.station_id "
"WHERE t.tunnel_id = %1 AND t.is_valid = true AND l.is_valid = true").arg(tunnelid));
exactTunnelModel->setQuery(query);
qDebug() << "getExactTunnel" << ret;
return exactTunnelModel;
}
/**
* 是否有该lineid对应的隧道数据库记录
* @return true有,false没有
*/
bool TunnelDAO::hasTunnelID(int tunnelid)
{
QSqlQuery query;
query.exec(QString("SELECT * FROM tunnel WHERE tunnel_id = %1 "
).arg(tunnelid));
while (query.next()) {
return true;
}
qDebug() << tunnelid << "can not find in table tunnel!";
return false;
}
/**
* 创建铁道隧道,没有tunnel参数,因为加入数据库时采取主键自增策略
* @return 0 创建成功
* 1 创建不成功 已经存在该隧道
* 2 创建不成功 lineid不存在
*/
int TunnelDAO::addTunnel(QString tunnelName, bool isValid, int lineID,
QString tunnelID_std, _int64 startPoint, _int64 endPoint,
int isNew, int lineType, bool isDoubleLine, bool isDownlink, bool isBridge)
{
int ret = 0;
if (getTunnelID_P(tunnelName, tunnelID_std, startPoint, endPoint,
isNew, lineType, isDoubleLine, isDownlink) > 0)
{
ret = 1;
return ret;
}
if (LineDAO::getLineDAOInstance()->hasLineID(lineID))
{
createTunnel_P(tunnelName, isValid, lineID, tunnelID_std, startPoint, endPoint,
isNew, lineType, isDoubleLine, isDownlink, isBridge);
return ret;
}
ret = 2;
qDebug() << "this line has not existed!";
return ret;
}
/**
* 更新铁道隧道
* @return 0 更新成功
* 1 更新不成功,当前tunnelid不存在
* 2 更新不成功,lineid不存在
*/
int TunnelDAO::updateTunnel(int tunnelid, QString tunnelName, bool isValid, int lineID,
QString tunnelID_std, _int64 startPoint, _int64 endPoint,
int isNew, int lineType, bool isDoubleLine, bool isDownlink)
{
if (!hasTunnelID(tunnelid)) {
qDebug() << tunnelid << "do not has the tunnel in table tunnel!";
return 1;
} else if (LineDAO::getLineDAOInstance()->hasLineID(lineID)) {
updateTunnel_P(tunnelid, tunnelName, isValid, lineID, tunnelID_std, startPoint, endPoint,
isNew, lineType, isDoubleLine, isDownlink);
return 0;
} else {
qDebug() << lineID << "do not has the related line!";
return 2;
}
}
/**
* 删除铁道隧道,并非真正删除,即is_valid变为false
* @return 0 成功,1不存在该tunnel
*/
int TunnelDAO::removeTunnel(int tunnelid)
{
if (!hasTunnelID(tunnelid))
{
qDebug() << tunnelid << "do not has the tunnel in table tunnel!";
return 1;
}
updateTunnel_P(tunnelid, false);
return 0;
}
// 是否有这条线路,return >0 tunnelid,-1没有
int TunnelDAO::getTunnelID_P(QString tunnelName, QString tunnelID_std, _int64 startPoint, _int64 endPoint,
int isNew, int lineType, bool isDoubleLine, bool isDownlink)
{
QSqlQuery query;
query.exec(QString("SELECT * FROM tunnel WHERE tunnel_name_std = '%1', "
"tunnel_id_std = '%2', start_point = %3, end_point = %4, is_new_std = %5, "
"line_type_std = %6, is_double_line = %7, is_downlink = %9"
).arg(tunnelName).arg(tunnelID_std).arg(startPoint).arg(endPoint).
arg(isNew).arg(lineType).arg(isDoubleLine).arg(isDownlink));
while (query.next()) {
int tunnelid = query.value(0).toInt();
return tunnelid;
}
qDebug() << "can not find in table tunnel!";
return -1;
}
bool TunnelDAO::createTunnel_P(QString tunnelName, bool isValid, int lineID,
QString tunnelID_std, _int64 startPoint, _int64 endPoint,
int isNew, int lineType, bool isDoubleLine, bool isDownlink, bool isBridge)
{
QSqlQuery query;
bool ret = query.exec(QString("INSERT INTO tunnel (tunnel_name_std, is_valid, line_id, "
"tunnel_id_std, start_point_std, end_point_std, is_new_std, line_type_std, "
"is_double_line, is_downlink, is_bridge) "
"VALUES ('%1', %2, %3, '%4', %5, %6, %7, %8, %9, %10, %11) "
).arg(tunnelName).arg(isValid).arg(lineID).arg(tunnelID_std)
.arg(startPoint).arg(endPoint).arg(isNew).arg(lineType).arg(isDoubleLine).arg(isDownlink).arg(isBridge));
qDebug() << "createTunnel_P" << tunnelName << ret;
return ret;
}
bool TunnelDAO::updateTunnel_P(int tunnelid, QString tunnelName, bool isValid, int lineID,
QString tunnelID_std, _int64 startPoint, _int64 endPoint,
int isNew, int lineType, bool isDoubleLine, bool isDownlink)
{
QSqlQuery query;
bool ret = query.exec(QString("UPDATE tunnel SET tunnel_name_std = '%1', "
"is_valid = %2, line_id = %3, tunnel_id_std = '%4', "
"start_point_std = %5, end_point_std = %6, is_new_std = %7, "
"line_type_std = %8, is_double_line = %9, is_downlink = %10 "
"WHERE tunnel_id = %11"
).arg(tunnelName).arg(isValid).arg(lineID).
arg(tunnelID_std).arg(startPoint).arg(endPoint).
arg(isNew).arg(lineType).arg(isDoubleLine).arg(isDownlink).arg(tunnelid));
qDebug() << "updateTunnel_P" << tunnelid << tunnelName << ret;
return ret;
}
bool TunnelDAO::updateTunnel_P(int tunnelid, bool isValid)
{
QSqlQuery query;
bool ret = query.exec(QString("UPDATE tunnel SET is_valid = %1 "
"WHERE tunnel_id = %2").arg(isValid).arg(tunnelid));
qDebug() << "updateTunnel_P" << tunnelid << ret;
return ret;
}
bool TunnelDAO::deleteTunnel_P(int tunnelid)
{
QSqlQuery query;
bool ret = query.exec(QString("DELETE FROM tunnel WHERE tunnel_id = %1").arg(tunnelid));
qDebug() << "deleteTunnel_P" << tunnelid << ret;
return ret;
}
| [
"fanxiang090909@126.com"
] | fanxiang090909@126.com |
5d4cfcdd167c00756cf9cefc2bf4f959089fa7ae | 5ec06dab1409d790496ce082dacb321392b32fe9 | /clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIComAdobeCqDtmImplServletsDTMDeployHookServletInfo.h | 423a83f7fd8071213b20912db3375a44d3edf96e | [
"Apache-2.0",
"MIT"
] | permissive | shinesolutions/swagger-aem-osgi | e9d2385f44bee70e5bbdc0d577e99a9f2525266f | c2f6e076971d2592c1cbd3f70695c679e807396b | refs/heads/master | 2022-10-29T13:07:40.422092 | 2021-04-09T07:46:03 | 2021-04-09T07:46:03 | 190,217,155 | 3 | 3 | Apache-2.0 | 2022-10-05T03:26:20 | 2019-06-04T14:23:28 | null | UTF-8 | C++ | false | false | 2,053 | h | /**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: opensource@shinesolutions.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
* OAIComAdobeCqDtmImplServletsDTMDeployHookServletInfo.h
*
*
*/
#ifndef OAIComAdobeCqDtmImplServletsDTMDeployHookServletInfo_H
#define OAIComAdobeCqDtmImplServletsDTMDeployHookServletInfo_H
#include <QJsonObject>
#include "OAIComAdobeCqDtmImplServletsDTMDeployHookServletProperties.h"
#include <QString>
#include "OAIObject.h"
namespace OpenAPI {
class OAIComAdobeCqDtmImplServletsDTMDeployHookServletInfo: public OAIObject {
public:
OAIComAdobeCqDtmImplServletsDTMDeployHookServletInfo();
OAIComAdobeCqDtmImplServletsDTMDeployHookServletInfo(QString json);
~OAIComAdobeCqDtmImplServletsDTMDeployHookServletInfo() override;
void init();
QString asJson () const override;
QJsonObject asJsonObject() const override;
void fromJsonObject(QJsonObject json) override;
void fromJson(QString jsonString) override;
QString getPid() const;
void setPid(const QString &pid);
QString getTitle() const;
void setTitle(const QString &title);
QString getDescription() const;
void setDescription(const QString &description);
OAIComAdobeCqDtmImplServletsDTMDeployHookServletProperties getProperties() const;
void setProperties(const OAIComAdobeCqDtmImplServletsDTMDeployHookServletProperties &properties);
virtual bool isSet() const override;
private:
QString pid;
bool m_pid_isSet;
QString title;
bool m_title_isSet;
QString description;
bool m_description_isSet;
OAIComAdobeCqDtmImplServletsDTMDeployHookServletProperties properties;
bool m_properties_isSet;
};
}
#endif // OAIComAdobeCqDtmImplServletsDTMDeployHookServletInfo_H
| [
"cliffano@gmail.com"
] | cliffano@gmail.com |
d175c597bac36fe373996702341a131c40b38630 | f0b7bcc41298354b471a72a7eeafe349aa8655bf | /codebase/apps/titan/src/CIDD_titan/render_xsect_grids.cc | 73282a98c3c4b8b4e30cb7aff37030f0513d9c76 | [
"BSD-3-Clause"
] | permissive | NCAR/lrose-core | 23abeb4e4f1b287725dc659fb566a293aba70069 | be0d059240ca442883ae2993b6aa112011755688 | refs/heads/master | 2023-09-01T04:01:36.030960 | 2023-08-25T00:41:16 | 2023-08-25T00:41:16 | 51,408,988 | 90 | 53 | NOASSERTION | 2023-08-18T21:59:40 | 2016-02-09T23:36:25 | C++ | UTF-8 | C++ | false | false | 11,173 | cc | // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
// ** Copyright UCAR (c) 1990 - 2016
// ** University Corporation for Atmospheric Research (UCAR)
// ** National Center for Atmospheric Research (NCAR)
// ** Boulder, Colorado, USA
// ** BSD licence applies - redistribution and use in source and binary
// ** forms, with or without modification, are permitted provided that
// ** the following conditions are met:
// ** 1) If the software is modified to produce derivative works,
// ** such modified software should be clearly marked, so as not
// ** to confuse it with the version available from UCAR.
// ** 2) Redistributions of source code must retain the above copyright
// ** notice, this list of conditions and the following disclaimer.
// ** 3) 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.
// ** 4) Neither the name of UCAR nor the names of its contributors,
// ** if any, may be used to endorse or promote products derived from
// ** this software without specific prior written permission.
// ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS
// ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
// ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
/************************************************************************
* RENDER_XSECT_GRIDS.C:
*
* For the Configurable Interactive Data Display (CIDD)
* Frank Hage July 1991 NCAR, Research Applications Program
*/
#define RENDER_XSECT_GRIDS
#define PSEUDO_RADIUS 8533.0
#include "cidd.h"
static int render_polar_rhi( Drawable xid, met_record_t *mr, time_t start_time, time_t end_time, int is_overlay_field);
/**********************************************************************
* RENDER_XSECT_GRIDS
*/
int render_xsect_grid( Drawable xid, met_record_t *mr, time_t start_time, time_t end_time, int is_overlay_field)
{
int i,j;
int ht,wd; /* Dims of drawing canvas */
int out_of_date;
int stretch_secs;
int startx,starty; /* Pixel limits of data area */
int endx,endy; /* Pixel limits of data area */
int xmid,ymid;
double dist; /* distance between corner of vert section and grid point */
double height;
double val;
double r_wd; /* data point rectangle dims */
unsigned short *ptr;
char message[32];
Font font;
if(xid == 0) return CIDD_FAILURE;
ptr = (unsigned short *) mr->v_data;
stretch_secs = (int) (60.0 * mr->time_allowance);
out_of_date = 0;
if(gd.check_data_times) {
if(mr->v_date.unix_time < start_time - stretch_secs) out_of_date = 1;
if(mr->v_date.unix_time > end_time + stretch_secs) out_of_date = 1;
}
if(ptr == NULL || out_of_date) { /* If no data - Draw warning message */
if(out_of_date) {
sprintf(message,"%s - Data too Old",gd.no_data_message);
} else {
sprintf(message,"%s",gd.no_data_message);
}
font = choose_font(message,gd.v_win.img_dim.width,gd.v_win.img_dim.height,&xmid,&ymid);
XSetFont(gd.dpy,gd.legends.foreground_color->gc,font);
XDrawImageString(gd.dpy,xid,gd.legends.foreground_color->gc,
((gd.v_win.win_dim.width / 2) + xmid),
((gd.v_win.win_dim.height / 2) + ymid),
message,strlen(message));
fprintf(stderr, "Message with no data received from\n");
fprintf(stderr, " default service at: %s\n",
gd.io_info.mr->url);
fflush(stderr);
return CIDD_SUCCESS;
}
// is this a polar RHI? If so, special case.
if (mr->v_fhdr.vlevel_type == Mdvx::VERT_TYPE_AZ) {
return render_polar_rhi(xid, mr, start_time, end_time, is_overlay_field);
}
height = mr->vert[0].min;
disp_proj_to_pixel_v(&gd.v_win.margin,0.0,height,&startx,&starty);
height = mr->vert[mr->v_fhdr.nz -1].max;
disp_proj_to_pixel_v(&gd.v_win.margin,gd.h_win.route.total_length,height,&endx,&endy);
r_wd = (double)ABSDIFF(endx,startx) / (double) mr->v_fhdr.nx; /* get data point rectangle width */
vert_spacing_t vert[mr->v_fhdr.nz];
for(i=0; i < mr->v_fhdr.nz; i++) {
if(i == 0) { // Lowest plane
double delta = fabs(mr->v_vhdr.level[i+1] - mr->v_vhdr.level[i]) / 2.0;
vert[i].min = mr->v_vhdr.level[0] - delta;
vert[i].cent = mr->v_vhdr.level[0];
vert[i].max = mr->v_vhdr.level[0] + delta;
} else if (i == mr->v_fhdr.nz -1) { // highest plane
double delta = fabs(mr->v_vhdr.level[i] - mr->v_vhdr.level[i-1]) / 2.0;
vert[i].min = mr->v_vhdr.level[i] - delta;
vert[i].cent = mr->v_vhdr.level[i];
vert[i].max = mr->v_vhdr.level[i] + delta;
} else { // Middle planes
vert[i].min = (mr->v_vhdr.level[i] + mr->v_vhdr.level[i-1]) / 2.0;
vert[i].cent = mr->v_vhdr.level[i];
vert[i].max = (mr->v_vhdr.level[i] + mr->v_vhdr.level[i+1]) /2.0;
}
}
int y_start[mr->v_fhdr.nz]; /* canvas rectangle begin coords */
int y_end[mr->v_fhdr.nz]; /* canvas rectangle end coords */
for(i= 0; i < mr->v_fhdr.nz; i++) { /* Calc starting/ending coords for the array */
height = vert[i].min;
disp_proj_to_pixel_v(&gd.v_win.margin,dist,height,&endx,&(y_start[i]));
height = vert[i].max;
disp_proj_to_pixel_v(&gd.v_win.margin,dist,height,&endx,&(y_end[i]));
if ((y_start[i] - y_end[i]) < 0 ) {
int tval = y_start[i];
y_start[i] = y_end[i];
y_end[i] = tval;
}
}
int x_start[mr->v_fhdr.nx]; /* canvas rectangle begin coords */
for(j=0;j< mr->v_fhdr.nx; j++) {
x_start[j] = (int)(((double) j * r_wd) + startx);
}
wd = (int)(r_wd + 1.0);
if(is_overlay_field) {
for(i= 0; i < mr->v_fhdr.nz; i++) {
ht = y_start[i] - y_end[i];
for(j=0;j< mr->v_fhdr.nx; j++) {
if(mr->v_vcm.val_gc[*ptr] != NULL) {
val = (mr->v_fhdr.scale * *ptr) + mr->v_fhdr.bias;
if(val >= mr->overlay_min && val <= mr->overlay_max)
XFillRectangle(gd.dpy,xid,mr->v_vcm.val_gc[*ptr],x_start[j],y_end[i],wd,ht);
}
ptr++;
}
}
} else {
int rend_m = mr->render_method;
// Handle case where contours really don't apply (vertical sides)
if(mr->v_fhdr.min_value == mr->v_fhdr.max_value ) rend_m = POLYGONS;
switch (rend_m) {
case POLYGONS:
//printf("Drawing Filled Rectangle image: field %s\n", mr->field_label);
for(i= 0; i < mr->v_fhdr.nz; i++) {
ht = (y_start[i] - y_end[i]);
for(j=0;j< mr->v_fhdr.nx; j++) {
if(mr->v_vcm.val_gc[*ptr] != NULL) {
XFillRectangle(gd.dpy,xid,mr->v_vcm.val_gc[*ptr],x_start[j],y_end[i],wd,ht);
}
ptr++;
}
}
break;
case FILLED_CONTOURS:
case DYNAMIC_CONTOURS:
for(j=0;j <= mr->v_fhdr.nx; j++) {
x_start[j] = (int) (x_start[j] + (r_wd / 2));
if(x_start[j] > gd.v_win.can_dim.width) x_start[j] = gd.v_win.can_dim.width;
}
for(i= 0; i <= mr->v_fhdr.nz; i++) { /* Calc starting coords for the array */
y_start[i] = (int) ((y_start[i] + y_end[i]) / 2.0);
if(y_start[i] < 0) y_start[i] = 0;
if(y_start[i] >= gd.v_win.can_dim.height) y_start[i] = gd.v_win.can_dim.height -1;
}
// printf("Drawing Filled Contour image: field %s\n", mr->field_label);
if (gd.layers.use_alt_contours) {
RenderFilledPolygons(xid, mr, true);
} else {
draw_xsect_filled_contours(xid,x_start,y_start,mr);
}
break;
}
}
return CIDD_SUCCESS;
}
//////////////////////////
// rendering for POLAR RHI
static int render_polar_rhi( Drawable xid, met_record_t *mr, time_t start_time, time_t end_time, int is_overlay_field)
{
// alloc arrays - for large arrays we need to use malloc
// to avoid a SEGV
double elevLimit[mr->v_fhdr.ny + 1];
double slant[mr->v_fhdr.nx + 1];
double htcorr[mr->v_fhdr.nx + 1];
double **ht = (double **) umalloc2(mr->v_fhdr.ny + 1, mr->v_fhdr.nx + 1, sizeof(double));
double **range = (double **) umalloc2(mr->v_fhdr.ny + 1, mr->v_fhdr.nx + 1, sizeof(double));
int **yy = (int **) umalloc2(mr->v_fhdr.ny + 1, mr->v_fhdr.nx + 1, sizeof(int));
int **xx = (int **) umalloc2(mr->v_fhdr.ny + 1, mr->v_fhdr.nx + 1, sizeof(int));
// compute array of heights and ranges
double twiceRad = PSEUDO_RADIUS * 2.0;
double radarHt = mr->v_mhdr.sensor_alt;
elevLimit[0] = mr->v_fhdr.grid_miny - 0.5 * mr->v_fhdr.grid_dy;
for (int ii = 0; ii < mr->v_fhdr.ny; ii++) {
elevLimit[ii + 1] = elevLimit[ii] + mr->v_fhdr.grid_dy;
}
slant[0] = mr->v_fhdr.grid_minx - 0.5 * mr->v_fhdr.grid_dx;
for (int jj = 0; jj < mr->v_fhdr.nx; jj++) {
slant[jj + 1] = slant[jj] + mr->v_fhdr.grid_dx;
}
double maxRange = slant[mr->v_fhdr.nx];
for (int jj = 0; jj <= mr->v_fhdr.nx; jj++) {
htcorr[jj] = (slant[jj] * slant[jj]) / twiceRad;
}
for (int ii = 0; ii <= mr->v_fhdr.ny; ii++) {
double sinel = sin(elevLimit[ii] * DEG_TO_RAD);
double cosel = cos(elevLimit[ii] * DEG_TO_RAD);
for (int jj = 0; jj <= mr->v_fhdr.nx; jj++) {
range[ii][jj] = slant[jj] * cosel;
ht[ii][jj] = slant[jj] * sinel + htcorr[jj] + radarHt;
}
}
// convert to screen coords
for (int ii = 0; ii <= mr->v_fhdr.ny; ii++) {
for (int jj = 0; jj <= mr->v_fhdr.nx; jj++) {
disp_proj_to_pixel_v(&gd.v_win.margin,
range[ii][jj], ht[ii][jj],
&xx[ii][jj], &yy[ii][jj]);
}
}
// render polygons
int num_points = 4;
XPoint xpt[num_points];
unsigned short *ptr = (unsigned short *) mr->v_data;
for (int ii = 0; ii < mr->v_fhdr.ny; ii++) {
for (int jj = 0; jj < mr->v_fhdr.nx; jj++, ptr++) {
if(mr->v_vcm.val_gc[*ptr] != NULL) {
xpt[0].x = xx[ii][jj];
xpt[0].y = yy[ii][jj];
xpt[1].x = xx[ii+1][jj];
xpt[1].y = yy[ii+1][jj];
xpt[2].x = xx[ii+1][jj+1];
xpt[2].y = yy[ii+1][jj+1];
xpt[3].x = xx[ii][jj+1];
xpt[3].y = yy[ii][jj+1];
XFillPolygon(gd.dpy, xid, mr->v_vcm.val_gc[*ptr],
xpt, num_points, Nonconvex, CoordModeOrigin);
}
} // jj
} // ii
// free up
ufree2((void **) ht);
ufree2((void **) range);
ufree2((void **) xx);
ufree2((void **) yy);
return CIDD_SUCCESS;
}
| [
"dixon@ucar.edu"
] | dixon@ucar.edu |
73ec68c1ca400b6d7fb2cc9344130f90b15d54b4 | 02095cd4aeaa3a0d724f7362cdb8795fe9a81620 | /oplink/algorithms/team/src/plugins/scores/HVSynergyPairs/HVSynergyPairs.h | d4c9c7c38ca64ffe947c9261dda57a51946bc942 | [] | no_license | PAL-ULL/software-metco | ba5123cb1423fed4a2ac678ab375728ba4bbfbc8 | 59edc4e49bddbd9fc7237bf2f24271bdfc8afd79 | refs/heads/master | 2021-04-15T04:12:56.292543 | 2021-03-08T13:29:14 | 2021-03-08T13:29:14 | 126,484,450 | 10 | 5 | null | 2020-07-21T18:43:10 | 2018-03-23T12:49:10 | C++ | ISO-8859-1 | C++ | false | false | 2,646 | h | /***********************************************************************************
* AUTORES
* Carlos Segura González
*
* DESCRIPCION
* Algoritmo de puntuacion que implementa el algoritmo basado en detección
* de "pares sinérgicos".
* Al módulo se le debe pasar el número de islas esclavas que intervienen y supone
* que el criterio de parada está definido de forma que todos acaban a la vez, es decir,
* que todas las islas van a cambiar el algoritmo de forma simultánea.
*
* El funcionamiento es el siguiente:
* - Cada heurística tiene una puntuación que es la media ponderada de los incrementos
* que ha conseguido (se usan los últimos n valores)
* - Cada par de heurísticas tiene una puntuación que es la media ponderada de las
* mejoras que se han conseguido al utilizar las 2 heurísticas de forma simultánea
* - La Selección se hace de la siguiente forma:
* * En un x% (parámetro) de las veces se utiliza la puntuación independiente
* * En un y% (parámetro) de las veces se utiliza la puntuación de pares
* * En el resto de las veces se utiliza una selección aleatoria
***********************************************************************************/
#include <vector>
#include <map>
#include <list>
#include "LocalScoreAlgorithm.h"
#include "MOFront.h"
using namespace std;
class HVSynergyPairs : public LocalScoreAlgorithm {
public:
long double score(MOFront *);
long double estimateScore(const long double breakFromScore, const int alg, const int conf, const int islandId, const double rndValue);
void updateScore(const long double breakFrom, const long double arriveTo, int alg, int conf, int islandId);
bool init(const vector<string> ¶ms) ;
void printHistory();
void begins(const int algId, const int confId, const int islandId);
void ends(const int algId, const int confId, const int islandId);
int getDirection() const { return MAXIMIZE; }
private:
long double getScore(const long double breakFromScore, const int alg, const int conf, const int islandId, const double rndValue);
void asynchronyDetection(int islandId);
vector< long double > refPoint;
map< int, map <int, int > > executions;
map<int, map <int, int > > configToExecuting;
map< int, map < int, vector < long double > > > scores;
//map< int, map < int, map < int, map < int, vector < pair < double, int > > > > > > pairScores;
map< int, map < int, map < int, map < int, vector < long double > > > > > pairScores;
list < pair < int, int > > assignedHeuristics;
int slaveIslands;
double p1Value, p2Value;
int consideredValues;
};
| [
"edusegre@gmail.com"
] | edusegre@gmail.com |
156cdab558d3a82b97d42de974a228325ddf5da5 | d0be9a869d4631c58d09ad538b0908554d204e1c | /utf8/lib/client/kernelengine/include/CGAL3.2.1/include/CGAL/Delaunay_triangulation_3.h | 8dbb514bce53a5d51c17dab59337defe723f85cc | [] | no_license | World3D/pap | 19ec5610393e429995f9e9b9eb8628fa597be80b | de797075062ba53037c1f68cd80ee6ab3ed55cbe | refs/heads/master | 2021-05-27T08:53:38.964500 | 2014-07-24T08:10:40 | 2014-07-24T08:10:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,213 | h | // Copyright (c) 1999-2004 INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); you may redistribute it under
// the terms of the Q Public License version 1.0.
// See the file LICENSE.QPL distributed with CGAL.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL: svn+ssh://scm.gforge.inria.fr/svn/cgal/branches/CGAL-3.2-branch/Triangulation_3/include/CGAL/Delaunay_triangulation_3.h $
// $Id: Delaunay_triangulation_3.h 28567 2006-02-16 14:30:13Z lsaboret $
//
//
// Author(s) : Monique Teillaud <Monique.Teillaud@sophia.inria.fr>
// Sylvain Pion <Sylvain.Pion@sophia.inria.fr>
// Andreas Fabri <Andreas.Fabri@sophia.inria.fr>
#ifndef CGAL_DELAUNAY_TRIANGULATION_3_H
#define CGAL_DELAUNAY_TRIANGULATION_3_H
#include <CGAL/basic.h>
#include <utility>
#include <vector>
#include <CGAL/Triangulation_short_names_3.h>
#include <CGAL/Triangulation_3.h>
#include <CGAL/Delaunay_remove_tds_3.h>
#include <CGAL/Unique_hash_map.h>
#include <CGAL/iterator.h>
CGAL_BEGIN_NAMESPACE
template < class Tr > class Natural_neighbors_3;
template < class Gt,
class Tds = Triangulation_data_structure_3 <
Triangulation_vertex_base_3<Gt>,
Triangulation_cell_base_3<Gt> > >
class Delaunay_triangulation_3 : public Triangulation_3<Gt,Tds>
{
typedef Delaunay_triangulation_3<Gt, Tds> Self;
typedef Triangulation_3<Gt,Tds> Tr_Base;
friend class Natural_neighbors_3<Self>;
public:
typedef Tds Triangulation_data_structure;
typedef Gt Geom_traits;
typedef typename Gt::Point_3 Point;
typedef typename Gt::Segment_3 Segment;
typedef typename Gt::Triangle_3 Triangle;
typedef typename Gt::Tetrahedron_3 Tetrahedron;
// types for dual:
typedef typename Gt::Line_3 Line;
typedef typename Gt::Ray_3 Ray;
typedef typename Gt::Plane_3 Plane;
typedef typename Gt::Object_3 Object;
typedef typename Tr_Base::Cell_handle Cell_handle;
typedef typename Tr_Base::Vertex_handle Vertex_handle;
typedef typename Tr_Base::Cell Cell;
typedef typename Tr_Base::Vertex Vertex;
typedef typename Tr_Base::Facet Facet;
typedef typename Tr_Base::Edge Edge;
typedef typename Tr_Base::Cell_circulator Cell_circulator;
typedef typename Tr_Base::Facet_circulator Facet_circulator;
typedef typename Tr_Base::Cell_iterator Cell_iterator;
typedef typename Tr_Base::Facet_iterator Facet_iterator;
typedef typename Tr_Base::Edge_iterator Edge_iterator;
typedef typename Tr_Base::Vertex_iterator Vertex_iterator;
typedef typename Tr_Base::Finite_vertices_iterator Finite_vertices_iterator;
typedef typename Tr_Base::Finite_cells_iterator Finite_cells_iterator;
typedef typename Tr_Base::Finite_facets_iterator Finite_facets_iterator;
typedef typename Tr_Base::Finite_edges_iterator Finite_edges_iterator;
typedef typename Tr_Base::All_cells_iterator All_cells_iterator;
typedef typename Tr_Base::Locate_type Locate_type;
typedef Triple<Vertex_handle,Vertex_handle,Vertex_handle> Vertex_triple;
#ifndef CGAL_CFG_USING_BASE_MEMBER_BUG_2
using Tr_Base::cw;
using Tr_Base::ccw;
using Tr_Base::geom_traits;
using Tr_Base::number_of_vertices;
using Tr_Base::dimension;
using Tr_Base::finite_facets_begin;
using Tr_Base::finite_facets_end;
using Tr_Base::finite_vertices_begin;
using Tr_Base::finite_vertices_end;
using Tr_Base::finite_cells_begin;
using Tr_Base::finite_cells_end;
using Tr_Base::finite_edges_begin;
using Tr_Base::finite_edges_end;
using Tr_Base::tds;
using Tr_Base::infinite_vertex;
using Tr_Base::next_around_edge;
using Tr_Base::vertex_triple_index;
using Tr_Base::mirror_vertex;
using Tr_Base::coplanar;
using Tr_Base::coplanar_orientation;
using Tr_Base::orientation;
#endif
protected:
Oriented_side
side_of_oriented_sphere(const Point &p0, const Point &p1, const Point &p2,
const Point &p3, const Point &t, bool perturb = false) const;
Bounded_side
coplanar_side_of_bounded_circle(const Point &p, const Point &q,
const Point &r, const Point &s, bool perturb = false) const;
// for dual:
Point
construct_circumcenter(const Point &p, const Point &q, const Point &r) const
{
return geom_traits().construct_circumcenter_3_object()(p, q, r);
}
Point
construct_circumcenter(const Point &p, const Point &q,
const Point &r, const Point &s) const
{
return geom_traits().construct_circumcenter_3_object()(p, q, r, s);
}
Line
construct_perpendicular_line(const Plane &pl, const Point &p) const
{
return geom_traits().construct_perpendicular_line_3_object()(pl, p);
}
Plane
construct_plane(const Point &p, const Point &q, const Point &r) const
{
return geom_traits().construct_plane_3_object()(p, q, r);
}
Ray
construct_ray(const Point &p, const Line &l) const
{
return geom_traits().construct_ray_3_object()(p, l);
}
Object
construct_object(const Point &p) const
{
return geom_traits().construct_object_3_object()(p);
}
Object
construct_object(const Segment &s) const
{
return geom_traits().construct_object_3_object()(s);
}
Object
construct_object(const Ray &r) const
{
return geom_traits().construct_object_3_object()(r);
}
bool
less_distance(const Point &p, const Point &q, const Point &r) const
{
return geom_traits().compare_distance_3_object()(p, q, r) == SMALLER;
}
public:
Delaunay_triangulation_3(const Gt& gt = Gt())
: Tr_Base(gt)
{}
// copy constructor duplicates vertices and cells
Delaunay_triangulation_3(const Delaunay_triangulation_3 & tr)
: Tr_Base(tr)
{
CGAL_triangulation_postcondition( is_valid() );
}
template < typename InputIterator >
Delaunay_triangulation_3(InputIterator first, InputIterator last,
const Gt& gt = Gt())
: Tr_Base(gt)
{
insert(first, last);
}
template < class InputIterator >
int
insert(InputIterator first, InputIterator last)
{
int n = number_of_vertices();
while(first != last){
insert(*first);
++first;
}
return number_of_vertices() - n;
}
Vertex_handle insert(const Point & p, Cell_handle start = Cell_handle());
Vertex_handle insert(const Point & p, Locate_type lt,
Cell_handle c, int li, int);
Vertex_handle move_point(Vertex_handle v, const Point & p);
template <class OutputIteratorBoundaryFacets,
class OutputIteratorCells,
class OutputIteratorInternalFacets>
Triple<OutputIteratorBoundaryFacets,
OutputIteratorCells,
OutputIteratorInternalFacets>
find_conflicts(const Point &p, Cell_handle c,
OutputIteratorBoundaryFacets bfit,
OutputIteratorCells cit,
OutputIteratorInternalFacets ifit) const
{
CGAL_triangulation_precondition(dimension() >= 2);
std::vector<Cell_handle> cells;
cells.reserve(32);
std::vector<Facet> facets;
facets.reserve(64);
if (dimension() == 2) {
Conflict_tester_2 tester(p, this);
ifit = find_conflicts_2(c, tester,
make_triple(std::back_inserter(facets),
std::back_inserter(cells),
ifit)).third;
}
else {
Conflict_tester_3 tester(p, this);
ifit = find_conflicts_3(c, tester,
make_triple(std::back_inserter(facets),
std::back_inserter(cells),
ifit)).third;
}
// Reset the conflict flag on the boundary.
for(typename std::vector<Facet>::iterator fit=facets.begin();
fit != facets.end(); ++fit) {
fit->first->neighbor(fit->second)->set_in_conflict_flag(0);
*bfit++ = *fit;
}
// Reset the conflict flag in the conflict cells.
for(typename std::vector<Cell_handle>::iterator ccit=cells.begin();
ccit != cells.end(); ++ccit) {
(*ccit)->set_in_conflict_flag(0);
*cit++ = *ccit;
}
return make_triple(bfit, cit, ifit);
}
template <class OutputIteratorBoundaryFacets, class OutputIteratorCells>
std::pair<OutputIteratorBoundaryFacets, OutputIteratorCells>
find_conflicts(const Point &p, Cell_handle c,
OutputIteratorBoundaryFacets bfit,
OutputIteratorCells cit) const
{
Triple<OutputIteratorBoundaryFacets,
OutputIteratorCells,
Emptyset_iterator> t = find_conflicts(p, c, bfit, cit,
Emptyset_iterator());
return std::make_pair(t.first, t.second);
}
// Returns the vertices on the boundary of the conflict hole.
template <class OutputIterator>
OutputIterator
vertices_in_conflict(const Point&p, Cell_handle c, OutputIterator res) const
{
CGAL_triangulation_precondition(dimension() >= 2);
// Get the facets on the boundary of the hole.
std::vector<Facet> facets;
find_conflicts(p, c, std::back_inserter(facets),
Emptyset_iterator(), Emptyset_iterator());
// Then extract uniquely the vertices.
std::set<Vertex_handle> vertices;
if (dimension() == 3) {
for (typename std::vector<Facet>::const_iterator i = facets.begin();
i != facets.end(); ++i) {
vertices.insert(i->first->vertex((i->second+1)&3));
vertices.insert(i->first->vertex((i->second+2)&3));
vertices.insert(i->first->vertex((i->second+3)&3));
}
} else {
for (typename std::vector<Facet>::const_iterator i = facets.begin();
i != facets.end(); ++i) {
vertices.insert(i->first->vertex(cw(i->second)));
vertices.insert(i->first->vertex(ccw(i->second)));
}
}
return std::copy(vertices.begin(), vertices.end(), res);
}
// We return bool only for backward compatibility (it's always true).
// The documentation mentions void.
bool remove(Vertex_handle v);
template < typename InputIterator >
int remove(InputIterator first, InputIterator beyond)
{
int n = number_of_vertices();
while (first != beyond) {
remove(*first);
++first;
}
return n - number_of_vertices();
}
private:
typedef Facet Edge_2D;
void remove_2D(Vertex_handle v);
void make_hole_2D(Vertex_handle v, std::list<Edge_2D> & hole);
void fill_hole_delaunay_2D(std::list<Edge_2D> & hole);
void make_canonical(Vertex_triple& t) const;
Vertex_triple
make_vertex_triple(const Facet& f) const;
void remove_3D(Vertex_handle v);
void remove_3D_new(Vertex_handle v);
Bounded_side
side_of_sphere(const Vertex_handle& v0, const Vertex_handle& v1,
const Vertex_handle& v2, const Vertex_handle& v3,
const Point &p, bool perturb) const;
public:
// Queries
Bounded_side
side_of_sphere(const Cell_handle& c, const Point & p,
bool perturb = false) const
{
return side_of_sphere(c->vertex(0), c->vertex(1),
c->vertex(2), c->vertex(3), p, perturb);
}
Bounded_side
side_of_circle( const Facet & f, const Point & p, bool perturb = false) const
{
return side_of_circle(f.first, f.second, p, perturb);
}
Bounded_side
side_of_circle( const Cell_handle& c, int i, const Point & p,
bool perturb = false) const;
Vertex_handle
nearest_vertex_in_cell(const Point& p, const Cell_handle& c) const;
Vertex_handle
nearest_vertex(const Point& p, Cell_handle c = Cell_handle()) const;
bool is_Gabriel(Cell_handle c, int i) const;
bool is_Gabriel(Cell_handle c, int i, int j) const;
bool is_Gabriel(const Facet& f)const ;
bool is_Gabriel(const Edge& e) const;
// Dual functions
Point dual(Cell_handle c) const;
Object dual(const Facet & f) const
{ return dual( f.first, f.second ); }
Object dual(Cell_handle c, int i) const;
bool is_valid(bool verbose = false, int level = 0) const;
bool is_valid(Cell_handle c, bool verbose = false, int level = 0) const;
template < class Stream>
Stream& draw_dual(Stream & os)
{
for (Finite_facets_iterator fit = finite_facets_begin(),
end = finite_facets_end();
fit != end; ++fit) {
Object o = dual(*fit);
if (const Point *p = object_cast<Point>(&o)) os << *p;
if (const Segment *s = object_cast<Segment>(&o)) os << *s;
if (const Ray *r = object_cast<Ray>(&o)) os << *r;
}
return os;
}
private:
Vertex_handle
nearest_vertex(const Point &p, Vertex_handle v, Vertex_handle w) const
{
// In case of equality, v is returned.
CGAL_triangulation_precondition(v != w);
if (is_infinite(v))
return w;
if (is_infinite(w))
return v;
return less_distance(p, w->point(), v->point()) ? w : v;
}
#ifndef CGAL_CFG_NET2003_MATCHING_BUG
void make_hole_3D_ear( Vertex_handle v,
std::vector<Facet> & boundhole,
std::vector<Cell_handle> & hole);
#else
void make_hole_3D_ear( Vertex_handle v,
std::vector<Facet> & boundhole,
std::vector<Cell_handle> & hole)
{
CGAL_triangulation_expensive_precondition( ! test_dim_down(v) );
incident_cells(v, std::back_inserter(hole));
for (typename std::vector<Cell_handle>::iterator cit = hole.begin();
cit != hole.end(); ++cit) {
int indv = (*cit)->index(v);
Cell_handle opp_cit = (*cit)->neighbor( indv );
boundhole.push_back(Facet( opp_cit, opp_cit->index(*cit)) );
for (int i=0; i<4; i++)
if ( i != indv )
(*cit)->vertex(i)->set_cell(opp_cit);
}
}
#endif
void fill_hole_3D_ear(const std::vector<Facet> & boundhole);
void make_hole_3D_new( Vertex_handle v,
std::map<Vertex_triple,Facet>& outer_map,
std::vector<Cell_handle> & hole);
class Conflict_tester_3
{
const Point &p;
const Self *t;
public:
Conflict_tester_3(const Point &pt, const Self *tr)
: p(pt), t(tr) {}
bool operator()(const Cell_handle c) const
{
return t->side_of_sphere(c, p, true) == ON_BOUNDED_SIDE;
}
};
class Conflict_tester_2
{
const Point &p;
const Self *t;
public:
Conflict_tester_2(const Point &pt, const Self *tr)
: p(pt), t(tr) {}
bool operator()(const Cell_handle c) const
{
return t->side_of_circle(c, 3, p, true) == ON_BOUNDED_SIDE;
}
};
class Perturbation_order {
const Self *t;
public:
Perturbation_order(const Self *tr)
: t(tr) {}
bool operator()(const Point *p, const Point *q) const {
return t->compare_xyz(*p, *q) == SMALLER;
}
};
friend class Perturbation_order;
friend class Conflict_tester_3;
friend class Conflict_tester_2;
};
template < class Gt, class Tds >
typename Delaunay_triangulation_3<Gt,Tds>::Vertex_handle
Delaunay_triangulation_3<Gt,Tds>::
insert(const Point & p, Cell_handle start)
{
Locate_type lt;
int li, lj;
Cell_handle c = locate(p, lt, li, lj, start);
return insert(p, lt, c, li, lj);
}
template < class Gt, class Tds >
typename Delaunay_triangulation_3<Gt,Tds>::Vertex_handle
Delaunay_triangulation_3<Gt,Tds>::
insert(const Point & p, Locate_type lt, Cell_handle c, int li, int)
{
switch (dimension()) {
case 3:
{
if ( lt == Tr_Base::VERTEX )
return c->vertex(li);
Conflict_tester_3 tester(p, this);
Vertex_handle v = insert_conflict_3(c, tester);
v->set_point(p);
return v;
}// dim 3
case 2:
{
switch (lt) {
case Tr_Base::OUTSIDE_CONVEX_HULL:
case Tr_Base::FACET:
case Tr_Base::EDGE:
{
Conflict_tester_2 tester(p, this);
Vertex_handle v = insert_conflict_2(c, tester);
v->set_point(p);
return v;
}
case Tr_Base::VERTEX:
return c->vertex(li);
case Tr_Base::OUTSIDE_AFFINE_HULL:
// if the 2d triangulation is Delaunay, the 3d
// triangulation will be Delaunay
return Tr_Base::insert_outside_affine_hull(p);
default:
CGAL_triangulation_assertion(false); // CELL should not happen in 2D.
}
}//dim 2
default :
// dimension <= 1
return Tr_Base::insert(p, c);
}
}
template < class Gt, class Tds >
typename Delaunay_triangulation_3<Gt,Tds>::Vertex_handle
Delaunay_triangulation_3<Gt,Tds>::
move_point(Vertex_handle v, const Point & p)
{
CGAL_triangulation_precondition(! is_infinite(v));
CGAL_triangulation_expensive_precondition(is_vertex(v));
// Dummy implementation for a start.
// Remember an incident vertex to restart
// the point location after the removal.
Cell_handle c = v->cell();
Vertex_handle old_neighbor = c->vertex(c->index(v) == 0 ? 1 : 0);
CGAL_triangulation_assertion(old_neighbor != v);
remove(v);
if (dimension() <= 0)
return insert(p);
return insert(p, old_neighbor->cell());
}
template < class Gt, class Tds >
void
Delaunay_triangulation_3<Gt,Tds>::
remove_2D(Vertex_handle v)
{
CGAL_triangulation_precondition(dimension() == 2);
std::list<Edge_2D> hole;
make_hole_2D(v, hole);
fill_hole_delaunay_2D(hole);
tds().delete_vertex(v);
}
template <class Gt, class Tds >
void
Delaunay_triangulation_3<Gt, Tds>::
fill_hole_delaunay_2D(std::list<Edge_2D> & first_hole)
{
typedef std::list<Edge_2D> Hole;
std::vector<Hole> hole_list;
Cell_handle f, ff, fn;
int i, ii, in;
hole_list.push_back(first_hole);
while( ! hole_list.empty())
{
Hole hole = hole_list.back();
hole_list.pop_back();
// if the hole has only three edges, create the triangle
if (hole.size() == 3) {
typename Hole::iterator hit = hole.begin();
f = (*hit).first; i = (*hit).second;
ff = (* ++hit).first; ii = (*hit).second;
fn = (* ++hit).first; in = (*hit).second;
tds().create_face(f, i, ff, ii, fn, in);
continue;
}
// else find an edge with two finite vertices
// on the hole boundary
// and the new triangle adjacent to that edge
// cut the hole and push it back
// first, ensure that a neighboring face
// whose vertices on the hole boundary are finite
// is the first of the hole
while (1) {
ff = (hole.front()).first;
ii = (hole.front()).second;
if ( is_infinite(ff->vertex(cw(ii))) ||
is_infinite(ff->vertex(ccw(ii)))) {
hole.push_back(hole.front());
hole.pop_front();
}
else
break;
}
// take the first neighboring face and pop it;
ff = (hole.front()).first;
ii = (hole.front()).second;
hole.pop_front();
Vertex_handle v0 = ff->vertex(cw(ii));
Vertex_handle v1 = ff->vertex(ccw(ii));
Vertex_handle v2 = infinite_vertex();
const Point &p0 = v0->point();
const Point &p1 = v1->point();
const Point *p2 = NULL; // Initialize to NULL to avoid warning.
typename Hole::iterator hdone = hole.end();
typename Hole::iterator hit = hole.begin();
typename Hole::iterator cut_after(hit);
// if tested vertex is c with respect to the vertex opposite
// to NULL neighbor,
// stop at the before last face;
hdone--;
for (; hit != hdone; ++hit) {
fn = hit->first;
in = hit->second;
Vertex_handle vv = fn->vertex(ccw(in));
if (is_infinite(vv)) {
if (is_infinite(v2))
cut_after = hit;
}
else { // vv is a finite vertex
const Point &p = vv->point();
if (coplanar_orientation(p0, p1, p) == COUNTERCLOCKWISE) {
if (is_infinite(v2) ||
coplanar_side_of_bounded_circle(p0, p1, *p2, p, true)
== ON_BOUNDED_SIDE) {
v2 = vv;
p2 = &p;
cut_after = hit;
}
}
}
}
// create new triangle and update adjacency relations
Cell_handle newf;
//update the hole and push back in the Hole_List stack
// if v2 belongs to the neighbor following or preceding *f
// the hole remain a single hole
// otherwise it is split in two holes
fn = (hole.front()).first;
in = (hole.front()).second;
if (fn->has_vertex(v2, i) && i == ccw(in)) {
newf = tds().create_face(ff, ii, fn, in);
hole.pop_front();
hole.push_front(Edge_2D(newf, 1));
hole_list.push_back(hole);
}
else{
fn = (hole.back()).first;
in = (hole.back()).second;
if (fn->has_vertex(v2, i) && i == cw(in)) {
newf = tds().create_face(fn, in, ff, ii);
hole.pop_back();
hole.push_back(Edge_2D(newf, 1));
hole_list.push_back(hole);
}
else{
// split the hole in two holes
newf = tds().create_face(ff, ii, v2);
Hole new_hole;
++cut_after;
while( hole.begin() != cut_after )
{
new_hole.push_back(hole.front());
hole.pop_front();
}
hole.push_front(Edge_2D(newf, 1));
new_hole.push_front(Edge_2D(newf, 0));
hole_list.push_back(hole);
hole_list.push_back(new_hole);
}
}
}
}
template <class Gt, class Tds >
void
Delaunay_triangulation_3<Gt, Tds>::
make_hole_2D(Vertex_handle v, std::list<Edge_2D> & hole)
{
std::vector<Cell_handle> to_delete;
typename Tds::Face_circulator fc = tds().incident_faces(v);
typename Tds::Face_circulator done(fc);
// We prepare for deleting all interior cells.
// We ->set_cell() pointers to cells outside the hole.
// We push the Edges_2D of the boundary (seen from outside) in "hole".
do {
Cell_handle f = fc;
int i = f->index(v);
Cell_handle fn = f->neighbor(i);
int in = fn->index(f);
f->vertex(cw(i))->set_cell(fn);
fn->set_neighbor(in, Cell_handle());
hole.push_back(Edge_2D(fn, in));
to_delete.push_back(f);
++fc;
} while (fc != done);
tds().delete_cells(to_delete.begin(), to_delete.end());
}
template < class Gt, class Tds >
void
Delaunay_triangulation_3<Gt,Tds>::
make_canonical(Vertex_triple& t) const
{
int i = (&*(t.first) < &*(t.second))? 0 : 1;
if(i==0) {
i = (&*(t.first) < &*(t.third))? 0 : 2;
} else {
i = (&*(t.second) < &*(t.third))? 1 : 2;
}
Vertex_handle tmp;
switch(i){
case 0: return;
case 1:
tmp = t.first;
t.first = t.second;
t.second = t.third;
t.third = tmp;
return;
default:
tmp = t.first;
t.first = t.third;
t.third = t.second;
t.second = tmp;
}
}
template < class Gt, class Tds >
typename Delaunay_triangulation_3<Gt,Tds>::Vertex_triple
Delaunay_triangulation_3<Gt,Tds>::
make_vertex_triple(const Facet& f) const
{
// static const int vertex_triple_index[4][3] = { {1, 3, 2}, {0, 2, 3},
// {0, 3, 1}, {0, 1, 2} };
Cell_handle ch = f.first;
int i = f.second;
return Vertex_triple(ch->vertex(vertex_triple_index(i,0)),
ch->vertex(vertex_triple_index(i,1)),
ch->vertex(vertex_triple_index(i,2)));
}
template < class Gt, class Tds >
void
Delaunay_triangulation_3<Gt,Tds>::
remove_3D(Vertex_handle v)
{
std::vector<Facet> boundhole; // facets on the boundary of the hole
boundhole.reserve(64); // 27 on average.
std::vector<Cell_handle> hole;
hole.reserve(64);
make_hole_3D_ear(v, boundhole, hole);
fill_hole_3D_ear(boundhole);
tds().delete_vertex(v);
tds().delete_cells(hole.begin(), hole.end());
}
template < class Gt, class Tds >
void
Delaunay_triangulation_3<Gt,Tds>::
remove_3D_new(Vertex_handle v)
{
std::vector<Cell_handle> hole;
hole.reserve(64);
// Construct the set of vertex triples on the boundary
// with the facet just behind
typedef std::map<Vertex_triple,Facet> Vertex_triple_Facet_map;
Vertex_triple_Facet_map outer_map;
Vertex_triple_Facet_map inner_map;
make_hole_3D_new(v, outer_map, hole);
bool inf = false;
unsigned int i;
// collect all vertices on the boundary
std::vector<Vertex_handle> vertices;
vertices.reserve(64);
incident_vertices(v, std::back_inserter(vertices));
// create a Delaunay triangulation of the points on the boundary
// and make a map from the vertices in aux towards the vertices in *this
Self aux;
Unique_hash_map<Vertex_handle,Vertex_handle> vmap;
Cell_handle ch = Cell_handle();
for(i=0; i < vertices.size(); i++){
if(! is_infinite(vertices[i])){
Vertex_handle vh = aux.insert(vertices[i]->point(), ch);
ch = vh->cell();
vmap[vh] = vertices[i];
}else {
inf = true;
}
}
if(aux.dimension()==2){
Vertex_handle fake_inf = aux.insert(v->point());
vmap[fake_inf] = infinite_vertex();
} else {
vmap[aux.infinite_vertex()] = infinite_vertex();
}
CGAL_triangulation_assertion(aux.dimension() == 3);
// Construct the set of vertex triples of aux
// We reorient the vertex triple so that it matches those from outer_map
// Also note that we use the vertices of *this, not of aux
if(inf){
for(All_cells_iterator it = aux.all_cells_begin();
it != aux.all_cells_end();
++it){
for(i=0; i < 4; i++){
Facet f = std::pair<Cell_handle,int>(it,i);
Vertex_triple vt_aux = make_vertex_triple(f);
Vertex_triple vt(vmap[vt_aux.first],vmap[vt_aux.third],vmap[vt_aux.second]);
make_canonical(vt);
inner_map[vt]= f;
}
}
} else {
for(Finite_cells_iterator it = aux.finite_cells_begin();
it != aux.finite_cells_end();
++it){
for(i=0; i < 4; i++){
Facet f = std::pair<Cell_handle,int>(it,i);
Vertex_triple vt_aux = make_vertex_triple(f);
Vertex_triple vt(vmap[vt_aux.first],vmap[vt_aux.third],vmap[vt_aux.second]);
make_canonical(vt);
inner_map[vt]= f;
}
}
}
// Grow inside the hole, by extending the surface
while(! outer_map.empty()){
typename Vertex_triple_Facet_map::iterator oit = outer_map.begin();
while(is_infinite(oit->first.first) ||
is_infinite(oit->first.second) ||
is_infinite(oit->first.third)){
++oit;
// otherwise the lookup in the inner_map fails
// because the infinite vertices are different
}
typename Vertex_triple_Facet_map::value_type o_vt_f_pair = *oit;
Cell_handle o_ch = o_vt_f_pair.second.first;
unsigned int o_i = o_vt_f_pair.second.second;
typename Vertex_triple_Facet_map::iterator iit =
inner_map.find(o_vt_f_pair.first);
CGAL_triangulation_assertion(iit != inner_map.end());
typename Vertex_triple_Facet_map::value_type i_vt_f_pair = *iit;
Cell_handle i_ch = i_vt_f_pair.second.first;
unsigned int i_i = i_vt_f_pair.second.second;
// create a new cell and glue it to the outer surface
Cell_handle new_ch = tds().create_cell();
new_ch->set_vertices(vmap[i_ch->vertex(0)], vmap[i_ch->vertex(1)],
vmap[i_ch->vertex(2)], vmap[i_ch->vertex(3)]);
o_ch->set_neighbor(o_i,new_ch);
new_ch->set_neighbor(i_i, o_ch);
// for the other faces check, if they can also be glued
for(i = 0; i < 4; i++){
if(i != i_i){
Facet f = std::pair<Cell_handle,int>(new_ch,i);
Vertex_triple vt = make_vertex_triple(f);
make_canonical(vt);
std::swap(vt.second,vt.third);
typename Vertex_triple_Facet_map::iterator oit2 = outer_map.find(vt);
if(oit2 == outer_map.end()){
std::swap(vt.second,vt.third);
outer_map[vt]= f;
} else {
// glue the faces
typename Vertex_triple_Facet_map::value_type o_vt_f_pair2 = *oit2;
Cell_handle o_ch2 = o_vt_f_pair2.second.first;
int o_i2 = o_vt_f_pair2.second.second;
o_ch2->set_neighbor(o_i2,new_ch);
new_ch->set_neighbor(i, o_ch2);
outer_map.erase(oit2);
}
}
}
outer_map.erase(oit);
}
tds().delete_vertex(v);
tds().delete_cells(hole.begin(), hole.end());
}
template < class Gt, class Tds >
bool
Delaunay_triangulation_3<Gt,Tds>::
remove(Vertex_handle v)
{
CGAL_triangulation_precondition( v != Vertex_handle());
CGAL_triangulation_precondition( !is_infinite(v));
CGAL_triangulation_expensive_precondition(is_vertex(v));
if (dimension() >= 0 && test_dim_down(v)) {
tds().remove_decrease_dimension(v);
// Now try to see if we need to re-orient.
if (dimension() == 2) {
Facet f = *finite_facets_begin();
if (coplanar_orientation(f.first->vertex(0)->point(),
f.first->vertex(1)->point(),
f.first->vertex(2)->point()) == NEGATIVE)
tds().reorient();
}
CGAL_triangulation_expensive_postcondition(is_valid());
return true;
}
if (dimension() == 1) {
tds().remove_from_maximal_dimension_simplex(v);
CGAL_triangulation_expensive_postcondition(is_valid());
return true;
}
if (dimension() == 2) {
remove_2D(v);
CGAL_triangulation_expensive_postcondition(is_valid());
return true;
}
CGAL_triangulation_assertion( dimension() == 3 );
#ifdef CGAL_DELAUNAY_3_OLD_REMOVE
remove_3D(v);
#else
remove_3D_new(v);
#endif
CGAL_triangulation_expensive_postcondition(is_valid());
return true;
}
template < class Gt, class Tds >
Oriented_side
Delaunay_triangulation_3<Gt,Tds>::
side_of_oriented_sphere(const Point &p0, const Point &p1, const Point &p2,
const Point &p3, const Point &p, bool perturb) const
{
CGAL_triangulation_precondition( orientation(p0, p1, p2, p3) == POSITIVE );
Oriented_side os =
geom_traits().side_of_oriented_sphere_3_object()(p0, p1, p2, p3, p);
if (os != ON_ORIENTED_BOUNDARY || !perturb)
return os;
// We are now in a degenerate case => we do a symbolic perturbation.
// We sort the points lexicographically.
const Point * points[5] = {&p0, &p1, &p2, &p3, &p};
std::sort(points, points+5, Perturbation_order(this) );
// We successively look whether the leading monomial, then 2nd monomial
// of the determinant has non null coefficient.
// 2 iterations are enough (cf paper)
for (int i=4; i>2; --i) {
if (points[i] == &p)
return ON_NEGATIVE_SIDE; // since p0 p1 p2 p3 are non coplanar
// and positively oriented
Orientation o;
if (points[i] == &p3 && (o = orientation(p0,p1,p2,p)) != COPLANAR )
return Oriented_side(o);
if (points[i] == &p2 && (o = orientation(p0,p1,p,p3)) != COPLANAR )
return Oriented_side(o);
if (points[i] == &p1 && (o = orientation(p0,p,p2,p3)) != COPLANAR )
return Oriented_side(o);
if (points[i] == &p0 && (o = orientation(p,p1,p2,p3)) != COPLANAR )
return Oriented_side(o);
}
CGAL_triangulation_assertion(false);
return ON_NEGATIVE_SIDE;
}
template < class Gt, class Tds >
Bounded_side
Delaunay_triangulation_3<Gt,Tds>::
coplanar_side_of_bounded_circle(const Point &p0, const Point &p1,
const Point &p2, const Point &p, bool perturb) const
{
// In dim==2, we should even be able to assert orient == POSITIVE.
CGAL_triangulation_precondition( coplanar_orientation(p0, p1, p2)
!= COLLINEAR );
Bounded_side bs =
geom_traits().coplanar_side_of_bounded_circle_3_object()(p0, p1, p2, p);
if (bs != ON_BOUNDARY || !perturb)
return bs;
// We are now in a degenerate case => we do a symbolic perturbation.
// We sort the points lexicographically.
const Point * points[4] = {&p0, &p1, &p2, &p};
std::sort(points, points+4, Perturbation_order(this) );
Orientation local = coplanar_orientation(p0, p1, p2);
// we successively look whether the leading monomial, then 2nd monimial,
// then 3rd monomial, of the determinant which has non null coefficient
// [syl] : TODO : Probably it can be stopped earlier like the 3D version
for (int i=3; i>0; --i) {
if (points[i] == &p)
return Bounded_side(NEGATIVE); // since p0 p1 p2 are non collinear
// but not necessarily positively oriented
Orientation o;
if (points[i] == &p2
&& (o = coplanar_orientation(p0,p1,p)) != COLLINEAR )
// [syl] : TODO : I'm not sure of the signs here (nor the rest :)
return Bounded_side(o*local);
if (points[i] == &p1
&& (o = coplanar_orientation(p0,p,p2)) != COLLINEAR )
return Bounded_side(o*local);
if (points[i] == &p0
&& (o = coplanar_orientation(p,p1,p2)) != COLLINEAR )
return Bounded_side(o*local);
}
// case when the first non null coefficient is the coefficient of
// the 4th monomial
// moreover, the tests (points[] == &p) were false up to here, so the
// monomial corresponding to p is the only monomial with non-zero
// coefficient, it is equal to coplanar_orient(p0,p1,p2) == positive
// so, no further test is required
return Bounded_side(-local); //ON_UNBOUNDED_SIDE;
}
template < class Gt, class Tds >
Bounded_side
Delaunay_triangulation_3<Gt,Tds>::
side_of_sphere(const Vertex_handle& v0, const Vertex_handle& v1,
const Vertex_handle& v2, const Vertex_handle& v3,
const Point &p, bool perturb) const
{
CGAL_triangulation_precondition( dimension() == 3 );
// TODO :
// - avoid accessing points of infinite vertex
// - share the 4 codes below (see old version)
const Point &p0 = v0->point();
const Point &p1 = v1->point();
const Point &p2 = v2->point();
const Point &p3 = v3->point();
if (is_infinite(v0)) {
Orientation o = orientation(p2, p1, p3, p);
if (o != COPLANAR)
return Bounded_side(o);
return coplanar_side_of_bounded_circle(p2, p1, p3, p, perturb);
}
if (is_infinite(v1)) {
Orientation o = orientation(p2, p3, p0, p);
if (o != COPLANAR)
return Bounded_side(o);
return coplanar_side_of_bounded_circle(p2, p3, p0, p, perturb);
}
if (is_infinite(v2)) {
Orientation o = orientation(p1, p0, p3, p);
if (o != COPLANAR)
return Bounded_side(o);
return coplanar_side_of_bounded_circle(p1, p0, p3, p, perturb);
}
if (is_infinite(v3)) {
Orientation o = orientation(p0, p1, p2, p);
if (o != COPLANAR)
return Bounded_side(o);
return coplanar_side_of_bounded_circle(p0, p1, p2, p, perturb);
}
return (Bounded_side) side_of_oriented_sphere(p0, p1, p2, p3, p, perturb);
}
template < class Gt, class Tds >
Bounded_side
Delaunay_triangulation_3<Gt,Tds>::
side_of_circle(const Cell_handle& c, int i,
const Point & p, bool perturb) const
// precondition : dimension >=2
// in dimension 3, - for a finite facet
// returns ON_BOUNDARY if the point lies on the circle,
// ON_UNBOUNDED_SIDE when exterior, ON_BOUNDED_SIDE
// interior
// for an infinite facet, considers the plane defined by the
// adjacent finite facet of the same cell, and does the same as in
// dimension 2 in this plane
// in dimension 2, for an infinite facet
// in this case, returns ON_BOUNDARY if the point lies on the
// finite edge (endpoints included)
// ON_BOUNDED_SIDE for a point in the open half-plane
// ON_UNBOUNDED_SIDE elsewhere
{
CGAL_triangulation_precondition( dimension() >= 2 );
int i3 = 5;
if ( dimension() == 2 ) {
CGAL_triangulation_precondition( i == 3 );
// the triangulation is supposed to be valid, ie the facet
// with vertices 0 1 2 in this order is positively oriented
if ( ! c->has_vertex( infinite_vertex(), i3 ) )
return coplanar_side_of_bounded_circle( c->vertex(0)->point(),
c->vertex(1)->point(),
c->vertex(2)->point(),
p, perturb);
// else infinite facet
// v1, v2 finite vertices of the facet such that v1,v2,infinite
// is positively oriented
Vertex_handle v1 = c->vertex( ccw(i3) ),
v2 = c->vertex( cw(i3) );
CGAL_triangulation_assertion(coplanar_orientation(v1->point(), v2->point(),
mirror_vertex(c, i3)->point()) == NEGATIVE);
Orientation o = coplanar_orientation(v1->point(), v2->point(), p);
if ( o != COLLINEAR )
return Bounded_side( o );
// because p is in f iff
// it does not lie on the same side of v1v2 as vn
int i_e;
Locate_type lt;
// case when p collinear with v1v2
return side_of_segment( p,
v1->point(), v2->point(),
lt, i_e );
}
// else dimension == 3
CGAL_triangulation_precondition( i >= 0 && i < 4 );
if ( ( ! c->has_vertex(infinite_vertex(),i3) ) || ( i3 != i ) ) {
// finite facet
// initialization of i0 i1 i2, vertices of the facet positively
// oriented (if the triangulation is valid)
int i0 = (i>0) ? 0 : 1;
int i1 = (i>1) ? 1 : 2;
int i2 = (i>2) ? 2 : 3;
CGAL_triangulation_precondition( coplanar( c->vertex(i0)->point(),
c->vertex(i1)->point(),
c->vertex(i2)->point(),
p ) );
return coplanar_side_of_bounded_circle( c->vertex(i0)->point(),
c->vertex(i1)->point(),
c->vertex(i2)->point(),
p, perturb);
}
//else infinite facet
// v1, v2 finite vertices of the facet such that v1,v2,infinite
// is positively oriented
Vertex_handle v1 = c->vertex( next_around_edge(i3,i) ),
v2 = c->vertex( next_around_edge(i,i3) );
Orientation o = (Orientation)
(coplanar_orientation( v1->point(), v2->point(),
c->vertex(i)->point()) *
coplanar_orientation( v1->point(), v2->point(), p ));
// then the code is duplicated from 2d case
if ( o != COLLINEAR )
return Bounded_side( -o );
// because p is in f iff
// it is not on the same side of v1v2 as c->vertex(i)
int i_e;
Locate_type lt;
// case when p collinear with v1v2
return side_of_segment( p,
v1->point(), v2->point(),
lt, i_e );
}
template < class Gt, class Tds >
typename Delaunay_triangulation_3<Gt,Tds>::Vertex_handle
Delaunay_triangulation_3<Gt,Tds>::
nearest_vertex_in_cell(const Point& p, const Cell_handle& c) const
// Returns the finite vertex of the cell c which is the closest to p.
{
CGAL_triangulation_precondition(dimension() >= 1);
Vertex_handle nearest = nearest_vertex(p, c->vertex(0), c->vertex(1));
if (dimension() >= 2) {
nearest = nearest_vertex(p, nearest, c->vertex(2));
if (dimension() == 3)
nearest = nearest_vertex(p, nearest, c->vertex(3));
}
return nearest;
}
template < class Gt, class Tds >
typename Delaunay_triangulation_3<Gt,Tds>::Vertex_handle
Delaunay_triangulation_3<Gt,Tds>::
nearest_vertex(const Point& p, Cell_handle start) const
{
if (number_of_vertices() == 0)
return Vertex_handle();
// Use a brute-force algorithm if dimension < 3.
if (dimension() < 3) {
Finite_vertices_iterator vit = finite_vertices_begin();
Vertex_handle res = vit;
for (++vit; vit != finite_vertices_end(); ++vit)
res = nearest_vertex(p, res, vit);
return res;
}
Locate_type lt;
int li, lj;
Cell_handle c = locate(p, lt, li, lj, start);
if (lt == Tr_Base::VERTEX)
return c->vertex(li);
// - start with the closest vertex from the located cell.
// - repeatedly take the nearest of its incident vertices if any
// - if not, we're done.
Vertex_handle nearest = nearest_vertex_in_cell(p, c);
std::vector<Vertex_handle> vs;
vs.reserve(32);
while (true) {
Vertex_handle tmp = nearest;
incident_vertices(nearest, std::back_inserter(vs));
for (typename std::vector<Vertex_handle>::const_iterator
vsit = vs.begin(); vsit != vs.end(); ++vsit)
tmp = nearest_vertex(p, tmp, *vsit);
if (tmp == nearest)
break;
vs.clear();
nearest = tmp;
}
return nearest;
}
template < class Gt, class Tds >
bool
Delaunay_triangulation_3<Gt,Tds>::
is_Gabriel(const Facet& f) const
{
return is_Gabriel(f.first, f.second);
}
template < class Gt, class Tds >
bool
Delaunay_triangulation_3<Gt,Tds>::
is_Gabriel(Cell_handle c, int i) const
{
CGAL_triangulation_precondition(dimension() == 3 && !is_infinite(c,i));
typename Geom_traits::Side_of_bounded_sphere_3
side_of_bounded_sphere =
geom_traits().side_of_bounded_sphere_3_object();
if ((!is_infinite(c->vertex(i))) &&
side_of_bounded_sphere (
c->vertex(vertex_triple_index(i,0))->point(),
c->vertex(vertex_triple_index(i,1))->point(),
c->vertex(vertex_triple_index(i,2))->point(),
c->vertex(i)->point()) == ON_BOUNDED_SIDE ) return false;
Cell_handle neighbor = c->neighbor(i);
int in = neighbor->index(c);
if ((!is_infinite(neighbor->vertex(in))) &&
side_of_bounded_sphere(
c->vertex(vertex_triple_index(i,0))->point(),
c->vertex(vertex_triple_index(i,1))->point(),
c->vertex(vertex_triple_index(i,2))->point(),
neighbor->vertex(in)->point()) == ON_BOUNDED_SIDE ) return false;
return true;
}
template < class Gt, class Tds >
bool
Delaunay_triangulation_3<Gt,Tds>::
is_Gabriel(const Edge& e) const
{
return is_Gabriel(e.first, e.second, e.third);
}
template < class Gt, class Tds >
bool
Delaunay_triangulation_3<Gt,Tds>::
is_Gabriel(Cell_handle c, int i, int j) const
{
CGAL_triangulation_precondition(dimension() == 3 && !is_infinite(c,i,j));
typename Geom_traits::Side_of_bounded_sphere_3
side_of_bounded_sphere =
geom_traits().side_of_bounded_sphere_3_object();
Facet_circulator fcirc = incident_facets(c,i,j),
fdone(fcirc);
Vertex_handle v1 = c->vertex(i);
Vertex_handle v2 = c->vertex(j);
do {
// test whether the vertex of cc opposite to *fcirc
// is inside the sphere defined by the edge e = (s, i,j)
Cell_handle cc = (*fcirc).first;
int ii = (*fcirc).second;
if (!is_infinite(cc->vertex(ii)) &&
side_of_bounded_sphere( v1->point(),
v2->point(),
cc->vertex(ii)->point())
== ON_BOUNDED_SIDE ) return false;
} while(++fcirc != fdone);
return true;
}
template < class Gt, class Tds >
typename Delaunay_triangulation_3<Gt,Tds>::Point
Delaunay_triangulation_3<Gt,Tds>::
dual(Cell_handle c) const
{
CGAL_triangulation_precondition(dimension()==3);
CGAL_triangulation_precondition( ! is_infinite(c) );
return construct_circumcenter( c->vertex(0)->point(),
c->vertex(1)->point(),
c->vertex(2)->point(),
c->vertex(3)->point() );
}
template < class Gt, class Tds >
typename Delaunay_triangulation_3<Gt,Tds>::Object
Delaunay_triangulation_3<Gt,Tds>::
dual(Cell_handle c, int i) const
{
CGAL_triangulation_precondition(dimension()>=2);
CGAL_triangulation_precondition( ! is_infinite(c,i) );
if ( dimension() == 2 ) {
CGAL_triangulation_precondition( i == 3 );
return construct_object( construct_circumcenter(c->vertex(0)->point(),
c->vertex(1)->point(),
c->vertex(2)->point()) );
}
// dimension() == 3
Cell_handle n = c->neighbor(i);
if ( ! is_infinite(c) && ! is_infinite(n) )
return construct_object(construct_segment( dual(c), dual(n) ));
// either n or c is infinite
int in;
if ( is_infinite(c) )
in = n->index(c);
else {
n = c;
in = i;
}
// n now denotes a finite cell, either c or c->neighbor(i)
unsigned char ind[3] = {(in+1)&3,(in+2)&3,(in+3)&3};
if ( (in&1) == 1 )
std::swap(ind[0], ind[1]);
const Point& p = n->vertex(ind[0])->point();
const Point& q = n->vertex(ind[1])->point();
const Point& r = n->vertex(ind[2])->point();
Line l = construct_perpendicular_line( construct_plane(p,q,r),
construct_circumcenter(p,q,r) );
return construct_object(construct_ray( dual(n), l));
}
template < class Gt, class Tds >
bool
Delaunay_triangulation_3<Gt,Tds>::
is_valid(bool verbose, int level) const
{
if ( ! tds().is_valid(verbose,level) ) {
if (verbose)
std::cerr << "invalid data structure" << std::endl;
CGAL_triangulation_assertion(false);
return false;
}
if ( infinite_vertex() == Vertex_handle() ) {
if (verbose)
std::cerr << "no infinite vertex" << std::endl;
CGAL_triangulation_assertion(false);
return false;
}
switch ( dimension() ) {
case 3:
{
Finite_cells_iterator it;
for ( it = finite_cells_begin(); it != finite_cells_end(); ++it ) {
is_valid_finite(it);
for (int i=0; i<4; i++ ) {
if ( !is_infinite
(it->neighbor(i)->vertex(it->neighbor(i)->index(it))) ) {
if ( side_of_sphere
(it,
it->neighbor(i)->vertex(it->neighbor(i)->index(it))->point())
== ON_BOUNDED_SIDE ) {
if (verbose)
std::cerr << "non-empty sphere " << std::endl;
CGAL_triangulation_assertion(false);
return false;
}
}
}
}
break;
}
case 2:
{
Finite_facets_iterator it;
for ( it = finite_facets_begin(); it != finite_facets_end(); ++it ) {
is_valid_finite((*it).first);
for (int i=0; i<3; i++ ) {
if( !is_infinite
((*it).first->neighbor(i)->vertex( (((*it).first)->neighbor(i))
->index((*it).first))) ) {
if ( side_of_circle ( (*it).first, 3,
(*it).first->neighbor(i)->
vertex( (((*it).first)->neighbor(i))
->index((*it).first) )->point() )
== ON_BOUNDED_SIDE ) {
if (verbose)
std::cerr << "non-empty circle " << std::endl;
CGAL_triangulation_assertion(false);
return false;
}
}
}
}
break;
}
case 1:
{
Finite_edges_iterator it;
for ( it = finite_edges_begin(); it != finite_edges_end(); ++it )
is_valid_finite((*it).first);
break;
}
}
if (verbose)
std::cerr << "Delaunay valid triangulation" << std::endl;
return true;
}
template < class Gt, class Tds >
bool
Delaunay_triangulation_3<Gt,Tds>::
is_valid(Cell_handle c, bool verbose, int level) const
{
if ( ! Tr_Base::is_valid(c,verbose,level) ) {
if (verbose) {
std::cerr << "combinatorically invalid cell" ;
for (int i=0; i <= dimension(); i++ )
std::cerr << c->vertex(i)->point() << ", " ;
std::cerr << std::endl;
}
CGAL_triangulation_assertion(false);
return false;
}
switch ( dimension() ) {
case 3:
{
if ( ! is_infinite(c) ) {
is_valid_finite(c,verbose,level);
for (int i=0; i<4; i++ ) {
if (side_of_sphere(c, c->vertex((c->neighbor(i))->index(c))->point())
== ON_BOUNDED_SIDE ) {
if (verbose)
std::cerr << "non-empty sphere " << std::endl;
CGAL_triangulation_assertion(false);
return false;
}
}
}
break;
}
case 2:
{
if ( ! is_infinite(c,3) ) {
for (int i=0; i<2; i++ ) {
if (side_of_circle(c, 3, c->vertex(c->neighbor(i)->index(c))->point())
== ON_BOUNDED_SIDE ) {
if (verbose)
std::cerr << "non-empty circle " << std::endl;
CGAL_triangulation_assertion(false);
return false;
}
}
}
break;
}
}
if (verbose)
std::cerr << "Delaunay valid cell" << std::endl;
return true;
}
#ifndef CGAL_CFG_NET2003_MATCHING_BUG
template < class Gt, class Tds >
void
Delaunay_triangulation_3<Gt,Tds>::
make_hole_3D_ear( Vertex_handle v,
std::vector<Facet> & boundhole,
std::vector<Cell_handle> & hole)
{
CGAL_triangulation_expensive_precondition( ! test_dim_down(v) );
incident_cells(v, std::back_inserter(hole));
for (typename std::vector<Cell_handle>::iterator cit = hole.begin();
cit != hole.end(); ++cit) {
int indv = (*cit)->index(v);
Cell_handle opp_cit = (*cit)->neighbor( indv );
boundhole.push_back(Facet( opp_cit, opp_cit->index(*cit)) );
for (int i=0; i<4; i++)
if ( i != indv )
(*cit)->vertex(i)->set_cell(opp_cit);
}
}
#endif
template < class Gt, class Tds >
void
Delaunay_triangulation_3<Gt,Tds>::
make_hole_3D_new( Vertex_handle v,
std::map<Vertex_triple,Facet>& outer_map,
std::vector<Cell_handle> & hole)
{
CGAL_triangulation_expensive_precondition( ! test_dim_down(v) );
incident_cells(v, std::back_inserter(hole));
for (typename std::vector<Cell_handle>::iterator cit = hole.begin();
cit != hole.end(); ++cit) {
int indv = (*cit)->index(v);
Cell_handle opp_cit = (*cit)->neighbor( indv );
Facet f(opp_cit, opp_cit->index(*cit));
Vertex_triple vt = make_vertex_triple(f);
make_canonical(vt);
outer_map[vt] = f;
for (int i=0; i<4; i++)
if ( i != indv )
(*cit)->vertex(i)->set_cell(opp_cit);
}
}
template < class Gt, class Tds >
void
Delaunay_triangulation_3<Gt,Tds>::
fill_hole_3D_ear(const std::vector<Facet> & boundhole)
{
typedef Delaunay_remove_tds_3_2<Delaunay_triangulation_3> Surface;
typedef typename Surface::Face_3_2 Face_3_2;
typedef typename Surface::Face_handle_3_2 Face_handle_3_2;
typedef typename Surface::Vertex_handle_3_2 Vertex_handle_3_2;
Surface surface(boundhole);
Face_handle_3_2 f = surface.faces_begin();
Face_handle_3_2 last_op = f; // This is where the last ear was inserted
int k = -1;
// This is a loop over the halfedges of the surface of the hole
// As edges are not explicitely there, we loop over the faces instead,
// and an index.
// The current face is f, the current index is k = -1, 0, 1, 2
for(;;) {
next_edge: ;
k++;
if(k == 3) {
// The faces form a circular list. With f->n() we go to the next face.
f = f->n();
CGAL_assertion_msg(f != last_op, "Unable to find an ear");
k = 0;
}
// The edges are marked, if they are a candidate for an ear.
// This saves time, for example an edge gets not considered
// from both adjacent faces.
if (!f->is_halfedge_marked(k))
continue;
Vertex_handle_3_2 w0, w1, w2, w3;
Vertex_handle v0, v1, v2, v3;
int i = ccw(k);
int j = cw(k);
Face_handle_3_2 n = f->neighbor(k);
int fi = n->index(f);
w1 = f->vertex(i);
w2 = f->vertex(j);
v1 = w1->info();
v2 = w2->info();
if( is_infinite(v1) || is_infinite(v2) ){
// there will be another ear, so let's ignore this one,
// because it is complicated to treat
continue;
}
w0 = f->vertex(k);
w3 = n->vertex(fi);
v0 = w0->info();
v3 = w3->info();
if( !is_infinite(v0) && !is_infinite(v3) &&
orientation(v0->point(), v1->point(),
v2->point(), v3->point()) != POSITIVE)
continue;
// the two faces form a concavity, in which we might plug a cell
// we now look at all vertices that are on the boundary of the hole
for(typename Surface::Vertex_iterator vit = surface.vertices_begin();
vit != surface.vertices_end(); ++vit) {
Vertex_handle v = vit->info();
if (is_infinite(v) || v == v0 || v == v1 || v == v2 || v == v3)
continue;
if (side_of_sphere(v0,v1,v2,v3, v->point(), true) == ON_BOUNDED_SIDE)
goto next_edge;
}
// we looked at all vertices
Face_handle_3_2 m_i = f->neighbor(i);
Face_handle_3_2 m_j = f->neighbor(j);
bool neighbor_i = m_i == n->neighbor(cw(fi));
bool neighbor_j = m_j == n->neighbor(ccw(fi));
// Test if the edge that would get introduced is on the surface
if ( !neighbor_i && !neighbor_j &&
surface.is_edge(f->vertex(k), n->vertex(fi)))
continue;
// none of the vertices violates the Delaunay property
// We are ready to plug a new cell
Cell_handle ch = tds().create_cell(v0, v1, v2, v3);
// The new cell touches the faces that form the ear
Facet fac = n->info();
tds().set_adjacency(ch, 0, fac.first, fac.second);
fac = f->info();
tds().set_adjacency(ch, 3, fac.first, fac.second);
// It may touch another face,
// or even two other faces if it is the last cell
if(neighbor_i) {
fac = m_i->info();
tds().set_adjacency(ch, 1, fac.first, fac.second);
}
if(neighbor_j) {
fac = m_j->info();
tds().set_adjacency(ch, 2, fac.first, fac.second);
}
if( !neighbor_i && !neighbor_j) {
surface.flip(f,k);
int fi = n->index(f);
int ni = f->index(n);
// The flipped edge is not a concavity
f->unmark_edge(ni);
// The adjacent edges may be a concavity
// that is they are candidates for an ear
// In the list of faces they get moved behind f
f->mark_edge(cw(ni), f);
f->mark_edge(ccw(ni), f);
n->mark_edge(cw(fi), f);
n->mark_edge(ccw(fi), f);
f->set_info(Facet(ch,2));
n->set_info(Facet(ch,1));
} else if (neighbor_i && (! neighbor_j)) {
surface.remove_degree_3(f->vertex(j), f);
// all three edges adjacent to f are
// candidate for an ear
f->mark_adjacent_edges();
f->set_info(Facet(ch,2));
} else if ((! neighbor_i) && neighbor_j) {
surface.remove_degree_3(f->vertex(i), f);
f->mark_adjacent_edges();
f->set_info(Facet(ch,1));
} else {
CGAL_assertion(surface.number_of_vertices() == 4);
// when we leave the function the vertices and faces of the surface
// are deleted by the destructor
return;
}
// we successfully inserted a cell
last_op = f;
// we have to reconsider all edges incident to f
k = -1;
} // for(;;)
}
CGAL_END_NAMESPACE
#endif // CGAL_DELAUNAY_TRIANGULATION_3_H
| [
"viticm@126.com"
] | viticm@126.com |
9a793f0bee197ceed6ec4499504bcf175ea5ed64 | 49e4e03786019f9c346570d7276c8ded43cbd86b | /firmware/AlarmsManager.cpp | bf853222eea93ada0b220a916f733c19df4833b4 | [] | no_license | nickswalker/tock | b94060a658293af12cfd48fd6addabe00bb0a239 | 6ac5dc737a85c1b5080c8164bb65d493d241e1e8 | refs/heads/master | 2021-01-22T17:47:33.724302 | 2015-02-01T06:16:50 | 2015-02-01T06:16:50 | 14,816,265 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,674 | cpp | #include "AlarmsManager.h"
#include "AlarmT.h"
#include "Time.h"
#include "Settings.h"
#include <EEPROM.h>
void AlarmsManager::setAlarm(AlarmNumber alarmNumber, AlarmT alarm){
EEPROM.write(Settings::getAlarmMinuteAddress(alarmNumber), alarm.getTriggerMinute());
EEPROM.write(Settings::getAlarmHourAddress(alarmNumber), alarm.getTriggerHour());
EEPROM.write(Settings::getAlarmRepeatAddress(alarmNumber), alarm.getSchedule());
}
AlarmNumber AlarmsManager::getNextEmptyAlarm(){
for(int i = 0; i < 8; i++){
AlarmT testAlarm = AlarmT((AlarmNumber)i);
if(testAlarm.getIntRepresentation() == 0) {
return (AlarmNumber)i;
}
}
return (AlarmNumber)0;
}
boolean AlarmsManager::checkIfTimeTriggersAnyAlarm(uint8_t hour, uint8_t minute){
for(int i = 0; i < 8; i++){
AlarmT testAlarm = AlarmT((AlarmNumber)i);
if(testAlarm.getTriggerHour() == hour && testAlarm.getTriggerMinute() == minute ) {
if(testAlarm.isOn() && testAlarm.isActiveOnDay((timeDayOfWeek_t)weekday())){
return true;
}
}
}
return false;
}
void AlarmsManager::clearAlarm(AlarmNumber alarmNumber){
EEPROM.write(Settings::getAlarmMinuteAddress(alarmNumber), 0);
EEPROM.write(Settings::getAlarmHourAddress(alarmNumber), 0);
EEPROM.write(Settings::getAlarmRepeatAddress(alarmNumber), 0);
}
AlarmT AlarmsManager::getAlarm(AlarmNumber alarmNumber){
return AlarmT(EEPROM.read(Settings::getAlarmRepeatAddress(alarmNumber)),
EEPROM.read(Settings::getAlarmHourAddress(alarmNumber)),
EEPROM.read(Settings::getAlarmMinuteAddress(alarmNumber))
);
}
| [
"nick@nickswalker.com"
] | nick@nickswalker.com |
373e291faf8ead7fe303882207ff8dfdae2d0706 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE762_Mismatched_Memory_Management_Routines/s01/CWE762_Mismatched_Memory_Management_Routines__delete_array_int64_t_realloc_32.cpp | df36ca93e5584b240c65c85718496cbe5c1553b8 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 3,667 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_int64_t_realloc_32.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml
Template File: sources-sinks-32.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: realloc Allocate data using realloc()
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete []
* Flow Variant: 32 Data flow using two pointers to the same value within the same function
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_int64_t_realloc_32
{
#ifndef OMITBAD
void bad()
{
int64_t * data;
int64_t * *dataPtr1 = &data;
int64_t * *dataPtr2 = &data;
/* Initialize data*/
data = NULL;
{
int64_t * data = *dataPtr1;
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (int64_t *)realloc(data, 100*sizeof(int64_t));
*dataPtr1 = data;
}
{
int64_t * data = *dataPtr2;
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
int64_t * data;
int64_t * *dataPtr1 = &data;
int64_t * *dataPtr2 = &data;
/* Initialize data*/
data = NULL;
{
int64_t * data = *dataPtr1;
/* FIX: Allocate memory using new [] */
data = new int64_t[100];
*dataPtr1 = data;
}
{
int64_t * data = *dataPtr2;
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
}
/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2G()
{
int64_t * data;
int64_t * *dataPtr1 = &data;
int64_t * *dataPtr2 = &data;
/* Initialize data*/
data = NULL;
{
int64_t * data = *dataPtr1;
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (int64_t *)realloc(data, 100*sizeof(int64_t));
*dataPtr1 = data;
}
{
int64_t * data = *dataPtr2;
/* FIX: Free memory using free() */
free(data);
}
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_int64_t_realloc_32; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
5fda5bfc215a15601646edcfb31c1b76e9cd6874 | 8c8625977a22b340f8290761ad153a3b7f0055b1 | /src/qt/clientmodel.h | 4fc36f3c62307b96e17980a13313102cea4e674b | [
"MIT"
] | permissive | nigelflaming/VYI | 8979c83167fa9e73adcdd5e70a1ce2fc8d12cfae | 487e699959fe1191a7de6af4b657b74f80a365fd | refs/heads/master | 2020-03-29T13:41:03.345265 | 2018-06-27T10:57:46 | 2018-06-27T10:57:46 | 149,976,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,156 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017 The Vyigrat developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_CLIENTMODEL_H
#define BITCOIN_QT_CLIENTMODEL_H
#include <QObject>
class AddressTableModel;
class OptionsModel;
class PeerTableModel;
class TransactionTableModel;
class CWallet;
QT_BEGIN_NAMESPACE
class QDateTime;
class QTimer;
QT_END_NAMESPACE
enum BlockSource {
BLOCK_SOURCE_NONE,
BLOCK_SOURCE_REINDEX,
BLOCK_SOURCE_DISK,
BLOCK_SOURCE_NETWORK
};
enum NumConnections {
CONNECTIONS_NONE = 0,
CONNECTIONS_IN = (1U << 0),
CONNECTIONS_OUT = (1U << 1),
CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
};
/** Model for Vyigrat network client. */
class ClientModel : public QObject
{
Q_OBJECT
public:
explicit ClientModel(OptionsModel* optionsModel, QObject* parent = 0);
~ClientModel();
OptionsModel* getOptionsModel();
PeerTableModel* getPeerTableModel();
//! Return number of connections, default is in- and outbound (total)
int getNumConnections(unsigned int flags = CONNECTIONS_ALL) const;
QString getMasternodeCountString() const;
int getNumBlocks() const;
int getNumBlocksAtStartup();
quint64 getTotalBytesRecv() const;
quint64 getTotalBytesSent() const;
double getVerificationProgress() const;
QDateTime getLastBlockDate() const;
//! Return true if core is doing initial block download
bool inInitialBlockDownload() const;
//! Return true if core is importing blocks
enum BlockSource getBlockSource() const;
//! Return warnings to be displayed in status bar
QString getStatusBarWarnings() const;
QString formatFullVersion() const;
QString formatBuildDate() const;
bool isReleaseVersion() const;
QString clientName() const;
QString formatClientStartupTime() const;
private:
OptionsModel* optionsModel;
PeerTableModel* peerTableModel;
int cachedNumBlocks;
QString cachedMasternodeCountString;
bool cachedReindexing;
bool cachedImporting;
int numBlocksAtStartup;
QTimer* pollTimer;
QTimer* pollMnTimer;
void subscribeToCoreSignals();
void unsubscribeFromCoreSignals();
signals:
void numConnectionsChanged(int count);
void numBlocksChanged(int count);
void strMasternodesChanged(const QString& strMasternodes);
void alertsChanged(const QString& warnings);
void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut);
//! Fired when a message should be reported to the user
void message(const QString& title, const QString& message, unsigned int style);
// Show progress dialog e.g. for verifychain
void showProgress(const QString& title, int nProgress);
public slots:
void updateTimer();
void updateMnTimer();
void updateNumConnections(int numConnections);
void updateAlert(const QString& hash, int status);
};
#endif // BITCOIN_QT_CLIENTMODEL_H
| [
"sarkawt909@yahoo.com"
] | sarkawt909@yahoo.com |
58e0d8d2ee0d28d51410b91d119adc94397d66ee | b7dddc7e7b9b98d661abe05fcc9ba98c6746112d | /CountAndSay/main.cpp | 13b2153bd82a36d249a0a7d5c608f44598eada74 | [] | no_license | scutLaoYi/leetcode | 7427c4c76b993e31d3f62bf8f04106ea2daeba77 | bfd959c5f0418f0f7de3e883e2746753ba0232bc | refs/heads/master | 2021-01-19T09:41:48.995695 | 2015-01-06T12:40:03 | 2015-01-06T12:40:03 | 28,499,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 211 | cpp | #include <iostream>
#include "CountAndSay.h"
using namespace std;
int main()
{
int n;
while(cin>>n)
{
Solution solution;
cout<<solution.countAndSay(n)<<endl;
}
return 0;
}
| [
"scutLaoYi@gmail.com"
] | scutLaoYi@gmail.com |
d28699999a7a17a0ae9bb6023844746b3afd42bf | 3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9 | /cpp/E/E/E/D/C/AEEEDC.cpp | f17fe340a08f0ef0ed372267c2bec2d1e7c39b8a | [] | no_license | devsisters/2021-NDC-ICECREAM | 7cd09fa2794cbab1ab4702362a37f6ab62638d9b | ac6548f443a75b86d9e9151ff9c1b17c792b2afd | refs/heads/master | 2023-03-19T06:29:03.216461 | 2021-03-10T02:53:14 | 2021-03-10T02:53:14 | 341,872,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 108 | cpp | #include "AEEEDC.h"
namespace AEEEDC {
std::string run() {
std::string out("AEEEDC");
return out;
}
} | [
"nakhyun@devsisters.com"
] | nakhyun@devsisters.com |
803510f111c085ef08faf548261d2be1cfb4fdf4 | d26652dc856c66276f1aa17f8ce714c47bea4b64 | /Editor/EditorInterop/EntityFactory.cpp | e4027f7f35ba59f111456a24025e3f94eacd3d19 | [] | no_license | PeterValtersson/Editor | 7b759f04918cb5b69d237d46e159ab338eaea93d | 78206df6b749b88b7a9b11825d5005a1d2f473f2 | refs/heads/master | 2023-03-15T10:18:23.041658 | 2023-03-08T20:47:46 | 2023-03-08T20:47:46 | 237,368,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44 | cpp | #include "pch.h"
#include "EntityFactory.h"
| [
"peter.walter.valtersson@gmail.com"
] | peter.walter.valtersson@gmail.com |
b3bf676ba2b392db55e41e72755af55f08a3a16f | 009c5fae8003f25e92e3dbf149e3177fefbc8d56 | /recombination.h | 7e38d5ac2ff57bd7816653f4d4f83179be90e4f7 | [] | no_license | fuyiqing/mpi_openmp_mopso | 963d3aa3057b81590d557fde03973ffdb6bb790c | 7ede129d2efe25b2bf50abb610079b3d0854a6eb | refs/heads/master | 2022-03-26T22:25:51.057138 | 2016-03-02T07:26:36 | 2016-03-02T07:26:36 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,531 | h | #ifndef _RECOMBINATION_H_
#define _RECOMBINATION_H_
#include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <memory.h>
#include"random.h"
//目标函数数、每个粒子的维度、邻居数量、粒子数量、进化次数
const int numObjectives = 2;
const int numVariables = 10;
const int numCores = 5;
const int numParticles = 100;
const int numNeighbors = numParticles/numCores;
const int numThreads = numParticles/numCores;
const int mg = 500;
const int numExchange = 2;
// bounds of variables
double lowBound = 0, uppBound = 1;
int seed = 237;
long rnd_uni_init;
int id_cx = 20; // crossover
int id_mu = 20; // for mutation
/* Routine for real polynomial mutation of an T */
template <class T>
void realmutation(T &ind, double rate)
{
double rnd, delta1, delta2, mut_pow, deltaq;
double y, yl, yu, val, xy;
double eta_m = id_mu;
int id_rnd = int(rnd_uni(&rnd_uni_init)*numVariables);
for (int j=0; j<numVariables; j++)
{
if (rnd_uni(&rnd_uni_init)<=rate)
{
y = ind.x_var[j];
yl = lowBound;
yu = uppBound;
delta1 = (y-yl)/(yu-yl);
delta2 = (yu-y)/(yu-yl);
rnd = rnd_uni(&rnd_uni_init);
mut_pow = 1.0/(eta_m+1.0);
if (rnd <= 0.5)
{
xy = 1.0-delta1;
val = 2.0*rnd+(1.0-2.0*rnd)*(pow(xy,(eta_m+1.0)));
deltaq = pow(val,mut_pow) - 1.0;
}
else
{
xy = 1.0-delta2;
val = 2.0*(1.0-rnd)+2.0*(rnd-0.5)*(pow(xy,(eta_m+1.0)));
deltaq = 1.0 - (pow(val,mut_pow));
}
y = y + deltaq*(yu-yl);
if (y<yl)
y = yl;
if (y>yu)
y = yu;
ind.x_var[j] = y;
}
}
return;
}
/* Routine for real variable SBX crossover */
template <class T>
void realbinarycrossover (T &parent1, T &parent2, T& child1, T& child2)
{
double rand;
double y1, y2, yl, yu;
double c1, c2;
double alpha, beta, betaq;
double eta_c = id_cx;
if (rnd_uni(&rnd_uni_init) <= 1.0)
{
for (int i=0; i<numVariables; i++)
{
if (rnd_uni(&rnd_uni_init)<=0.5 )
{
if (fabs(parent1.x_var[i]-parent2.x_var[i]) > EPS)
{
if (parent1.x_var[i] < parent2.x_var[i])
{
y1 = parent1.x_var[i];
y2 = parent2.x_var[i];
}
else
{
y1 = parent2.x_var[i];
y2 = parent1.x_var[i];
}
yl = lowBound;
yu = uppBound;
rand = rnd_uni(&rnd_uni_init);
beta = 1.0 + (2.0*(y1-yl)/(y2-y1));
alpha = 2.0 - pow(beta,-(eta_c+1.0));
if (rand <= (1.0/alpha))
{
betaq = pow ((rand*alpha),(1.0/(eta_c+1.0)));
}
else
{
betaq = pow ((1.0/(2.0 - rand*alpha)),(1.0/(eta_c+1.0)));
}
c1 = 0.5*((y1+y2)-betaq*(y2-y1));
beta = 1.0 + (2.0*(yu-y2)/(y2-y1));
alpha = 2.0 - pow(beta,-(eta_c+1.0));
if (rand <= (1.0/alpha))
{
betaq = pow ((rand*alpha),(1.0/(eta_c+1.0)));
}
else
{
betaq = pow ((1.0/(2.0 - rand*alpha)),(1.0/(eta_c+1.0)));
}
c2 = 0.5*((y1+y2)+betaq*(y2-y1));
if (_isnan(c2))
{
cout<<"wuxa"<<endl;
c2 = 1-rand;
}
if (c1<yl)
c1=yl;
if (c2<yl)
c2=yl;
if (c1>yu)
c1=yu;
if (c2>yu)
c2=yu;
if (rnd_uni(&rnd_uni_init)<=0.5)
{
child1.x_var[i] = c2;
child2.x_var[i] = c1;
}
else
{
child1.x_var[i] = c1;
child2.x_var[i] = c2;
}
}
else
{
child1.x_var[i] = parent1.x_var[i];
child2.x_var[i] = parent2.x_var[i];
}
}
else
{
child1.x_var[i] = parent1.x_var[i];
child2.x_var[i] = parent2.x_var[i];
}
}
}
else
{
for (int i=0; i<numVariables; i++)
{
child1.x_var[i] = parent1.x_var[i];
child2.x_var[i] = parent2.x_var[i];
}
}
return;
}
#endif
// Routine for real polynomial mutation of an T
/*
template <class T>
void realmutation(T &ind, double rate)
{
double rnd, delta1, delta2, mut_pow, deltaq;
double y, yl, yu, val, xy;
double eta_m = id_mu;
int id_rnd = int(rnd_uni(&rnd_uni_init)*numVariables);
for (int j=0; j<numVariables; j++)
{
if (rnd_uni(&rnd_uni_init)<=rate)
{
y = ind.x_var[j];
yl = lowBound;
yu = uppBound;
delta1 = (y-yl)/(yu-yl);
delta2 = (yu-y)/(yu-yl);
rnd = rnd_uni(&rnd_uni_init);
mut_pow = 1.0/(eta_m+1.0);
if (rnd <= 0.5)
{
xy = 1.0-delta1;
val = 2.0*rnd+(1.0-2.0*rnd)*(pow(xy,(eta_m+1.0)));
deltaq = pow(val,mut_pow) - 1.0;
}
else
{
xy = 1.0-delta2;
val = 2.0*(1.0-rnd)+2.0*(rnd-0.5)*(pow(xy,(eta_m+1.0)));
deltaq = 1.0 - (pow(val,mut_pow));
}
y = y + deltaq*(yu-yl);
if (y<yl)
y = yl;
if (y>yu)
y = yu;
ind.x_var[j] = y;
}
}
return;
}
// Routine for real variable SBX crossover
template <class T>
void realbinarycrossover (T &parent1, T &parent2, T& child1, T& child2)
{
double rand;
double y1, y2, yl, yu;
double c1, c2;
double alpha, beta, betaq;
double eta_c = id_cx;
if (rnd_uni(&rnd_uni_init) <= 1.0)
{
for (int i=0; i<numVariables; i++)
{
if (rnd_uni(&rnd_uni_init)<=1 )
{
if (fabs(parent1.x_var[i]-parent2.x_var[i]) > EPS)
{
if (parent1.x_var[i] < parent2.x_var[i])
{
y1 = parent1.x_var[i];
y2 = parent2.x_var[i];
}
else
{
y1 = parent2.x_var[i];
y2 = parent1.x_var[i];
}
yl = lowBound;
yu = uppBound;
rand = rnd_uni(&rnd_uni_init);
// do
// {
beta = 1.0 + (2.0*(y1-yl)/(y2-y1));
alpha = 2.0 - pow(beta,-(eta_c+1.0));
if (rand <= (1.0/alpha))
{
betaq = pow ((rand*alpha),(1.0/(eta_c+1.0)));
}
else
{
betaq = pow ((1.0/(2.0 - rand*alpha)),(1.0/(eta_c+1.0)));
}
c1 = 0.5*((y1+y2)-betaq*(y2-y1));
// c1 = y1 + betaq * y2 - y2;
// }while(_isnan(c1));
if (_isnan(c1))
{
cout<<"c1 wrong"<<endl;
cout<<parent1.x_var[i]<<" "<<parent2.x_var[i]<<" "<<beta<<" "<<alpha<<" "<<betaq<<" "<<rand<<endl;
}
// do
// {
beta = 1.0 + (2.0*(yu-y2)/(y2-y1));
alpha = 2.0 - pow(beta,-(eta_c+1.0));
if (rand <= (1.0/alpha))
{
betaq = pow ((rand*alpha),(1.0/(eta_c+1.0)));
}
else
{
betaq = pow ((1.0/(2.0 - rand*alpha)),(1.0/(eta_c+1.0)));
}
c2 = 0.5*((y1+y2)+betaq*(y2-y1));
// c2 = y1 - betaq * y2 + y2;
// }while(_isnan(c2));
if (_isnan(c2))
{
cout<<"wuxa"<<endl;
}
if (c1<yl)
c1=yl;
if (c2<yl)
c2=yl;
if (c1>yu)
c1=yu;
if (c2>yu)
c2=yu;
if(_isnan(c2) && _isnan(c1))
{
if (rnd_uni(&rnd_uni_init)<=0.5)
{
child1.x_var[i] = c2;
child2.x_var[i] = c1;
}
else
{
child1.x_var[i] = c1;
child2.x_var[i] = c2;
}
}
else
{
child1.x_var[i] = parent1.x_var[i];
child2.x_var[i] = parent2.x_var[i];
}
}
else
{
child1.x_var[i] = rnd_uni(&rnd_uni_init);
if(child1.x_var[i]<lowBound)
child1.x_var[i]=lowBound;
else if(child1.x_var[i]>uppBound)
child1.x_var[i]=uppBound;
child2.x_var[i] = parent2.x_var[i];
}
}
else
{
child1.x_var[i] = parent1.x_var[i];
child2.x_var[i] = parent2.x_var[i];
}
}
}
else
{
for (int i=0; i<numVariables; i++)
{
child1.x_var[i] = parent1.x_var[i];
child2.x_var[i] = parent2.x_var[i];
}
}
return;
}
#endif
*/ | [
"jzzlee@163.com"
] | jzzlee@163.com |
f3a7da1925afd693d47258cdb709b3aa81f37145 | 4cc7c74b4bb7b818562bedffd026a86f9ec78f41 | /chrome/browser/ui/app_list/search/omnibox_result.cc | e38e3977dfb2ad61b8d277c95c8b58069b0df555 | [
"BSD-3-Clause"
] | permissive | jennyb2911/chromium | 1e03c9e5a63af1cf82832e0e99e0028e255872bd | 62b48b4fdb3984762f4d2fd3690f02f167920f52 | refs/heads/master | 2023-01-10T01:08:34.961976 | 2018-09-28T03:36:36 | 2018-09-28T03:36:36 | 150,682,761 | 1 | 0 | NOASSERTION | 2018-09-28T03:49:28 | 2018-09-28T03:49:27 | null | UTF-8 | C++ | false | false | 7,501 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/app_list/search/omnibox_result.h"
#include <stddef.h>
#include "ash/public/cpp/app_list/app_list_config.h"
#include "ash/public/cpp/app_list/app_list_features.h"
#include "ash/public/cpp/app_list/vector_icons/vector_icons.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/app_list_controller_delegate.h"
#include "chrome/browser/ui/app_list/search/search_util.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/omnibox/browser/autocomplete_controller.h"
#include "components/omnibox/browser/autocomplete_match_type.h"
#include "components/omnibox/browser/vector_icons.h"
#include "ui/gfx/paint_vector_icon.h"
#include "url/gurl.h"
#include "url/url_canon.h"
using bookmarks::BookmarkModel;
namespace app_list {
namespace {
// #000 at 87% opacity.
constexpr SkColor kListIconColor = SkColorSetARGB(0xDE, 0x00, 0x00, 0x00);
int ACMatchStyleToTagStyle(int styles) {
int tag_styles = 0;
if (styles & ACMatchClassification::URL)
tag_styles |= ash::SearchResultTag::URL;
if (styles & ACMatchClassification::MATCH)
tag_styles |= ash::SearchResultTag::MATCH;
if (styles & ACMatchClassification::DIM)
tag_styles |= ash::SearchResultTag::DIM;
return tag_styles;
}
// Translates ACMatchClassifications into ChromeSearchResult tags.
void ACMatchClassificationsToTags(const base::string16& text,
const ACMatchClassifications& text_classes,
ChromeSearchResult::Tags* tags) {
int tag_styles = ash::SearchResultTag::NONE;
size_t tag_start = 0;
for (size_t i = 0; i < text_classes.size(); ++i) {
const ACMatchClassification& text_class = text_classes[i];
// Closes current tag.
if (tag_styles != ash::SearchResultTag::NONE) {
tags->push_back(
ash::SearchResultTag(tag_styles, tag_start, text_class.offset));
tag_styles = ash::SearchResultTag::NONE;
}
if (text_class.style == ACMatchClassification::NONE)
continue;
tag_start = text_class.offset;
tag_styles = ACMatchStyleToTagStyle(text_class.style);
}
if (tag_styles != ash::SearchResultTag::NONE) {
tags->push_back(ash::SearchResultTag(tag_styles, tag_start, text.length()));
}
}
// AutocompleteMatchType::Type to vector icon, used for app list.
const gfx::VectorIcon& TypeToVectorIcon(AutocompleteMatchType::Type type) {
switch (type) {
case AutocompleteMatchType::URL_WHAT_YOU_TYPED:
case AutocompleteMatchType::HISTORY_URL:
case AutocompleteMatchType::HISTORY_TITLE:
case AutocompleteMatchType::HISTORY_BODY:
case AutocompleteMatchType::HISTORY_KEYWORD:
case AutocompleteMatchType::NAVSUGGEST:
case AutocompleteMatchType::BOOKMARK_TITLE:
case AutocompleteMatchType::NAVSUGGEST_PERSONALIZED:
case AutocompleteMatchType::CLIPBOARD:
case AutocompleteMatchType::PHYSICAL_WEB_DEPRECATED:
case AutocompleteMatchType::PHYSICAL_WEB_OVERFLOW_DEPRECATED:
case AutocompleteMatchType::TAB_SEARCH_DEPRECATED:
case AutocompleteMatchType::DOCUMENT_SUGGESTION:
return kIcDomainIcon;
case AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED:
case AutocompleteMatchType::SEARCH_SUGGEST:
case AutocompleteMatchType::SEARCH_SUGGEST_ENTITY:
case AutocompleteMatchType::SEARCH_SUGGEST_TAIL:
case AutocompleteMatchType::SEARCH_SUGGEST_PROFILE:
case AutocompleteMatchType::SEARCH_OTHER_ENGINE:
case AutocompleteMatchType::CONTACT_DEPRECATED:
case AutocompleteMatchType::VOICE_SUGGEST:
return kIcSearchIcon;
case AutocompleteMatchType::SEARCH_HISTORY:
case AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED:
return kIcHistoryIcon;
case AutocompleteMatchType::CALCULATOR:
return kIcEqualIcon;
case AutocompleteMatchType::EXTENSION_APP_DEPRECATED:
case AutocompleteMatchType::NUM_TYPES:
NOTREACHED();
break;
}
NOTREACHED();
return kIcDomainIcon;
}
} // namespace
OmniboxResult::OmniboxResult(Profile* profile,
AppListControllerDelegate* list_controller,
AutocompleteController* autocomplete_controller,
const AutocompleteMatch& match)
: profile_(profile),
list_controller_(list_controller),
autocomplete_controller_(autocomplete_controller),
match_(match) {
if (match_.search_terms_args && autocomplete_controller_) {
match_.search_terms_args->from_app_list = true;
autocomplete_controller_->UpdateMatchDestinationURL(
*match_.search_terms_args, &match_);
}
set_id(match_.destination_url.spec());
set_comparable_id(match_.stripped_destination_url.spec());
SetResultType(ash::SearchResultType::kOmnibox);
// Derive relevance from omnibox relevance and normalize it to [0, 1].
// The magic number 1500 is the highest score of an omnibox result.
// See comments in autocomplete_provider.h.
set_relevance(match_.relevance / 1500.0);
if (AutocompleteMatch::IsSearchType(match_.type))
SetIsOmniboxSearch(true);
UpdateIcon();
UpdateTitleAndDetails();
}
OmniboxResult::~OmniboxResult() = default;
void OmniboxResult::Open(int event_flags) {
RecordHistogram(OMNIBOX_SEARCH_RESULT);
list_controller_->OpenURL(profile_, match_.destination_url, match_.transition,
ui::DispositionFromEventFlags(event_flags));
}
void OmniboxResult::UpdateIcon() {
BookmarkModel* bookmark_model =
BookmarkModelFactory::GetForBrowserContext(profile_);
bool is_bookmarked =
bookmark_model && bookmark_model->IsBookmarked(match_.destination_url);
const gfx::VectorIcon& icon =
is_bookmarked ? kIcBookmarkIcon : TypeToVectorIcon(match_.type);
SetIcon(gfx::CreateVectorIcon(
icon, AppListConfig::instance().search_list_icon_dimension(),
kListIconColor));
}
void OmniboxResult::UpdateTitleAndDetails() {
// For url result with non-empty description, swap title and details. Thus,
// the url description is presented as title, and url itself is presented as
// details.
const bool use_directly = !IsUrlResultWithDescription();
ChromeSearchResult::Tags title_tags;
if (use_directly) {
SetTitle(match_.contents);
ACMatchClassificationsToTags(match_.contents, match_.contents_class,
&title_tags);
} else {
SetTitle(match_.description);
ACMatchClassificationsToTags(match_.description, match_.description_class,
&title_tags);
}
SetTitleTags(title_tags);
ChromeSearchResult::Tags details_tags;
if (use_directly) {
SetDetails(match_.description);
ACMatchClassificationsToTags(match_.description, match_.description_class,
&details_tags);
} else {
SetDetails(match_.contents);
ACMatchClassificationsToTags(match_.contents, match_.contents_class,
&details_tags);
}
SetDetailsTags(details_tags);
}
bool OmniboxResult::IsUrlResultWithDescription() const {
return !AutocompleteMatch::IsSearchType(match_.type) &&
!match_.description.empty();
}
} // namespace app_list
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
abdebfb0eb9a4e8a7fc4855b2524a8cf0b3b801c | 91c71db50d3c9d60545e654b78a505adf99b6449 | /function.cpp | 78fc06c509cca8f052e0ab0d2aea1f3121c139a2 | [] | no_license | Tejas8765/scaling | 7d0e5b153edb97d279ae90f7b48a71083ff6c25d | e8bcd3f76f938217fddf4eda366b6fbfc0f368dd | refs/heads/master | 2023-01-08T05:19:56.190610 | 2020-11-09T17:21:21 | 2020-11-09T17:21:21 | 311,409,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | #include <iostream>
using namespace std;
void sqr(void);
int main()
{
sqr();
return 0;
}
void sqr()
{
int a;
cout<<"\n \tenter a no. ";
cin>>a;
cout<<"\n \tsqr of "<<a<<" is "<<a*a;
}
| [
"tejasawasthi8765@gmail.com"
] | tejasawasthi8765@gmail.com |
32f728d47d24af0fc0eda5bc91166b8b886f8b6b | 5168d97461d4335784082f88ba2f90d3dee71769 | /Coding Questions/2-D Array/Tutorial Sheet/Ques10.cpp | 4f227a2e17aac89158b8c19fbe94d90e8b9e3be6 | [] | no_license | parasjain929/Karma | eb4021397f085cbc24a08b2651d2d20103047484 | 7e52e7f5698f8a6e15684800ee336ae24dae8c36 | refs/heads/master | 2020-06-01T23:27:10.785809 | 2019-07-05T08:57:04 | 2019-07-05T08:57:04 | 190,964,636 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 674 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i,j,k;
cin>>n;
int a[n][n],b[n][n],c[n][n]={};
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cin>>b[i][j];
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<c[i][j];
}
cout<<endl;
}
}
| [
"parasjain929@gmail.com"
] | parasjain929@gmail.com |
186d1ba8b2e1a7f68836800c9f46370e83d937fb | 287dc1683f7e19a5239c2b8addbc8531809f9177 | /mooc40-bobo-Interview/Play-with-Algorithm-Interview-master/03-Using-Array/cpp/05-Sort-Colors/main2.cpp | b30136a2b541fb0a4d106314094c35b01e81c72f | [
"Apache-2.0"
] | permissive | yaominzh/CodeLrn2019 | ea192cf18981816c6adafe43d85e2462d4bc6e5d | adc727d92904c5c5d445a2621813dfa99474206d | refs/heads/master | 2023-01-06T14:11:45.281011 | 2020-10-28T07:16:32 | 2020-10-28T07:16:32 | 164,027,453 | 2 | 0 | Apache-2.0 | 2023-01-06T00:39:06 | 2019-01-03T22:02:24 | C++ | UTF-8 | C++ | false | false | 1,038 | cpp | #include <iostream>
#include <vector>
#include <cassert>
using namespace std;
// 75. Sort Colors
// https://leetcode.com/problems/sort-colors/description/
//
// 三路快速排序的思想
// 对整个数组只遍历了一遍
// 时间复杂度: O(n)
// 空间复杂度: O(1)
class Solution {
public:
void sortColors(vector<int> &nums) {
int zero = -1; // [0...zero] == 0
int two = nums.size(); // [two...n-1] == 2
for(int i = 0 ; i < two ; ){
if(nums[i] == 1)
i ++;
else if (nums[i] == 2)
swap( nums[i] , nums[--two]);
else{ // nums[i] == 0
assert(nums[i] == 0);
swap(nums[++zero] , nums[i++]);
}
}
}
};
int main() {
int nums[] = {2, 2, 2, 1, 1, 0};
vector<int> vec = vector<int>(nums, nums + sizeof(nums)/sizeof(int));
Solution().sortColors(vec);
for(int i = 0 ; i < vec.size() ; i ++)
cout << vec[i] << " ";
cout << endl;
return 0;
}
| [
"mcuallen@gmail.com"
] | mcuallen@gmail.com |
ea7912c07dfd5feb2a5143cded6c8d17fcadeff3 | 60b41b520961aec238fcff1fec8329fec33b3bfc | /src/pca.cpp | 243e68b90a88e66bb8cdc74b10b460bc773a5a36 | [] | no_license | kugelblitz1235/optical-character-recognition-Metnum | 7adfdf00a0bd43b50d59419a8bcead45f1770d0f | 015d129abb647abb4bade28c82e2e5fa04b4b1f4 | refs/heads/master | 2023-03-05T19:11:44.477697 | 2021-02-08T20:55:40 | 2021-02-08T20:55:40 | 337,206,027 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,693 | cpp | #include <iostream>
#include "pca.h"
#include "eigen.h"
using namespace std;
PCA::PCA(unsigned int n_components) {
this->alpha = n_components;
}
void PCA::fit(Matrix X) {
_V = get_eigenvectorMatrix(X);
}
MatrixXd PCA::transform(Matrix X) {
return (X*_V);
}
MatrixXd PCA::get_eigenvectorMatrix(Matrix X) {
// Armo Matriz de Covarianza
Vector meanValue(X.cols());
Matrix covMat = X;
// Calculo mediana de cada columna y se la resto
for (int i = 0; i < X.cols(); ++i) {
meanValue[i] = X.col(i).mean();
}
for (int i = 0; i < X.rows(); ++i) {
covMat.row(i) = covMat.row(i) - meanValue;
}
// Armo matriz de covarianza
Matrix covMatT = covMat.transpose();
covMat = (covMatT*covMat)/double(covMat.cols()-1);
// Obtenego los primeros alpha autovectores y autovalores correspondientes
Matrix V = get_first_eigenvalues(covMat, alpha).second;
// Devuelvo la matriz con dimension reducida
return V;
}
Vector PCA::get_eigenvaluesMatrix(Matrix X) {
// Armo Matriz de Covarianza
Vector meanValue(X.cols());
Matrix covMat = X;
// Calculo mediana de cada columna y se la resto
for (int i = 0; i < X.cols(); ++i) {
meanValue[i] = X.col(i).mean();
}
for (int i = 0; i < X.rows(); ++i) {
covMat.row(i) = covMat.row(i) - meanValue;
}
// Armo matriz de covarianza
Matrix covMatT = covMat.transpose();
covMat = (covMatT*covMat)/(covMat.cols()-1);
// Obtenego los primeros alpha autovectores y autovalores correspondientes
Vector res = get_first_eigenvalues(covMat, alpha).first;
// Devuelvo la matriz con dimension reducida
return res;
}
| [
"brunolml99@outlook.es"
] | brunolml99@outlook.es |
4c941727d5bff1d7e51a7782a8fccb1327f1e26c | fa13641f306497840a1348dd1577b42dddcd1173 | /arduino/CallibrateCompass/src/Main.cpp | 96aa4dad075766405bdba44a9b4ab37b2e0b69c1 | [] | no_license | hexgecko/ZumoRobotRemote | 7cae094447cd0a9fea546864c06390dc9797de2e | 32aa0743e86f225405db95cc37d2b5d647c0b2d0 | refs/heads/master | 2020-09-03T19:18:29.437082 | 2019-11-04T16:22:14 | 2019-11-04T16:22:14 | 219,544,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,009 | cpp | #include <Arduino.h>
/* This example uses the magnetometer in the Zumo Shield's onboard
* LSM303DLHC to help the Zumo make precise 90-degree turns and drive
* in squares. It uses ZumoMotors, Pushbutton, and the LSM303
* (compass) library.
*
* This program first calibrates the compass to account for offsets in
* its output. Calibration is accomplished in setup().
*
* In loop(), The driving angle then changes its offset by 90 degrees
* from the heading every second. Essentially, this navigates the
* Zumo to drive in square patterns.
*
* It is important to note that stray magnetic fields from electric
* current (including from the Zumo's own motors) and the environment
* (for example, steel rebar in a concrete floor) might adversely
* affect readings from the LSM303 compass and make them less
* reliable.
*/
#include <Wire.h>
#include <ZumoShield.h>
#define SPEED 300 // Maximum motor speed when going straight; variable speed when turning
#define TURN_BASE_SPEED 100 // Base speed when turning (added to variable speed)
#define CALIBRATION_SAMPLES 70 // Number of compass readings to take when calibrating
#define CRB_REG_M_2_5GAUSS 0x60 // CRB_REG_M value for magnetometer +/-2.5 gauss full scale
#define CRA_REG_M_220HZ 0x1C // CRA_REG_M value for magnetometer 220 Hz update rate
// Allowed deviation (in degrees) relative to target angle that must be achieved before driving straight
#define DEVIATION_THRESHOLD 5
ZumoMotors motors;
Pushbutton button(ZUMO_BUTTON);
LSM303 compass;
// Converts x and y components of a vector to a heading in degrees.
// This function is used instead of LSM303::heading() because we don't
// want the acceleration of the Zumo to factor spuriously into the
// tilt compensation that LSM303::heading() performs. This calculation
// assumes that the Zumo is always level.
template <typename T> float heading(LSM303::vector<T> v)
{
float x_scaled = 2.0*(float)(v.x - compass.m_min.x) / ( compass.m_max.x - compass.m_min.x) - 1.0;
float y_scaled = 2.0*(float)(v.y - compass.m_min.y) / (compass.m_max.y - compass.m_min.y) - 1.0;
float angle = atan2(y_scaled, x_scaled)*180 / M_PI;
if (angle < 0)
angle += 360;
return angle;
}
// Yields the angle difference in degrees between two headings
float relativeHeading(float heading_from, float heading_to)
{
float relative_heading = heading_to - heading_from;
// constrain to -180 to 180 degree range
if (relative_heading > 180)
relative_heading -= 360;
if (relative_heading < -180)
relative_heading += 360;
return relative_heading;
}
// Average 10 vectors to get a better measurement and help smooth out
// the motors' magnetic interference.
float averageHeading()
{
LSM303::vector<int32_t> avg = {0, 0, 0};
for(int i = 0; i < 10; i ++)
{
compass.read();
avg.x += compass.m.x;
avg.y += compass.m.y;
}
avg.x /= 10.0;
avg.y /= 10.0;
// avg is the average measure of the magnetic vector.
return heading(avg);
}
// Setup will calibrate our compass by finding maximum/minimum magnetic readings
void setup()
{
// The highest possible magnetic value to read in any direction is 2047
// The lowest possible magnetic value to read in any direction is -2047
LSM303::vector<int16_t> running_min = {32767, 32767, 32767}, running_max = {-32767, -32767, -32767};
unsigned char index;
Serial.begin(9600);
// Initiate the Wire library and join the I2C bus as a master
Wire.begin();
// Initiate LSM303
compass.init();
// Enables accelerometer and magnetometer
compass.enableDefault();
compass.writeReg(LSM303::CRB_REG_M, CRB_REG_M_2_5GAUSS); // +/- 2.5 gauss sensitivity to hopefully avoid overflow problems
compass.writeReg(LSM303::CRA_REG_M, CRA_REG_M_220HZ); // 220 Hz compass update rate
button.waitForButton();
Serial.println("starting calibration");
// To calibrate the magnetometer, the Zumo spins to find the max/min
// magnetic vectors. This information is used to correct for offsets
// in the magnetometer data.
motors.setLeftSpeed(SPEED);
motors.setRightSpeed(-SPEED);
for(index = 0; index < CALIBRATION_SAMPLES; index ++)
{
// Take a reading of the magnetic vector and store it in compass.m
Serial.println(index);
compass.read();
running_min.x = min(running_min.x, compass.m.x);
running_min.y = min(running_min.y, compass.m.y);
running_max.x = max(running_max.x, compass.m.x);
running_max.y = max(running_max.y, compass.m.y);
Serial.println(index);
delay(50);
}
motors.setLeftSpeed(0);
motors.setRightSpeed(0);
Serial.print("max.x ");
Serial.print(running_max.x);
Serial.println();
Serial.print("max.y ");
Serial.print(running_max.y);
Serial.println();
Serial.print("min.x ");
Serial.print(running_min.x);
Serial.println();
Serial.print("min.y ");
Serial.print(running_min.y);
Serial.println();
// Set calibrated values to compass.m_max and compass.m_min
compass.m_max.x = running_max.x;
compass.m_max.y = running_max.y;
compass.m_min.x = running_min.x;
compass.m_min.y = running_min.y;
button.waitForButton();
}
void loop()
{
float heading, relative_heading;
int speed;
static float target_heading = averageHeading();
// Heading is given in degrees away from the magnetic vector, increasing clockwise
heading = averageHeading();
// This gives us the relative heading with respect to the target angle
relative_heading = relativeHeading(heading, target_heading);
Serial.print("Target heading: ");
Serial.print(target_heading);
Serial.print(" Actual heading: ");
Serial.print(heading);
Serial.print(" Difference: ");
Serial.print(relative_heading);
// If the Zumo has turned to the direction it wants to be pointing, go straight and then do another turn
if(abs(relative_heading) < DEVIATION_THRESHOLD)
{
motors.setSpeeds(SPEED, SPEED);
Serial.print(" Straight");
delay(1000);
// Turn off motors and wait a short time to reduce interference from motors
motors.setSpeeds(0, 0);
delay(100);
// Turn 90 degrees relative to the direction we are pointing.
// This will help account for variable magnetic field, as opposed
// to using fixed increments of 90 degrees from the initial
// heading (which might have been measured in a different magnetic
// field than the one the Zumo is experiencing now).
// Note: fmod() is floating point modulo
target_heading = fmod(averageHeading() + 90, 360);
}
else
{
// To avoid overshooting, the closer the Zumo gets to the target
// heading, the slower it should turn. Set the motor speeds to a
// minimum base amount plus an additional variable amount based
// on the heading difference.
speed = SPEED*relative_heading/180;
if (speed < 0)
speed -= TURN_BASE_SPEED;
else
speed += TURN_BASE_SPEED;
motors.setSpeeds(speed, -speed);
Serial.print(" Turn");
}
Serial.println();
}
| [
"stefan.elmlund@gmail.com"
] | stefan.elmlund@gmail.com |
be24ac2dce771091a6a9511f3ff838fcd22716de | bf44ac4b80e485ee3b48afb714e47129b5f07c5e | /Maze Solving/stack_test.cpp | 31c0195039ee0bb929d22a4be25bded9255b741f | [] | no_license | ayushashi11/dsa | 3df8818b57de9be44511e051a40561275893d8c9 | 662d36c6f1e5aefbe5515835f4f9b9350383e201 | refs/heads/master | 2023-04-13T02:23:32.615694 | 2023-04-04T02:49:24 | 2023-04-04T02:49:24 | 230,466,217 | 0 | 0 | null | 2021-11-30T05:07:40 | 2019-12-27T15:21:14 | C++ | UTF-8 | C++ | false | false | 195 | cpp | #include<stack>
#include<iostream>
using namespace std;
stack<int> st;
int main(){
cout<<"hello\n";
for(int i=0;i<5;i++){
st.push(i);
}
cout<<(st.top()+2);
return 0;
} | [
"ayushashi11@gmail.com"
] | ayushashi11@gmail.com |
9df2d2c9bda897c1f7d5f0ddec85ccaac7e49604 | ba939b57e04c1ba5180ae1b47c2f71e02885e025 | /main.cpp | 6d43275fb6e83e989b80356e7df00ece8f0c8587 | [
"MIT"
] | permissive | aoleg94/gamepad-launcher | 9ea29195a3f8a4d2a461c4a1486b3c975a0b251c | f104ddb79e51ee759a2ed83b8ceb16a30d5bfc41 | refs/heads/master | 2021-01-11T17:43:14.546485 | 2017-02-01T18:47:47 | 2017-02-01T18:57:50 | 79,823,675 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | cpp | #include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setApplicationName("Gamepad Launcher");
MainWindow w;
//w.show();
return a.exec();
}
| [
"aoleg94@gmail.com"
] | aoleg94@gmail.com |
0d440ca4cdf4ae46d5bd9bbc9dca2306a407e1a6 | 7c94bc78c07023c7b1491418bd17585f52a9698d | /codeforces/contest-1136/3.cpp | 4cdf814ec8c62b7f8acdcbea29623a48fbefc49b | [] | no_license | vitkarpov/dcp | beac190e653190781a6c1ddcdb3e89448e4d78ef | 51cd0bed4e9909f7c01c8881e2e47704a5a49926 | refs/heads/master | 2021-07-17T22:36:59.764499 | 2020-04-27T15:34:01 | 2020-04-27T15:34:01 | 141,915,045 | 16 | 2 | null | 2019-11-13T15:29:13 | 2018-07-22T17:05:57 | C++ | UTF-8 | C++ | false | false | 1,496 | cpp | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void read_matrix(vector<vector<int>> &m, int xx, int yy) {
for (int i = 0; i < yy; i++) {
for (int j = 0; j < xx; j++) {
cin >> m[i][j];
}
}
}
bool check_transform(const vector<vector<int>> &m1,
const vector<vector<int>> &m2, int xx, int yy) {
// first row
for (int x = 0; x < xx; x++) {
vector<int> tmp1;
vector<int> tmp2;
int i = x;
int j = 0;
while (i >= 0 && j < yy) {
tmp1.push_back(m1[j][i]);
tmp2.push_back(m2[j][i]);
i--;
j++;
}
sort(tmp1.begin(), tmp1.end());
sort(tmp2.begin(), tmp2.end());
if (!equal(tmp1.begin(), tmp1.end(), tmp2.begin())) {
return false;
}
}
// last col
for (int y = 1; y < yy; y++) {
vector<int> tmp1;
vector<int> tmp2;
int i = xx - 1;
int j = y;
while (i >= 0 && j < yy) {
tmp1.push_back(m1[j][i]);
tmp2.push_back(m2[j][i]);
i--;
j++;
}
sort(tmp1.begin(), tmp1.end());
sort(tmp2.begin(), tmp2.end());
if (!equal(tmp1.begin(), tmp1.end(), tmp2.begin())) {
return false;
}
}
return true;
}
int main() {
int yy, xx;
cin >> yy >> xx;
vector<vector<int>> m1(yy, vector<int>(xx));
vector<vector<int>> m2(yy, vector<int>(xx));
read_matrix(m1, xx, yy);
read_matrix(m2, xx, yy);
if (check_transform(m1, m2, xx, yy)) {
cout << "YES";
} else {
cout << "NO";
}
}
| [
"viktor.karpov@toptal.com"
] | viktor.karpov@toptal.com |
530d76e8837d06ac3ee5be00e1c37c25e922f183 | d56a7b237481a81353c22a4772abd2376709e7b4 | /Ejercicios LP1/Ejercicio13-factura exenta/factura exenta.cpp | e5b0ac537c0b32181b6a4dcbab3f32db76f7667d | [
"MIT"
] | permissive | IrisVH/cpp | 89bafb23689822bd8e8e4d995688c28f3586f580 | 2abeca0df70cfdc6e95e8b07160062b66e4b2799 | refs/heads/master | 2022-12-26T13:21:26.389770 | 2020-10-05T02:14:20 | 2020-10-05T02:14:20 | 276,538,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 820 | cpp | #include <iostream>
using namespace std;
int main(int argc, char** argv) {
double subtotal=0;
double total=0;
double impuesto=0;
char estaexenta;
double calculoImpuesto=0;
int descuento=0;
double calculoDescuento=0;
cout <<"Ingrese el valor de la factura:";
cin >>subtotal;
cout <<"Ingrese el descuento (0,10,15,20):";
cin >>descuento;
cout <<"Factura exenta (s/n)";
cin >>estaexenta;
if (estaexenta== 's'||estaexenta== 'S'){
calculoDescuento=(subtotal* descuento)/100;
total=subtotal-calculoDescuento;
cout <<"Total a pagar es:"<<total;
} else{
calculoImpuesto=(subtotal*0.15);
calculoDescuento=(subtotal* descuento)/100;
total=subtotal-calculoDescuento+calculoImpuesto;
cout <<"Total a pagar es:"<<total;
}
cout <<endl;
return 0;
} | [
"ivhernandez@unah.hn"
] | ivhernandez@unah.hn |
b5ccf891fcd5263a788b04a041d37e1e8f098280 | 0ca8832a2818af66f1a584d7cf6c56abf0af8591 | /src/thirdparty/boost/boost/ptr_container/ptr_sequence_adapter.hpp | cb51cd14e4ee6ffc7576cd01b692e9a7450fe9ba | [] | no_license | knobik/source-python | 241e27d325d40fc8374fc9fb8f8311a146dc7e77 | e57308a662c25110f1a1730199985a5f2cf11713 | refs/heads/master | 2021-01-10T08:28:55.402519 | 2013-09-12T04:00:12 | 2013-09-12T04:00:12 | 54,717,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,327 | hpp | //
// Boost.Pointer Container
//
// Copyright Thorsten Ottosen 2003-2005. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//
#ifndef BOOST_PTR_CONTAINER_PTR_SEQUENCE_ADAPTER_HPP
#define BOOST_PTR_CONTAINER_PTR_SEQUENCE_ADAPTER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <boost/ptr_container/detail/reversible_ptr_container.hpp>
#include <boost/ptr_container/indirect_fun.hpp>
#include <boost/ptr_container/detail/void_ptr_iterator.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/type_traits/is_same.hpp>
namespace boost
{
namespace ptr_container_detail
{
template
<
class T,
class VoidPtrSeq
>
struct sequence_config
{
typedef BOOST_DEDUCED_TYPENAME remove_nullable<T>::type
U;
typedef VoidPtrSeq
void_container_type;
typedef BOOST_DEDUCED_TYPENAME VoidPtrSeq::allocator_type
allocator_type;
typedef U value_type;
typedef void_ptr_iterator<
BOOST_DEDUCED_TYPENAME VoidPtrSeq::iterator, U >
iterator;
typedef void_ptr_iterator<
BOOST_DEDUCED_TYPENAME VoidPtrSeq::const_iterator, const U >
const_iterator;
#if defined(BOOST_NO_SFINAE) || defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
template< class Iter >
static U* get_pointer( Iter i )
{
return static_cast<U*>( *i.base() );
}
#else
template< class Iter >
static U* get_pointer( void_ptr_iterator<Iter,U> i )
{
return static_cast<U*>( *i.base() );
}
template< class Iter >
static U* get_pointer( Iter i )
{
return &*i;
}
#endif
#if defined(BOOST_NO_SFINAE) && !BOOST_WORKAROUND(__MWERKS__, <= 0x3003)
template< class Iter >
static const U* get_const_pointer( Iter i )
{
return static_cast<const U*>( *i.base() );
}
#else // BOOST_NO_SFINAE
#if BOOST_WORKAROUND(__MWERKS__, <= 0x3003)
template< class Iter >
static const U* get_const_pointer( void_ptr_iterator<Iter,U> i )
{
return static_cast<const U*>( *i.base() );
}
#else // BOOST_WORKAROUND
template< class Iter >
static const U* get_const_pointer( void_ptr_iterator<Iter,const U> i )
{
return static_cast<const U*>( *i.base() );
}
#endif // BOOST_WORKAROUND
template< class Iter >
static const U* get_const_pointer( Iter i )
{
return &*i;
}
#endif // BOOST_NO_SFINAE
BOOST_STATIC_CONSTANT(bool, allow_null = boost::is_nullable<T>::value );
};
} // ptr_container_detail
template< class Iterator, class T >
inline bool is_null( void_ptr_iterator<Iterator,T> i )
{
return *i.base() == 0;
}
template
<
class T,
class VoidPtrSeq,
class CloneAllocator = heap_clone_allocator
>
class ptr_sequence_adapter : public
ptr_container_detail::reversible_ptr_container< ptr_container_detail::sequence_config<T,VoidPtrSeq>,
CloneAllocator >
{
typedef ptr_container_detail::reversible_ptr_container< ptr_container_detail::sequence_config<T,VoidPtrSeq>,
CloneAllocator >
base_type;
typedef ptr_sequence_adapter<T,VoidPtrSeq,CloneAllocator>
this_type;
protected:
typedef BOOST_DEDUCED_TYPENAME base_type::scoped_deleter scoped_deleter;
public:
typedef BOOST_DEDUCED_TYPENAME base_type::value_type value_type;
typedef BOOST_DEDUCED_TYPENAME base_type::reference reference;
typedef BOOST_DEDUCED_TYPENAME base_type::const_reference
const_reference;
typedef BOOST_DEDUCED_TYPENAME base_type::auto_type auto_type;
typedef BOOST_DEDUCED_TYPENAME base_type::clone_allocator_type
clone_allocator_type;
typedef BOOST_DEDUCED_TYPENAME base_type::iterator iterator;
typedef BOOST_DEDUCED_TYPENAME base_type::size_type size_type;
typedef BOOST_DEDUCED_TYPENAME base_type::allocator_type
allocator_type;
ptr_sequence_adapter()
{ }
template< class Allocator >
explicit ptr_sequence_adapter( const Allocator& a )
: base_type( a )
{ }
template< class SizeType >
ptr_sequence_adapter( SizeType n,
ptr_container_detail::fixed_length_sequence_tag tag )
: base_type( n, tag )
{ }
template< class SizeType, class Allocator >
ptr_sequence_adapter( SizeType n, const Allocator& a,
ptr_container_detail::fixed_length_sequence_tag tag )
: base_type( n, a, tag )
{ }
template< class InputIterator >
ptr_sequence_adapter( InputIterator first, InputIterator last )
: base_type( first, last )
{ }
template< class InputIterator, class Allocator >
ptr_sequence_adapter( InputIterator first, InputIterator last,
const Allocator& a )
: base_type( first, last, a )
{ }
template< class ForwardIterator >
ptr_sequence_adapter( ForwardIterator first,
ForwardIterator last,
ptr_container_detail::fixed_length_sequence_tag tag )
: base_type( first, last, tag )
{ }
template< class SizeType, class ForwardIterator >
ptr_sequence_adapter( SizeType n,
ForwardIterator first,
ForwardIterator last,
ptr_container_detail::fixed_length_sequence_tag tag )
: base_type( n, first, last, tag )
{ }
ptr_sequence_adapter( const ptr_sequence_adapter& r )
: base_type( r )
{ }
template< class U >
ptr_sequence_adapter( const ptr_sequence_adapter<U,VoidPtrSeq,CloneAllocator>& r )
: base_type( r )
{ }
ptr_sequence_adapter( const ptr_sequence_adapter& r,
ptr_container_detail::fixed_length_sequence_tag tag )
: base_type( r, tag )
{ }
template< class U >
ptr_sequence_adapter( const ptr_sequence_adapter<U,VoidPtrSeq,CloneAllocator>& r,
ptr_container_detail::fixed_length_sequence_tag tag )
: base_type( r, tag )
{ }
template< class PtrContainer >
explicit ptr_sequence_adapter( std::auto_ptr<PtrContainer> clone )
: base_type( clone )
{ }
ptr_sequence_adapter& operator=( const ptr_sequence_adapter r )
{
this->swap( r );
return *this;
}
template< class PtrContainer >
ptr_sequence_adapter& operator=( std::auto_ptr<PtrContainer> clone )
{
base_type::operator=( clone );
return *this;
}
/////////////////////////////////////////////////////////////
// modifiers
/////////////////////////////////////////////////////////////
void push_back( value_type x ) // strong
{
this->enforce_null_policy( x, "Null pointer in 'push_back()'" );
auto_type ptr( x, *this ); // notrow
this->base().push_back( x ); // strong, commit
ptr.release(); // nothrow
}
template< class U >
void push_back( std::auto_ptr<U> x )
{
push_back( x.release() );
}
void push_front( value_type x )
{
this->enforce_null_policy( x, "Null pointer in 'push_front()'" );
auto_type ptr( x, *this ); // nothrow
this->base().push_front( x ); // strong, commit
ptr.release(); // nothrow
}
template< class U >
void push_front( std::auto_ptr<U> x )
{
push_front( x.release() );
}
auto_type pop_back()
{
BOOST_ASSERT( !this->empty() &&
"'pop_back()' on empty container" );
auto_type ptr( static_cast<value_type>(this->base().back()), *this );
// nothrow
this->base().pop_back(); // nothrow
return ptr_container_detail::move( ptr ); // nothrow
}
auto_type pop_front()
{
BOOST_ASSERT( !this->empty() &&
"'pop_front()' on empty container" );
auto_type ptr( static_cast<value_type>(this->base().front()), *this );
// nothrow
this->base().pop_front(); // nothrow
return ptr_container_detail::move( ptr );
}
reference front()
{
BOOST_ASSERT( !this->empty() &&
"accessing 'front()' on empty container" );
BOOST_ASSERT( !::boost::is_null( this->begin() ) );
return *this->begin();
}
const_reference front() const
{
return const_cast<ptr_sequence_adapter*>(this)->front();
}
reference back()
{
BOOST_ASSERT( !this->empty() &&
"accessing 'back()' on empty container" );
BOOST_ASSERT( !::boost::is_null( --this->end() ) );
return *--this->end();
}
const_reference back() const
{
return const_cast<ptr_sequence_adapter*>(this)->back();
}
public: // deque/vector inerface
reference operator[]( size_type n ) // nothrow
{
BOOST_ASSERT( n < this->size() );
BOOST_ASSERT( !this->is_null( n ) );
return *static_cast<value_type>( this->base()[n] );
}
const_reference operator[]( size_type n ) const // nothrow
{
BOOST_ASSERT( n < this->size() );
BOOST_ASSERT( !this->is_null( n ) );
return *static_cast<value_type>( this->base()[n] );
}
reference at( size_type n )
{
BOOST_PTR_CONTAINER_THROW_EXCEPTION( n >= this->size(), bad_index,
"'at()' out of bounds" );
BOOST_ASSERT( !this->is_null( n ) );
return (*this)[n];
}
const_reference at( size_type n ) const
{
BOOST_PTR_CONTAINER_THROW_EXCEPTION( n >= this->size(), bad_index,
"'at()' out of bounds" );
BOOST_ASSERT( !this->is_null( n ) );
return (*this)[n];
}
public: // vector interface
size_type capacity() const
{
return this->base().capacity();
}
void reserve( size_type n )
{
this->base().reserve( n );
}
void reverse()
{
this->base().reverse();
}
public: // assign, insert, transfer
// overhead: 1 heap allocation (very cheap compared to cloning)
template< class InputIterator >
void assign( InputIterator first, InputIterator last ) // strong
{
base_type temp( first, last );
this->swap( temp );
}
template< class Range >
void assign( const Range& r ) // strong
{
assign( boost::begin(r), boost::end(r ) );
}
private:
template< class I >
void insert_impl( iterator before, I first, I last, std::input_iterator_tag ) // strong
{
ptr_sequence_adapter temp(first,last); // strong
transfer( before, temp ); // strong, commit
}
template< class I >
void insert_impl( iterator before, I first, I last, std::forward_iterator_tag ) // strong
{
if( first == last )
return;
scoped_deleter sd( *this, first, last ); // strong
this->insert_clones_and_release( sd, before ); // strong, commit
}
public:
using base_type::insert;
template< class InputIterator >
void insert( iterator before, InputIterator first, InputIterator last ) // strong
{
insert_impl( before, first, last, BOOST_DEDUCED_TYPENAME
iterator_category<InputIterator>::type() );
}
#if defined(BOOST_NO_SFINAE) || defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
#else
template< class Range >
BOOST_DEDUCED_TYPENAME
boost::disable_if< ptr_container_detail::is_pointer_or_integral<Range> >::type
insert( iterator before, const Range& r )
{
insert( before, boost::begin(r), boost::end(r) );
}
#endif
template< class PtrSeqAdapter >
void transfer( iterator before,
BOOST_DEDUCED_TYPENAME PtrSeqAdapter::iterator first,
BOOST_DEDUCED_TYPENAME PtrSeqAdapter::iterator last,
PtrSeqAdapter& from ) // strong
{
BOOST_ASSERT( (void*)&from != (void*)this );
if( from.empty() )
return;
this->base().
insert( before.base(), first.base(), last.base() ); // strong
from.base().erase( first.base(), last.base() ); // nothrow
}
template< class PtrSeqAdapter >
void transfer( iterator before,
BOOST_DEDUCED_TYPENAME PtrSeqAdapter::iterator object,
PtrSeqAdapter& from ) // strong
{
BOOST_ASSERT( (void*)&from != (void*)this );
if( from.empty() )
return;
this->base().insert( before.base(), *object.base() ); // strong
from.base().erase( object.base() ); // nothrow
}
#if defined(BOOST_NO_SFINAE) || defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
#else
template< class PtrSeqAdapter, class Range >
BOOST_DEDUCED_TYPENAME boost::disable_if< boost::is_same< Range,
BOOST_DEDUCED_TYPENAME PtrSeqAdapter::iterator > >::type
transfer( iterator before, const Range& r, PtrSeqAdapter& from ) // strong
{
transfer( before, boost::begin(r), boost::end(r), from );
}
#endif
template< class PtrSeqAdapter >
void transfer( iterator before, PtrSeqAdapter& from ) // strong
{
BOOST_ASSERT( (void*)&from != (void*)this );
if( from.empty() )
return;
this->base().
insert( before.base(),
from.begin().base(), from.end().base() ); // strong
from.base().clear(); // nothrow
}
public: // C-array support
void transfer( iterator before, value_type* from,
size_type size, bool delete_from = true ) // strong
{
BOOST_ASSERT( from != 0 );
if( delete_from )
{
BOOST_DEDUCED_TYPENAME base_type::scoped_deleter
deleter( *this, from, size ); // nothrow
this->base().insert( before.base(), from, from + size ); // strong
deleter.release(); // nothrow
}
else
{
this->base().insert( before.base(), from, from + size ); // strong
}
}
value_type* c_array() // nothrow
{
if( this->empty() )
return 0;
T** res = reinterpret_cast<T**>( &this->begin().base()[0] );
return res;
}
public: // null functions
bool is_null( size_type idx ) const
{
BOOST_ASSERT( idx < this->size() );
return this->base()[idx] == 0;
}
public: // resize
void resize( size_type size ) // basic
{
size_type old_size = this->size();
if( old_size > size )
{
this->erase( boost::next( this->begin(), size ), this->end() );
}
else if( size > old_size )
{
for( ; old_size != size; ++old_size )
this->push_back( new BOOST_DEDUCED_TYPENAME
boost::remove_pointer<value_type>::type() );
}
BOOST_ASSERT( this->size() == size );
}
void resize( size_type size, value_type to_clone ) // basic
{
size_type old_size = this->size();
if( old_size > size )
{
this->erase( boost::next( this->begin(), size ), this->end() );
}
else if( size > old_size )
{
for( ; old_size != size; ++old_size )
this->push_back( this->null_policy_allocate_clone( to_clone ) );
}
BOOST_ASSERT( this->size() == size );
}
void rresize( size_type size ) // basic
{
size_type old_size = this->size();
if( old_size > size )
{
this->erase( this->begin(),
boost::next( this->begin(), old_size - size ) );
}
else if( size > old_size )
{
for( ; old_size != size; ++old_size )
this->push_front( new BOOST_DEDUCED_TYPENAME
boost::remove_pointer<value_type>::type() );
}
BOOST_ASSERT( this->size() == size );
}
void rresize( size_type size, value_type to_clone ) // basic
{
size_type old_size = this->size();
if( old_size > size )
{
this->erase( this->begin(),
boost::next( this->begin(), old_size - size ) );
}
else if( size > old_size )
{
for( ; old_size != size; ++old_size )
this->push_front( this->null_policy_allocate_clone( to_clone ) );
}
BOOST_ASSERT( this->size() == size );
}
public: // algorithms
void sort( iterator first, iterator last )
{
sort( first, last, std::less<T>() );
}
void sort()
{
sort( this->begin(), this->end() );
}
template< class Compare >
void sort( iterator first, iterator last, Compare comp )
{
BOOST_ASSERT( first <= last && "out of range sort()" );
BOOST_ASSERT( this->begin() <= first && "out of range sort()" );
BOOST_ASSERT( last <= this->end() && "out of range sort()" );
// some static assert on the arguments of the comparison
std::sort( first.base(), last.base(),
void_ptr_indirect_fun<Compare,T>(comp) );
}
template< class Compare >
void sort( Compare comp )
{
sort( this->begin(), this->end(), comp );
}
void unique( iterator first, iterator last )
{
unique( first, last, std::equal_to<T>() );
}
void unique()
{
unique( this->begin(), this->end() );
}
private:
struct is_not_zero_ptr
{
template< class U >
bool operator()( const U* r ) const
{
return r != 0;
}
};
protected:
template< class Fun, class Arg1 >
class void_ptr_delete_if
{
Fun fun;
public:
void_ptr_delete_if() : fun(Fun())
{ }
void_ptr_delete_if( Fun f ) : fun(f)
{ }
bool operator()( void* r ) const
{
BOOST_ASSERT( r != 0 );
Arg1 arg1 = static_cast<Arg1>(r);
if( fun( *arg1 ) )
{
clone_allocator_type::deallocate_clone( arg1 );
return true;
}
return false;
}
};
private:
void compact_and_erase_nulls( iterator first, iterator last ) // nothrow
{
typename base_type::ptr_iterator p = std::stable_partition(
first.base(),
last.base(),
is_not_zero_ptr() );
this->base().erase( p, this->end().base() );
}
void range_check_impl( iterator first, iterator last,
std::bidirectional_iterator_tag )
{ /* do nothing */ }
void range_check_impl( iterator first, iterator last,
std::random_access_iterator_tag )
{
BOOST_ASSERT( first <= last && "out of range unique()/erase_if()" );
BOOST_ASSERT( this->begin() <= first && "out of range unique()/erase_if()" );
BOOST_ASSERT( last <= this->end() && "out of range unique()/erase_if)(" );
}
void range_check( iterator first, iterator last )
{
range_check_impl( first, last,
BOOST_DEDUCED_TYPENAME iterator_category<iterator>::type() );
}
public:
template< class Compare >
void unique( iterator first, iterator last, Compare comp )
{
range_check(first,last);
iterator prev = first;
iterator next = first;
++next;
for( ; next != last; ++next )
{
BOOST_ASSERT( !::boost::is_null(prev) );
BOOST_ASSERT( !::boost::is_null(next) );
if( comp( *prev, *next ) )
{
this->remove( next ); // delete object
*next.base() = 0; // mark pointer as deleted
}
else
{
prev = next;
}
// ++next
}
compact_and_erase_nulls( first, last );
}
template< class Compare >
void unique( Compare comp )
{
unique( this->begin(), this->end(), comp );
}
template< class Pred >
void erase_if( iterator first, iterator last, Pred pred )
{
range_check(first,last);
this->base().erase( std::remove_if( first.base(), last.base(),
void_ptr_delete_if<Pred,value_type>(pred) ),
last.base() );
}
template< class Pred >
void erase_if( Pred pred )
{
erase_if( this->begin(), this->end(), pred );
}
void merge( iterator first, iterator last,
ptr_sequence_adapter& from )
{
merge( first, last, from, std::less<T>() );
}
template< class BinPred >
void merge( iterator first, iterator last,
ptr_sequence_adapter& from, BinPred pred )
{
void_ptr_indirect_fun<BinPred,T> bin_pred(pred);
size_type current_size = this->size();
this->transfer( this->end(), first, last, from );
typename base_type::ptr_iterator middle = this->begin().base();
std::advance(middle,current_size);
std::inplace_merge( this->begin().base(),
middle,
this->end().base(),
bin_pred );
}
void merge( ptr_sequence_adapter& r )
{
merge( r, std::less<T>() );
BOOST_ASSERT( r.empty() );
}
template< class BinPred >
void merge( ptr_sequence_adapter& r, BinPred pred )
{
merge( r.begin(), r.end(), r, pred );
BOOST_ASSERT( r.empty() );
}
};
} // namespace 'boost'
#endif
| [
"satoon101@gmail.com"
] | satoon101@gmail.com |
2c3809abab313609399dedd10082c951f9df08ec | 0dae1ca57bc87080ffde4eebf8ce9e9ac1338637 | /src/netfulfilledman.h | 5ec3b7fb3f7f0a256b198131f5b17499217e38d1 | [
"MIT"
] | permissive | kiranrh/innoket-master | 393cee942e2aadbeb3bc55a71b5928a1069da152 | 9bc414a7caea3ce1eaef8a171909d32e1e56711d | refs/heads/master | 2021-04-06T05:46:22.665334 | 2018-03-18T14:57:56 | 2018-03-18T14:57:56 | 125,207,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,587 | h | // Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The Innoket Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef NETFULFILLEDMAN_H
#define NETFULFILLEDMAN_H
#include "netbase.h"
#include "protocol.h"
#include "serialize.h"
#include "sync.h"
class CNetFulfilledRequestManager;
extern CNetFulfilledRequestManager netfulfilledman;
// Fulfilled requests are used to prevent nodes from asking for the same data on sync
// and from being banned for doing so too often.
class CNetFulfilledRequestManager
{
private:
typedef std::map<std::string, int64_t> fulfilledreqmapentry_t;
typedef std::map<CNetAddr, fulfilledreqmapentry_t> fulfilledreqmap_t;
//keep track of what node has/was asked for and when
fulfilledreqmap_t mapFulfilledRequests;
CCriticalSection cs_mapFulfilledRequests;
public:
CNetFulfilledRequestManager() {}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
LOCK(cs_mapFulfilledRequests);
READWRITE(mapFulfilledRequests);
}
void AddFulfilledRequest(CAddress addr, std::string strRequest); // expire after 1 hour by default
bool HasFulfilledRequest(CAddress addr, std::string strRequest);
void RemoveFulfilledRequest(CAddress addr, std::string strRequest);
void CheckAndRemove();
void Clear();
std::string ToString() const;
};
#endif
| [
"36470139+Innoket@users.noreply.github.com"
] | 36470139+Innoket@users.noreply.github.com |
684d121d1a32c385cee5527c94bc401662b29e6f | a64a8d76aac2c9a9cba574f7361f055472488557 | /Semester 1/Praktikum/TUGAS SORTING 1/SelectionSortModul.cpp | de326c4a6e2f9b324341b6e0f9f37e33f182c94a | [] | no_license | danielsitepu36/Cpp-as-the-first | 10ea28beff8557afecea15e4db5d677ac08e4ee2 | d94b8b7cfe8c3bdb3fbd55fb3cea11ee72534bd6 | refs/heads/master | 2020-07-06T12:49:53.446105 | 2019-08-28T12:29:16 | 2019-08-28T12:29:16 | 203,023,073 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 621 | cpp | #include<iostream>
using namespace std;
int main(){
int data[]={5,3,7,2,0,9,4,1,8,6};
int i,dataSize,temp,min;
dataSize=sizeof(data)/sizeof(data[0]);
cout<<"PROGRAM SELECTION SORT"<<endl;
cout<<"Data sebelum diurutkan = "<<endl;
for(int j=0;j<dataSize;j++){
cout<<data[j]<<" ";
}
for(int i=0;i<dataSize-1;i++){
min=i;
for(int j=i+1;j<dataSize;j++){
if(data[j]<data[min]){
min=j;
}
}
temp=data[i];
data[i]=data[min];
data[min]=temp;
}
cout<<endl<<"Data setelah diurutkan = "<<endl;
for(int j=0;j<dataSize;j++){
cout<<data[j]<<" ";
}
cout<<endl;
system("PAUSE");
return 0;
}
| [
"danielsitepu96@users.noreply.github.com"
] | danielsitepu96@users.noreply.github.com |
16c1a993a0caa920577026a20c4a430fc21e36ef | 3333dd52c91331597c0a785c1ae8e663ae12dfdd | /CNT/Semester 3/CNT353/LAB3/LAB3/Germ.cpp | 01193b8e95834a3820184ad209b478619769b378 | [] | no_license | mtikoian/School | 2e20f2fc1d6992d0047bc8686c8ac34be4369c3c | 901d5ea0fd384c1713f6a7415401f15cbc75e274 | refs/heads/master | 2020-12-03T08:44:16.261018 | 2018-01-31T16:22:19 | 2018-01-31T16:22:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,903 | cpp | /****************************************************
Project: Lab 03 - Petri dish
Files: Germ.h, Germ.cpp, Dish.h, Dish.cpp
Date: 06 Mar 2007
Author: Addison Babcock Class: CNT3K
Instructor: Herb V. Course: CNT353
Description: Petri dish simulation
****************************************************/
#include "Dish.h"
#include "Germ.h"
CDrawInterface CGerm::_draw;
// Function name : CGerm::CheckHealth ()
// Description : Checks the supplied argument to see if it is valid.
// Argument : int iHealth - the health to be checked for validity
// Return type : bool - true if the supplied argument is a valid health
bool CGerm::CheckHealth (int iHealth)
{
return iHealth >= 0 && iHealth <= gkiMaxHealth;
}
// Function name : CGerm::Show ()
// Description : Shows the germs health on the _draw interface
// Return type : void
void CGerm::Show () const
{
//show the germ on the display
_draw.SetColor (_iHealth * 25, _iHealth * 25, 0);
_draw.SetSpace (_iRow, _iCol);
}
// Function name : CGerm::Clear ()
// Description : Clears the drawing interface
// Return type : void
void CGerm::Clear ()
{
//set the bg color and clear the display
_draw.SetBackroundColor (0,0, 0);
_draw.Clear ();
}
// Function name : CGerm::CGerm ()
// Description : Initializes the germ, iRow and iCol are bounds checked
// Argument : int iRow - the row this germ is located in
// Argument : int iCol - the column this germ is located in
CGerm::CGerm(int iRow, int iCol) : _iHealth (0), _iRow (0), _iCol (0)
{
if (iRow < 0 || iRow > gkiRows)
{
cerr << gkszCGermCGerm << " : " << gkszRowOOR << " : " << iRow <<endl;
return;
}
if (iCol < 0 || iCol > gkiCols)
{
cerr << gkszCGermCGerm << " : " << gkszColOOR << " : " << iCol << endl;
return;
}
_iRow = iRow;
_iCol = iCol;
} | [
"addison@a587bc9e-4a24-0a48-8c52-e76df6254a9c"
] | addison@a587bc9e-4a24-0a48-8c52-e76df6254a9c |
a7dcfa2045ab95010df4273dd18f2fdae51b4b72 | 32f0212af6c615868940f44b2e57686f9d755d57 | /Judge/BaekjoonOnline/baekjoon5582.cpp | c3230da0da72122723938b59a22b26213c993856 | [] | no_license | micMalloc/Algorithm | 9aa3c47b492fe7be2239a14501aac4fd9efc5a47 | 766626bea64af6c681803efc153eaf23a7c305a2 | refs/heads/master | 2021-06-11T18:42:35.917637 | 2020-07-01T15:25:48 | 2020-07-01T15:25:48 | 93,248,063 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cpp | #include <iostream>
#include <algorithm>
#define _BUFSIZE 4001
using namespace std;
int dp[_BUFSIZE][_BUFSIZE];
int LCS (string str1, string str2) {
int max_length;
int len1, len2;
len1 = str1.length();
len2 = str2.length();
max_length = 0;
for (int i = 0; i <= max(len1, len2); ++ i) {
dp[i][0] = dp[0][i] = 0;
}
for (int i = 1; i <= len1; ++ i) {
for (int j = 1; j <= len2; ++ j) {
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
max_length = max(max_length, dp[i][j]);
}
}
}
return max_length;
}
int main (int argc, char* argv[]) {
ios::sync_with_stdio(false);
string str1;
string str2;
cin >> str1;
cin >> str2;
printf("%d\n", LCS(str1, str2));
return 0;
} | [
"hesue615@naver.com"
] | hesue615@naver.com |
93ad8979f335cc3fb89e410a3ea99ee9d6cc0068 | 2cc9e5f2faf6016243e63fa43aff8725c0b41260 | /Assignments/Solutions/Assign6_Q3.cpp | f96064dd07e76e7bd8744d784e104eb8e794d1df | [] | no_license | prakharshreyash/DSA_Uplift_Project | 3e16f8c4a2433647e8ec0e28c644027f40282900 | 100316efca135f7fcb8b30c42f105b5c664952df | refs/heads/master | 2023-08-03T10:35:39.512939 | 2021-09-11T02:38:18 | 2021-09-11T02:38:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 790 | cpp | #include <bits/stdc++.h>
using namespace std;
int binarySearch(int arr[], int low, int high, int x)
{
while (low <= high)
{
int mid = (low + high) / 2;
if (arr[mid] == x)
return mid;
else if (arr[mid] > x)
high = mid - 1;
else
low = mid + 1;
}
}
string isKSortedArray(int arr[], int n, int k)
{
int aux[n];
for (int i = 0; i<n; i++)
aux[i] = arr[i];
sort(aux, aux + n);
for (int i = 0; i<n; i++)
{
int j = binarySearch(aux, 0, n-1, arr[i]);
if (abs(i - j) > k)
return "No";
}
return "Yes";
}
int main()
{
int arr[] = {3, 2, 1, 5, 6, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
cout << "Is it a k sorted array?: "
<< isKSortedArray(arr, n, k);
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
6f0e1ba6c37becfb3e245d6bdf0970cb1cb3ebf8 | c47c254ca476c1f9969f8f3e89acb4d0618c14b6 | /datasets/tensorflow-1.0.1/tensorflow/compiler/tf2xla/kernels/gather_op.cc | b98d3864790ea24e8c80c2c7e0c083a4a9ad1acf | [
"BSD-2-Clause",
"Apache-2.0"
] | permissive | yijunyu/demo | 5cf4e83f585254a28b31c4a050630b8f661a90c8 | 11c0c84081a3181494b9c469bda42a313c457ad2 | refs/heads/master | 2023-02-22T09:00:12.023083 | 2021-01-25T16:51:40 | 2021-01-25T16:51:40 | 175,939,000 | 3 | 6 | BSD-2-Clause | 2021-01-09T23:00:12 | 2019-03-16T07:13:00 | C | UTF-8 | C++ | false | false | 4,105 | cc | /* Copyright 2017 The TensorFlow 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.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/xla_compilation_device.h"
#include "tensorflow/compiler/tf2xla/xla_context.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/core/framework/kernel_def_builder.h"
namespace tensorflow {
namespace {
class GatherOp : public XlaOpKernel {
public:
explicit GatherOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override {
const TensorShape params_shape = ctx->InputShape(0);
const TensorShape indices_shape = ctx->InputShape(1);
OP_REQUIRES(
ctx, TensorShapeUtils::IsVectorOrHigher(params_shape),
errors::InvalidArgument("params must be at least 1 dimensional"));
DataType index_type = input_type(1);
OP_REQUIRES(ctx, index_type == DT_INT32 || index_type == DT_INT64,
errors::InvalidArgument("index must be int32 or int64"));
// Check that we have enough index space.
const int64 limit = index_type == DT_INT32
? std::numeric_limits<int32>::max()
: std::numeric_limits<int64>::max();
OP_REQUIRES(
ctx, params_shape.dim_size(0) <= limit,
errors::InvalidArgument("params.shape[0] too large for ",
DataTypeString(index_type), " indexing: ",
params_shape.dim_size(0), " > ", limit));
// The result shape is indices.shape + params.shape[1:].
TensorShape result_shape = indices_shape;
for (int i = 1; i < params_shape.dims(); i++) {
result_shape.AddDim(params_shape.dim_size(i));
}
XlaContext& tc = XlaContext::Get(ctx);
OP_REQUIRES(
ctx, tc.allow_cpu_custom_calls(),
errors::InvalidArgument("Gather op requires CustomCall on CPU"));
xla::ComputationBuilder& b = *ctx->builder();
// Call gather_xla_float_kernel (from gather_op_kernel_float.cc).
// XLA passes <out> to the function, so it is not included here.
std::vector<xla::ComputationDataHandle> args;
args.push_back(tc.GetOrCreateRuntimeContextParameter());
args.push_back(b.ConstantLiteral(
*xla::LiteralUtil::CreateR0<int64>(indices_shape.num_elements())));
args.push_back(b.ConstantLiteral(
*xla::LiteralUtil::CreateR0<int64>(params_shape.dim_size(0))));
args.push_back(b.ConstantLiteral(*xla::LiteralUtil::CreateR0<int64>(
params_shape.num_elements() / params_shape.dim_size(0))));
args.push_back(ctx->Input(0));
args.push_back(ctx->Input(1));
xla::Shape xla_out_shape;
OP_REQUIRES_OK(
ctx, TensorShapeToXLAShape(DT_FLOAT, result_shape, &xla_out_shape));
// Call the custom code with args:
xla::ComputationDataHandle output;
if (index_type == DT_INT32) {
output = b.CustomCall("gather_float_int32_xla_impl", args, xla_out_shape);
} else {
output = b.CustomCall("gather_float_int64_xla_impl", args, xla_out_shape);
}
ctx->SetOutput(0, output);
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(GatherOp);
};
REGISTER_XLA_OP("Gather", GatherOp);
REGISTER_XLA_KERNEL(DEVICE_CPU_XLA_JIT,
Name("Gather")
.TypeConstraint("Tparams", DT_FLOAT)
.TypeConstraint("Tindices", {DT_INT32, DT_INT64}));
} // namespace
} // namespace tensorflow
| [
"y.yu@open.ac.uk"
] | y.yu@open.ac.uk |
32e97d2a8e4c4f972fce948a89ea06be137b385e | b030fcd33d6960af0e5d0d4ddc0c5b12d9ec3fcb | /Invader2.cpp | bb6de4b8ac63d6c0462e20a6f6f8ddb4a4ce64b1 | [] | no_license | Jun1981/C-- | 43e147becb5d1fb49a589d4e0a87a62e4add08c4 | e1ce08ed7d9280a38e15f1fcb6494e7faef10652 | refs/heads/master | 2021-01-13T01:35:51.485086 | 2014-07-16T15:04:39 | 2014-07-16T15:04:39 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 24,298 | cpp | /************************************
* *
* シューティングゲームループ *
* *
************************************
*/
//------ インクルードファイルの読み込み ------//
#include "../DxLib/DxLib.h"
#include<windows.h>
#include<time.h>
#include <stdlib.h>
#define kazu 100
#define jikidan_kankaku 3;
//------ 関数のプロトタイプ宣言 ------//
void start();//タイトル画面
void key_check(); // キー情報取得
void game_main(); // ゲームコントロールメイン
void init(); // ゲームシステム初期化
void haikei();//背景表示
void hyouji_all();//表示全体
void jikidan_hassha();//自機弾発射
void jiki_hyouji();
void jiki_sousa();
void jikidan_hyouji();
void jikidan_idou();
void jiki_tenmetsu();
void teki_hyouji();
void tekidan_hyouji();
void tekidan_idou();
void tekidan_hassha();
void zanki();
void teki_idou();//敵移動関数
void haji_chk();
void counter();//カウンタ関数
void gover_chk();//敵が自分のラインに到達したらゲームオーバー
void teki_atari();//自機弾と敵の当たり判定関数
void jiki_atari();//敵弾と自機の当たり判定関数
void sentou_chk();//敵の列の中で先頭が誰かチェック
void teki_nokori_chk();//敵の残りチェック
void sc_chk();//点数計算
void tm_cnt();//タイマー関数
void fade();//フェード関数
//関数宣言終わり
//------ 変数の定義 ------//
int Key_Trg, Key_Info, Key_Old; // キー情報r
int ChkKAny; // とにかくキーが押されたらtrue
int GLpCnt; // ゲームループカウンタ
int i, j, k,l;//ループ用
int title;//タイトル画像読み込み用
int bg; //ゲーム本編背景画像用
int GO;//ゲームオーバー画面読み取り用
int cl;//クリア画面用
int S1, S2;//音声用
int chr[10];//キャラクター分割画像読み込み用変数
int tm[2];//弾データ読み込み用変数
int FontHandle1;//タイトル用フォントハンドラ;//フォントハンドラ1用
int FontHandle2;//ゲーム用フォントハンドラ;//フォントハンドラ2用
int migihaji;//右端のx座標を入れる変数
int hidarihaji;//左端のx座標をいれる変数
int T_Cnt;//タイトルのPUSH SPACE点滅用
unsigned long tm_1;//タイマー開始
unsigned long tm_2;//タイマー終了
unsigned long r_tm;//残り時間変数
unsigned long tm_p;//経過時間(秒)
int t_flag;//タイマーフラグ
//初期化が必要な変数群
int lx;//キャラクタ横の長さ
int ly;//キャラクタ縦の長さ
int G_mode;//ゲームモード切り替え用
int stop;//端に行った時たてるフラグ
int UFO=0;//UFOフラグ
int dead_cnt;//死んだときのカウンタ
int en_cnt_MAX = 100;//敵が何ループごとに動くか最大値
int en_cnt = en_cnt_MAX;//敵が何ループごとに動くか
int haji ;//敵が端に来たときのフラグ
static signed int alpha;
int fade_mode=0 ;//1がフェードイン2がフェードアウト
int sentou[5][11];
int teki_nokori ;//敵の残り
int yoyuu=8;//自機の当たり判定を緩める
struct par{
int x;//x座標
int y;//y座標
int sp;//スピード
int t_sp;//弾スピード
int dead;//死んでるかどうか
int life;//残り自機
int count;//カウンタ
int count_MAX;//カウンタ最大値
int shot[10];//弾が出たかどうか
int kankaku;//敵の弾を撃つ間隔
int kankaku_sk;//敵の弾うち間隔初期値
int tama_x[10];
int tama_y[10];
int sentou;//今先頭にいるかどうか
int flag;//
int tama_cnt;//自機弾の間隔
};//各キャラのパラメータ
struct score{
unsigned long now;//現在スコア
unsigned long high;//ハイスコア
}ten = { 0, 0 };
struct par teki[3][2][11];///敵の構造体宣言(強さ、何段目か、何列目)
struct par jiki;//自機の構造体宣言
struct par tama[kazu];//発射した弾
/**********************
* Main program *
**********************
*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
ChangeWindowMode(TRUE); // ウインドウモードに変更(ただし、256色)
if (DxLib_Init() == -1) { // DXライブラリ初期化処理
return -1; // エラーが起きたら直ちに終了
}
SetDrawScreen(DX_SCREEN_BACK); // 描画先を裏画面へ
init();
PlaySoundMem(S1, DX_PLAYTYPE_BACK);
// ゲームシステム初期化
//------ ゲームループ ------//
while (CheckHitKey(KEY_INPUT_ESCAPE) == 0) { // Escキーが押されるまでループ
ClsDrawScreen(); // 裏画面クリア
key_check(); // キー情報取得
game_main(); // ゲームコントロールメイン
GLpCnt++; // ゲームループカウンタをプラス
/////////////////// For debug
// フレーム(ゲーム)カウント表示
char b[20];
wsprintf(b, "%08X", GLpCnt);
DrawString(500, 32, b, GetColor(255, 255, 255));
wsprintf(b, "%08X", Key_Info);
DrawString(500, 52, b, GetColor(255, 255, 255));
DrawFormatStringToHandle(500, 72, GetColor(255, 255, 255), FontHandle2, "%d", teki_nokori);//敵の残りの数
/////////////////// For debug
ScreenFlip(); // 裏画面を表画面へ
if (ProcessMessage() == -1) { // メッセージ処理
break; // エラーが起きたらループから抜ける
}
}
DxLib_End(); // DXライブラリ使用の終了処理
return 0; // アプリケーションの終了
}
/*-----------------------------
* ゲームシステム初期化 *
*-----------------------------
*/
void init()
{
//ランダム生成
srand((unsigned)time(NULL));
// ゲーム全体に関わる変数の初期化、画像ファイルの読み込みなどを書く
LoadDivGraph("../Img/en_my.png", 10, 5, 2, 32, 16, chr, 0);//キャラクタ読み込み
LoadDivGraph("../Img/missile1.png", 2, 2, 1, 2, 16, tm, 0);//弾画像の読み込み
title = LoadGraph("../Img/title.bmp");//タイトル画像読み込み
bg = LoadGraph("../Img/bg.jpg");//ゲーム本編背景画像
GO = LoadGraph("../Img/gover.jpg");//ゲームオーバー画面
cl = LoadGraph("../Img/gclear.jpg");//クリア画面
S1 = LoadSoundMem("G:/SVA/satou/INVADER/Sound/1.wav");
FontHandle1 = CreateFontToHandle(NULL, 40, 4);//タイトル用フォントハンドラ;//フォントハンドラ1
FontHandle2 = CreateFontToHandle(NULL, 16, 8);//ゲーム用フォントハンドラ;//フォントハンドラ2
//初期変数数値設定
lx = 32;//キャラクタ横の長さ
ly = 16;//キャラクタ縦の長さ
G_mode = 0;//ゲームモード
T_Cnt = 20;//タイトル”PUSH SPACE”点滅用カウンタ
migihaji = 450 + 30;//キャラクタ描写領域右端のx座標
hidarihaji = 30;//キャラクタ描写領域左端のx座標
stop = 0;//敵全体をストップする
UFO=0;//UFOフラグ0
dead_cnt=200;//自機死亡カウント初期値
en_cnt_MAX=100;//敵が何ループごとに動くかの最大値
en_cnt = en_cnt_MAX;//敵が何ループごとに動くか
haji = 0;//敵が端に来たときのフラグ
alpha=0;//フェード用変数
fade_mode=0;//フェードモード
teki_nokori=55;//敵の残り
jiki.x = 225 + 32; jiki.y = 480 - (16 * 5), jiki.sp = 2; jiki.t_sp = 4; jiki.dead = 0; jiki.life = 3; //自機の構造体宣言
ten.now = 0;//現在スコアの初期化
jiki.tama_cnt=jikidan_kankaku;
r_tm = 30;//残り時間初期化
t_flag = 0;//タイマースイッチ0
for (k = 0; k < 11; k++){
teki[0][0][k].y = ly * 5;//緑の敵の初期y座標
teki[0][0][k].t_sp = 6;//弾の速さ
teki[1][0][k].y = ly * 7;//水色1初期y座標
teki[1][0][k].t_sp = 4;//弾の速さ
teki[1][1][k].y = ly * 9;//水色2初期y座標
teki[1][1][k].t_sp = 4;//弾の速さ
teki[2][0][k].y = ly * 11;//紫1初期y座標
teki[2][0][k].t_sp = 3;//弾の速さ
teki[2][1][k].y = ly * 13;//紫2初期y座標
teki[2][1][k].t_sp = 3;//弾の速さ
//敵の弾撃ち間隔初期値設定
for (l = 0; l < 10; l++){
teki[0][0][k].kankaku_sk = rand() % 30 + 15;//緑の敵の弾うち間隔
teki[0][0][k].kankaku = teki[0][0][k].kankaku_sk;
teki[1][0][k].kankaku_sk = rand() % 30 + 60;//水色1敵の弾うち間隔
teki[1][0][k].kankaku = teki[1][0][k].kankaku_sk;
teki[1][1][k].kankaku_sk = rand() % 30 + 60;//水色2敵の弾うち間隔
teki[1][1][k].kankaku = teki[1][1][k].kankaku_sk;
teki[2][0][k].kankaku_sk = rand() % 50 + 100;//紫1敵の弾うち間隔
teki[2][0][k].kankaku = teki[2][0][k].kankaku_sk;
teki[2][1][k].kankaku_sk = rand() % 50 + 100;//紫2敵の弾うち間隔
teki[2][1][k].kankaku = teki[2][1][k].kankaku_sk;
}
//敵関係初期値
for (j = 0; j < 2; j++){
for (i = 0; i < 3; i++){
for (l = 0; l < 10; l++){
teki[i][j][k].shot[l] = 0;//敵ショットフラグ0
}
teki[i][j][k].x = (lx - 1) + lx*k;//緑の敵のx座標
teki[i][j][k].sp = lx / 2;//敵の一回の移動距離
teki[i][j][k].dead = 0;//敵に弾が当たったかどうか(1で当たり)
teki[i][j][k].sentou=0;//先頭フラグ
}
}
teki[0][1][k].dead = 1;//余分な敵を殺す(緑の2列目)
}
for (i = 0; i < kazu; i++){
tama[i].flag = 0;//弾が出ていない
}
}
/**********************************
* ゲームコントロールメイン *
**********************************
*/
////メイン//////////////////////////////////////////////////////////////////////
void game_main()
{
//static int alpha;
// ゲームの処理を書く
switch (G_mode)
{
case 0:
start();//スタート画面
break;
case 1://タイトルのフェードアウト
if (alpha <= 0) {
G_mode = 10;//ゲーム本編へ
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
fade_mode = 1;
break;
}
alpha -= 4;
SetDrawBlendMode(DX_BLENDMODE_ALPHA, alpha);
DrawGraph(70, 80, title, TRUE);//タイトルの表示
break;
case 10://ゲーム本編
tm_cnt();//タイマー
fade();//フェードイン/アウト
if (stop == 0){
tekidan_hassha();//敵弾発射
teki_atari();//自機の弾と敵の当たりチェック
gover_chk();//敵が自分のラインに到達したらゲームオーバー
jiki_atari();//敵弾と自機の当たりチェック
jiki_sousa();//自機の移動
teki_idou();//敵移動関数
haji_chk();
jikidan_idou();//自機弾移動
tekidan_idou();//敵弾移動
}
sentou_chk();//列で誰が先頭にいるか
teki_nokori_chk();//敵の残りチェック
hyouji_all();//表示関数
counter();
break;
case 2://ゲームオーバー
sc_chk();
if (alpha <= 251){
alpha += 2;
SetDrawBlendMode(DX_BLENDMODE_ALPHA, alpha);
}else{
WaitKey();
if(GetKeyState(0x52)<0){
init();
G_mode = 1;//ゲームへ
break;
}
}
//DrawGraph(0, 0, GO, TRUE);
SetFontSize(32);// 文字の大きさを指定する
DrawFormatString(100, 20, GetColor(255, 50, 50), " ゲームオーバー");
DrawFormatString(40, 120, GetColor(255,50,50), "スコア :%8d点", ten.now); // 現在の点数
DrawFormatString(40, 190, GetColor(255,50,50), "ハイスコア:%8d点", ten.high); // ハイスコア
DrawFormatString(40, 290, GetColor(255,50,50), "もう一度:R"); // 現在の点数
DrawFormatString(40, 360, GetColor(255,50,50), "やめる :ESC"); // ハイスコア
break;
case 3://クリア
sc_chk();
if (alpha <= 251){
alpha += 2;
SetDrawBlendMode(DX_BLENDMODE_ALPHA, alpha);
}else {
WaitKey();
if(GetKeyState(0x52)<0){
init();
G_mode=1;//ゲームへ
break;
}
}
SetFontSize(32);// 文字の大きさを指定する
DrawFormatString(100, 20, GetColor(0, 219, 255), " クリア");
DrawFormatString(40, 90, GetColor(0, 219, 255), "スコア :%8d点", ten.now); // 現在の点数
DrawFormatString(40, 160, GetColor(0, 219, 255), "ハイスコア:%8d点", ten.high); // ハイスコア
DrawFormatString(40, 290, GetColor(0,219,255), "もう一度:R"); // 現在の点数
DrawFormatString(40, 360, GetColor(0,219,255), "やめる :ESC"); // ハイスコア
//DrawGraph(0, 0, cl, TRUE);
break;
}
}
///////////////////////////////////////////////////////////////////////////////////
/*---------------------
* キー情報取得 *
*---------------------
*
* LEFT = 0000 0001
* RIGHT = 0000 0010
* UP = 0000 0100
* DOWN = 0000 1000
* key_trgは押した瞬間の情報
* key_infoは今の状態
*
*/
void key_check()
{
Key_Trg = Key_Info = 0; // キー情報クリア
ChkKAny = false;
if (CheckHitKey(KEY_INPUT_LEFT)) { Key_Info |= 0x01; }
if (CheckHitKey(KEY_INPUT_RIGHT)) { Key_Info |= 0x02; }
if (CheckHitKey(KEY_INPUT_UP)) { Key_Info |= 0x04; }
if (CheckHitKey(KEY_INPUT_DOWN)) { Key_Info |= 0x08; }
if (CheckHitKey(KEY_INPUT_SPACE)) { Key_Info |= 0x10; }
if (CheckHitKey(KEY_INPUT_Z)) { Key_Info |= 0x20; }
if (CheckHitKey(KEY_INPUT_ESCAPE)) { Key_Info |= 0x40; }
if (CheckHitKeyAll()) { ChkKAny = true; } // あにー
Key_Trg = (Key_Info ^ Key_Old) & Key_Info; // キートリガー情報セット
Key_Old = Key_Info; // キー情報セーブ
}
///////// 表示関係 //////////////////////
void haikei()
{
DrawGraph(0, 0, bg, TRUE);
DrawFormatStringToHandle( 64, 20, GetColor(255, 255, 255), FontHandle2, "Score %6d", ten.now);//現在スコアの表示
DrawFormatStringToHandle(450 + 32 - 192, 20, GetColor(255, 255, 255), FontHandle2, "Hi-Score %6d", ten.high);//ハイスコアの表示
DrawFormatStringToHandle(160+30, 20, GetColor(255, 255, 255), FontHandle2, "残り%2d秒", r_tm);//残り時間表示
}
//フェード
void fade(){
if (fade_mode == 1){//フェードイン
if (alpha <= 251){
alpha += 2;
SetDrawBlendMode(DX_BLENDMODE_ALPHA, alpha);
}
}
else if (fade_mode == 2){//フェードアウト
if (alpha <= 2){
G_mode = 2;//ゲームオーバー画面へ
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
//break;
}
alpha -= 2;
SetDrawBlendMode(DX_BLENDMODE_ALPHA, alpha);
}
else if (fade_mode == 3){//フェードアウト
if (alpha <= 2){
G_mode = 3;//クリア画面へ
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
//break;
}
alpha -= 2;
SetDrawBlendMode(DX_BLENDMODE_ALPHA, alpha);
}
}
//自機関係関数
void hyouji_all(){
//背景・スコア表示
haikei();
zanki();
//自機弾
jikidan_hyouji();
//敵弾表示
tekidan_hyouji();//敵弾表示
jiki_hyouji();//自機の表示
teki_hyouji();//敵の表示
}
void jiki_hyouji(){//自機の表示
if (jiki.dead == 0){
DrawGraph(jiki.x, jiki.y, chr[3], TRUE);//自機の表示
}
else if (jiki.dead == 1){
if (dead_cnt % 10 >= 5)
DrawGraph(jiki.x, jiki.y, chr[5], TRUE);//自機の表示
else if (dead_cnt % 10 < 5)
DrawGraph(jiki.x, jiki.y, chr[6], TRUE);//自機の表示
}
}
//自機の操作
void jiki_sousa() {
if ((Key_Info & 0x01) == 0x01 && jiki.x > 31){
jiki.x -= jiki.sp;//左へ
}
if ((Key_Info & 0x02) == 0x02 && jiki.x + lx < 450 + 31){
jiki.x += jiki.sp;//右へ
}
//if( (Key_Info&0x10) == 0x10){
if ((Key_Trg & 0x10) == 0x10){
if (jiki.tama_cnt <= 0){
jiki.tama_cnt = jikidan_kankaku;
jikidan_hassha();//自機弾発射
}
}
}
///////////////////////////////////
void jikidan_hassha(){
for (i = 0; i < kazu; i++){
if (tama[i].flag == 0 && stop == 0){
tama[i].x = jiki.x + 15; tama[i].y = jiki.y;//弾に現在の自機座標代入
tama[i].flag = 1;//弾0の発射
return;
}
}
}
void jikidan_idou(){//自機弾移動
for (i = 0; i < kazu; i++){
if (tama[i].flag == 1){
tama[i].y -= jiki.t_sp;//弾のy座標を引く
if (tama[i].y + 16 < 0)//自機弾が上に達したらフラグ0
tama[i].flag = 0;
}
}
}
void jikidan_hyouji(){//自機の弾表示関数
for (i = 0; i < kazu; i++){
if (tama[i].flag == 1){
DrawGraph(tama[i].x, tama[i].y, tm[1], TRUE);//弾0描画
}
}
}
void zanki(){//残り自機表示
for (i = 0; i < jiki.life; i++){
DrawGraph(480 - lx*(1 + i), 480 - ly, chr[3], TRUE);//自機の表示
}
}
//敵表示
void teki_hyouji(){//敵表示
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
if (teki[i][j][k].dead == 0){
if (UFO == 0){
if (i == 0){
DrawGraph(teki[i][0][k].x, teki[i][0][k].y, chr[2], TRUE);//敵1(緑)表示
}
else if (i == 1){
DrawGraph(teki[i][j][k].x, teki[i][j][k].y, chr[1], TRUE);//敵2(水色)表示
}
else if (i == 2){
DrawGraph(teki[i][j][k].x, teki[i][j][k].y, chr[0], TRUE);//敵3(紫)表示
}
}
else{
DrawGraph(teki[i][j][k].x, teki[i][j][k].y,chr[4] , TRUE);//UFO表示
}
}
}
}
}
}
//敵弾発射
void tekidan_hassha(){
if (stop == 0){
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
teki[i][j][k].kankaku--;
if (teki[i][j][k].dead == 0 && teki[i][j][k].sentou == 1){
for (l = 0; l < 10; l++){
if (teki[i][j][k].kankaku <= 0 && teki[i][j][k].shot[l] == 0 && stop == 0){
teki[i][j][k].kankaku = teki[i][j][k].kankaku_sk;
teki[i][j][k].shot[l] = 1;//玉フラグ1
teki[i][j][k].tama_x[l] = teki[i][j][k].x + 15;
teki[i][j][k].tama_y[l] = teki[i][j][k].y;
return;
}
}
}
}
}
}
}
}
void tekidan_hyouji(){//敵弾表示
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
for (l = 0; l < 10; l++){
if (teki[i][j][k].shot[l] == 1)DrawGraph(teki[i][j][k].tama_x[l], teki[i][j][k].tama_y[l], tm[0], TRUE);//敵弾の表示
}
}
}
}
}
//敵弾移動
void tekidan_idou(){
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
for (l = 0; l < 10; l++){
if (teki[i][j][k].shot[l] == 1){
teki[i][j][k].tama_y[l] += teki[i][j][k].t_sp;//敵弾のy座標を下に
if (teki[i][j][k].tama_y[l] + 16 >= 640)
teki[i][j][k].shot[l] = 0;//敵弾フラグ0
}
}
}
}
}
}
//敵移動
void teki_idou(){
en_cnt--;
if (haji == 0){
if (en_cnt == 0){
en_cnt = en_cnt_MAX;
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
teki[i][j][k].x += teki[i][j][k].sp;
}
}
}
}
}
else{
if (en_cnt == 0){
en_cnt = en_cnt_MAX;
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
teki[i][j][k].y += lx;
teki[i][j][k].sp = ~teki[i][j][k].sp + 1;
haji = 0;
}
}
}
}
}
}
//敵が自分のラインに到達したらゲームオーバー
void gover_chk(){
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
if (teki[i][j][k].y >= jiki.y && teki[i][j][k].dead == 0){
stop = 1;
fade_mode = 2;
return;
}
}
}
}
}
//端に来たかどうか
void haji_chk(){
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
if ((teki[i][j][k].x + 32 >= 480 - 1 && teki[i][j][k].sp>0) || (teki[i][j][k].x <= 31 && teki[i][j][k].sp < 0)){
if (teki[i][j][k].dead == 0){
haji = 1;
break;
}
}
}
}
}
}
///弾と敵の当たり判定
void teki_atari(){
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
for (l = 0; l < kazu; l++){
if (tama[l].x + 2 >= teki[i][j][k].x + 4 && tama[l].x <= teki[i][j][k].x + 32 - 4 && tama[l].y <= teki[i][j][k].y + 16 && tama[l].y + 16 >= teki[i][j][k].y){
if (tama[l].flag == 1 && teki[i][j][k].dead == 0){
tama[l].flag = 0;//弾フラグ0
teki[i][j][k].dead = 1;//敵死亡
teki_nokori--;//敵残りの数
switch (i){
case 0:
ten.now += 100*r_tm;//100点プラス
break;
case 1:
ten.now += 50*r_tm;//50点プラス
break;
case 2:
ten.now += 10*r_tm;//10点プラス
break;
}
}
}
}
}
}
}
}
// 敵弾が自機に当たった時
void jiki_atari(){
for (i = 0; i < 3; i++){
for (j = 0; j < 2; j++){
for (k = 0; k < 11; k++){
for (l = 0; l<10; l++){
if (teki[i][j][k].tama_x[l] + 2 > jiki.x+yoyuu && teki[i][j][k].tama_x[l] < jiki.x + 32-yoyuu && teki[i][j][k].tama_y[l]<jiki.y + 16 && teki[i][j][k].tama_y[l] + 16>jiki.y){
if (jiki.dead == 0 && teki[i][j][k].shot[l] == 1 && stop==0){
stop = 1;
jiki.dead = 1;
teki[i][j][k].shot[l] = 0;
teki[i][j][k].kankaku = teki[i][j][k].kankaku_sk;
jiki.life--;//自機ライフーー
teki[i][j][k].tama_x[l] = -100;
teki[i][j][k].tama_y[l] = -100;
if (jiki.life < 0){
alpha = 255;
fade_mode = 2;//フェードアウト
return;
}
}
}
}
}
}
}
}
//敵の先頭チェック
void sentou_chk(){
for (i = 0; i < 11; i++){
if (teki[2][1][i].dead == 0){
teki[2][1][i].sentou = 1;
}
else if (teki[2][0][i].dead == 0){
teki[2][1][i].sentou = 0;
teki[2][0][i].sentou = 1;
}
else if (teki[1][1][i].dead == 0){
teki[2][0][i].sentou = 0;
teki[1][1][i].sentou = 1;
}
else if (teki[1][0][i].dead == 0){
teki[1][1][i].sentou = 0;
teki[1][0][i].sentou = 1;
}
else if (teki[0][0][i].dead == 0){
teki[1][0][i].sentou = 0;
teki[0][0][i].sentou = 1;
}
else{
teki[0][0][i].sentou = 0;
}
}
}
//敵の残りに応じた動作
void teki_nokori_chk(){
if (fade_mode!=3 && fade_mode!=2){
if (teki_nokori <=5){
if (UFO == 0){
en_cnt_MAX = 5;
UFO = 1;
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
for (k = 0; k < 11; k++) {
teki[i][j][k].t_sp = 6;
for (l = 0; l < 10; l++) {
teki[i][j][k].kankaku_sk = rand() % 25;
}
}
}
}
}
}
if (teki_nokori == 11){
en_cnt_MAX = 30;
}
if (teki_nokori == 22){
en_cnt_MAX = 50;
}
if (teki_nokori == 33){
en_cnt_MAX = 70;
}
if (teki_nokori == 44){
en_cnt_MAX = 90;
}
if (teki_nokori == 0){
alpha = 255;
fade_mode = 3;//フェードアウト
}
}
}
//スコアチェック
void sc_chk(){
if (ten.now > ten.high) ten.high = ten.now;
}
//カウンタ関数
void counter(){
jiki.tama_cnt--;
if (jiki.dead == 0 && stop == 0){
jiki.count--;
}
if (jiki.dead == 1){
dead_cnt--;
if (jiki.life >= 0){
if (dead_cnt == 100){
stop = 0;
}
else if (dead_cnt == 0){
dead_cnt = 200;
jiki.dead = 0;
}
}
}
}
//スタート画面
void start(){
DrawGraph(70, 80, title, TRUE);//タイトルの表示
//スペースキーを押してください画面
if (T_Cnt > 10)
{
DrawStringToHandle(170, 300, "Push Space Key !", GetColor(0, 219, 255), FontHandle1); //文字を画面中央に表示
}
else if (T_Cnt > 0)
{
DrawStringToHandle(170, 300, "Push Space Key !", GetColor(0, 0, 0), FontHandle1); //文字を画面中央に表示
}
else if (T_Cnt == 0)
{
T_Cnt = 20;
}
if (CheckHitKey(KEY_INPUT_SPACE))
{
G_mode = 1;//ゲーム本編へ
DeleteFontToHandle(FontHandle1);//フォントハンドラ1を捨てる
alpha = 255;
}
T_Cnt--;//カウンタを引く
}
void tm_cnt(){
if (t_flag == 0){
tm_1 = clock();
t_flag = 1;
}
tm_2 = clock();//タイマースタート
tm_p = (tm_2 - tm_1) / 1000;//経過した時間
if (r_tm > 0){
r_tm = 30 - tm_p ;//60秒から引く
}
else{
fade_mode = 2;//ゲームオーバー
stop = 1;
}
}
| [
"j1981_1@nifty.com"
] | j1981_1@nifty.com |
5a267f97801b8a5b7b62faa3504c109215cf731d | 4b078004300df75077b85531a0b030b62d93058d | /pentevo/unreal/Unreal/wldr_pro.cpp | a41700e72c8a5c81818e63f732e78b588f9a5117 | [] | no_license | fromGoogleCode/zx-evo-fpga | 551932681cd1a997ef9d64e3eda68e376d4a5536 | aa70245c677cd3adb1ce9881213b6b2cb7a5766a | refs/heads/master | 2021-01-25T07:34:09.654849 | 2015-01-25T23:09:22 | 2015-01-25T23:09:22 | 32,766,483 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,459 | cpp | #include "std.h"
#include "emul.h"
#include "vars.h"
#include "util.h"
static const u8 sn0[] = { 1, 2, 3, 4, 9 };
static const u8 sn[] = { 1, 2, 3, 4, 5 };
void FDD::format_pro()
{
newdisk(80, 2);
for (unsigned c = 0; c < cyls; c++)
{
for (unsigned h = 0; h < 2; h++)
{
t.seek(this, c, h, JUST_SEEK);
t.s = 5;
for (unsigned s = 0; s < 5; s++)
{
unsigned n = (c == 0 && h == 0) ? sn0[s] : sn[s];
t.hdr[s].n = n; t.hdr[s].l = 3;
t.hdr[s].c = c; t.hdr[s].s = h;
t.hdr[s].c1 = t.hdr[s].c2 = 0;
t.hdr[s].data = (u8*)1;
}
t.format();
}
}
}
int FDD::read_pro()
{
format_pro();
for (unsigned c = 0; c < cyls; c++)
{
for (unsigned h = 0; h < 2; h++)
{
for (unsigned s = 0; s < 5; s++)
{
t.seek(this, c, h, LOAD_SECTORS);
t.write_sector((c == 0 && h == 0) ? sn0[s] : sn[s], snbuf+(c*10 + h*5 + s)*1024);
}
}
}
return 1;
}
int FDD::write_pro(FILE *ff)
{
for (unsigned c = 0; c < 80; c++)
{
for (unsigned h = 0; h < 2; h++)
{
t.seek(this, c, h, LOAD_SECTORS);
for (unsigned s = 0; s < 5; s++)
{
if (fwrite(t.hdr[s].data, 1, 1024, ff) != 1024)
return 0;
}
}
}
return 1;
}
| [
"EARL@localhost"
] | EARL@localhost |
c994446f7fea0c480df3954ff41e860dfceaf84d | c2755e421e716a2e30b61c3b2ebfeaed99118f17 | /Library/Il2cppBuildCache/Android/arm64-v8a/il2cppOutput/Assembly-CSharp_Attr.cpp | d6d4bbcce8e7ab99bdd8b676e8adcd92755abe3e | [] | no_license | phunghocong/Shooting-Birds | cb7b7a7f02c40252bb61778d92e9a1e0a752d291 | 9def07452788b044bf67e428ff341a6c232acad3 | refs/heads/master | 2023-07-19T23:42:04.991614 | 2021-09-08T12:57:36 | 2021-09-08T12:57:36 | 404,345,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,029 | cpp | #include "pch-cpp.hpp"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <limits>
#include <stdint.h>
// System.Char[]
struct CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34;
// System.Type[]
struct TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755;
// System.Reflection.Binder
struct Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30;
// System.Runtime.CompilerServices.CompilationRelaxationsAttribute
struct CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF;
// System.Runtime.CompilerServices.CompilerGeneratedAttribute
struct CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C;
// System.Diagnostics.DebuggableAttribute
struct DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B;
// System.Diagnostics.DebuggerHiddenAttribute
struct DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88;
// UnityEngine.HeaderAttribute
struct HeaderAttribute_t9B431E6BA0524D46406D9C413D6A71CB5F2DD1AB;
// System.Runtime.CompilerServices.IteratorStateMachineAttribute
struct IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830;
// System.Reflection.MemberFilter
struct MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81;
// UnityEngine.RangeAttribute
struct RangeAttribute_t14A6532D68168764C15E7CF1FDABCD99CB32D0C5;
// System.Runtime.CompilerServices.RuntimeCompatibilityAttribute
struct RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80;
// System.String
struct String_t;
// System.Type
struct Type_t;
// System.Void
struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5;
IL2CPP_EXTERN_C const RuntimeType* U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_0_0_0_var;
IL2CPP_EXTERN_C const RuntimeType* U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_0_0_0_var;
IL2CPP_EXTERN_C_BEGIN
IL2CPP_EXTERN_C_END
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
// System.Attribute
struct Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71 : public RuntimeObject
{
public:
public:
};
// System.Reflection.MemberInfo
struct MemberInfo_t : public RuntimeObject
{
public:
public:
};
// System.String
struct String_t : public RuntimeObject
{
public:
// System.Int32 System.String::m_stringLength
int32_t ___m_stringLength_0;
// System.Char System.String::m_firstChar
Il2CppChar ___m_firstChar_1;
public:
inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); }
inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; }
inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; }
inline void set_m_stringLength_0(int32_t value)
{
___m_stringLength_0 = value;
}
inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); }
inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; }
inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; }
inline void set_m_firstChar_1(Il2CppChar value)
{
___m_firstChar_1 = value;
}
};
struct String_t_StaticFields
{
public:
// System.String System.String::Empty
String_t* ___Empty_5;
public:
inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); }
inline String_t* get_Empty_5() const { return ___Empty_5; }
inline String_t** get_address_of_Empty_5() { return &___Empty_5; }
inline void set_Empty_5(String_t* value)
{
___Empty_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___Empty_5), (void*)value);
}
};
// System.ValueType
struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 : public RuntimeObject
{
public:
public:
};
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_com
{
};
// System.Boolean
struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37, ___m_value_0)); }
inline bool get_m_value_0() const { return ___m_value_0; }
inline bool* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(bool value)
{
___m_value_0 = value;
}
};
struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields
{
public:
// System.String System.Boolean::TrueString
String_t* ___TrueString_5;
// System.String System.Boolean::FalseString
String_t* ___FalseString_6;
public:
inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___TrueString_5)); }
inline String_t* get_TrueString_5() const { return ___TrueString_5; }
inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; }
inline void set_TrueString_5(String_t* value)
{
___TrueString_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___TrueString_5), (void*)value);
}
inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___FalseString_6)); }
inline String_t* get_FalseString_6() const { return ___FalseString_6; }
inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; }
inline void set_FalseString_6(String_t* value)
{
___FalseString_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FalseString_6), (void*)value);
}
};
// System.Runtime.CompilerServices.CompilationRelaxationsAttribute
struct CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
// System.Int32 System.Runtime.CompilerServices.CompilationRelaxationsAttribute::m_relaxations
int32_t ___m_relaxations_0;
public:
inline static int32_t get_offset_of_m_relaxations_0() { return static_cast<int32_t>(offsetof(CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF, ___m_relaxations_0)); }
inline int32_t get_m_relaxations_0() const { return ___m_relaxations_0; }
inline int32_t* get_address_of_m_relaxations_0() { return &___m_relaxations_0; }
inline void set_m_relaxations_0(int32_t value)
{
___m_relaxations_0 = value;
}
};
// System.Runtime.CompilerServices.CompilerGeneratedAttribute
struct CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
public:
};
// System.Diagnostics.DebuggerHiddenAttribute
struct DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
public:
};
// System.Enum
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA : public ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52
{
public:
public:
};
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields
{
public:
// System.Char[] System.Enum::enumSeperatorCharArray
CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* ___enumSeperatorCharArray_0;
public:
inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields, ___enumSeperatorCharArray_0)); }
inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; }
inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; }
inline void set_enumSeperatorCharArray_0(CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* value)
{
___enumSeperatorCharArray_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___enumSeperatorCharArray_0), (void*)value);
}
};
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_com
{
};
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
// UnityEngine.PropertyAttribute
struct PropertyAttribute_t4A352471DF625C56C811E27AC86B7E1CE6444052 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
public:
};
// System.Runtime.CompilerServices.RuntimeCompatibilityAttribute
struct RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
// System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::m_wrapNonExceptionThrows
bool ___m_wrapNonExceptionThrows_0;
public:
inline static int32_t get_offset_of_m_wrapNonExceptionThrows_0() { return static_cast<int32_t>(offsetof(RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80, ___m_wrapNonExceptionThrows_0)); }
inline bool get_m_wrapNonExceptionThrows_0() const { return ___m_wrapNonExceptionThrows_0; }
inline bool* get_address_of_m_wrapNonExceptionThrows_0() { return &___m_wrapNonExceptionThrows_0; }
inline void set_m_wrapNonExceptionThrows_0(bool value)
{
___m_wrapNonExceptionThrows_0 = value;
}
};
// System.Runtime.CompilerServices.StateMachineAttribute
struct StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3 : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
// System.Type System.Runtime.CompilerServices.StateMachineAttribute::<StateMachineType>k__BackingField
Type_t * ___U3CStateMachineTypeU3Ek__BackingField_0;
public:
inline static int32_t get_offset_of_U3CStateMachineTypeU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3, ___U3CStateMachineTypeU3Ek__BackingField_0)); }
inline Type_t * get_U3CStateMachineTypeU3Ek__BackingField_0() const { return ___U3CStateMachineTypeU3Ek__BackingField_0; }
inline Type_t ** get_address_of_U3CStateMachineTypeU3Ek__BackingField_0() { return &___U3CStateMachineTypeU3Ek__BackingField_0; }
inline void set_U3CStateMachineTypeU3Ek__BackingField_0(Type_t * value)
{
___U3CStateMachineTypeU3Ek__BackingField_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___U3CStateMachineTypeU3Ek__BackingField_0), (void*)value);
}
};
// System.Void
struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5
{
public:
union
{
struct
{
};
uint8_t Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5__padding[1];
};
public:
};
// System.Reflection.BindingFlags
struct BindingFlags_tAAAB07D9AC588F0D55D844E51D7035E96DF94733
{
public:
// System.Int32 System.Reflection.BindingFlags::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(BindingFlags_tAAAB07D9AC588F0D55D844E51D7035E96DF94733, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
// UnityEngine.HeaderAttribute
struct HeaderAttribute_t9B431E6BA0524D46406D9C413D6A71CB5F2DD1AB : public PropertyAttribute_t4A352471DF625C56C811E27AC86B7E1CE6444052
{
public:
// System.String UnityEngine.HeaderAttribute::header
String_t* ___header_0;
public:
inline static int32_t get_offset_of_header_0() { return static_cast<int32_t>(offsetof(HeaderAttribute_t9B431E6BA0524D46406D9C413D6A71CB5F2DD1AB, ___header_0)); }
inline String_t* get_header_0() const { return ___header_0; }
inline String_t** get_address_of_header_0() { return &___header_0; }
inline void set_header_0(String_t* value)
{
___header_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___header_0), (void*)value);
}
};
// System.Runtime.CompilerServices.IteratorStateMachineAttribute
struct IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 : public StateMachineAttribute_tA6E77C77F821508E405473BA1C4C08A69FDA0AC3
{
public:
public:
};
// UnityEngine.RangeAttribute
struct RangeAttribute_t14A6532D68168764C15E7CF1FDABCD99CB32D0C5 : public PropertyAttribute_t4A352471DF625C56C811E27AC86B7E1CE6444052
{
public:
// System.Single UnityEngine.RangeAttribute::min
float ___min_0;
// System.Single UnityEngine.RangeAttribute::max
float ___max_1;
public:
inline static int32_t get_offset_of_min_0() { return static_cast<int32_t>(offsetof(RangeAttribute_t14A6532D68168764C15E7CF1FDABCD99CB32D0C5, ___min_0)); }
inline float get_min_0() const { return ___min_0; }
inline float* get_address_of_min_0() { return &___min_0; }
inline void set_min_0(float value)
{
___min_0 = value;
}
inline static int32_t get_offset_of_max_1() { return static_cast<int32_t>(offsetof(RangeAttribute_t14A6532D68168764C15E7CF1FDABCD99CB32D0C5, ___max_1)); }
inline float get_max_1() const { return ___max_1; }
inline float* get_address_of_max_1() { return &___max_1; }
inline void set_max_1(float value)
{
___max_1 = value;
}
};
// System.RuntimeTypeHandle
struct RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9
{
public:
// System.IntPtr System.RuntimeTypeHandle::value
intptr_t ___value_0;
public:
inline static int32_t get_offset_of_value_0() { return static_cast<int32_t>(offsetof(RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9, ___value_0)); }
inline intptr_t get_value_0() const { return ___value_0; }
inline intptr_t* get_address_of_value_0() { return &___value_0; }
inline void set_value_0(intptr_t value)
{
___value_0 = value;
}
};
// System.Diagnostics.DebuggableAttribute/DebuggingModes
struct DebuggingModes_t279D5B9C012ABA935887CB73C5A63A1F46AF08A8
{
public:
// System.Int32 System.Diagnostics.DebuggableAttribute/DebuggingModes::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(DebuggingModes_t279D5B9C012ABA935887CB73C5A63A1F46AF08A8, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
// System.Diagnostics.DebuggableAttribute
struct DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B : public Attribute_t037CA9D9F3B742C063DB364D2EEBBF9FC5772C71
{
public:
// System.Diagnostics.DebuggableAttribute/DebuggingModes System.Diagnostics.DebuggableAttribute::m_debuggingModes
int32_t ___m_debuggingModes_0;
public:
inline static int32_t get_offset_of_m_debuggingModes_0() { return static_cast<int32_t>(offsetof(DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B, ___m_debuggingModes_0)); }
inline int32_t get_m_debuggingModes_0() const { return ___m_debuggingModes_0; }
inline int32_t* get_address_of_m_debuggingModes_0() { return &___m_debuggingModes_0; }
inline void set_m_debuggingModes_0(int32_t value)
{
___m_debuggingModes_0 = value;
}
};
// System.Type
struct Type_t : public MemberInfo_t
{
public:
// System.RuntimeTypeHandle System.Type::_impl
RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 ____impl_9;
public:
inline static int32_t get_offset_of__impl_9() { return static_cast<int32_t>(offsetof(Type_t, ____impl_9)); }
inline RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 get__impl_9() const { return ____impl_9; }
inline RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 * get_address_of__impl_9() { return &____impl_9; }
inline void set__impl_9(RuntimeTypeHandle_tC33965ADA3E041E0C94AF05E5CB527B56482CEF9 value)
{
____impl_9 = value;
}
};
struct Type_t_StaticFields
{
public:
// System.Reflection.MemberFilter System.Type::FilterAttribute
MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * ___FilterAttribute_0;
// System.Reflection.MemberFilter System.Type::FilterName
MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * ___FilterName_1;
// System.Reflection.MemberFilter System.Type::FilterNameIgnoreCase
MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * ___FilterNameIgnoreCase_2;
// System.Object System.Type::Missing
RuntimeObject * ___Missing_3;
// System.Char System.Type::Delimiter
Il2CppChar ___Delimiter_4;
// System.Type[] System.Type::EmptyTypes
TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755* ___EmptyTypes_5;
// System.Reflection.Binder System.Type::defaultBinder
Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 * ___defaultBinder_6;
public:
inline static int32_t get_offset_of_FilterAttribute_0() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterAttribute_0)); }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * get_FilterAttribute_0() const { return ___FilterAttribute_0; }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 ** get_address_of_FilterAttribute_0() { return &___FilterAttribute_0; }
inline void set_FilterAttribute_0(MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * value)
{
___FilterAttribute_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FilterAttribute_0), (void*)value);
}
inline static int32_t get_offset_of_FilterName_1() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterName_1)); }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * get_FilterName_1() const { return ___FilterName_1; }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 ** get_address_of_FilterName_1() { return &___FilterName_1; }
inline void set_FilterName_1(MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * value)
{
___FilterName_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FilterName_1), (void*)value);
}
inline static int32_t get_offset_of_FilterNameIgnoreCase_2() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterNameIgnoreCase_2)); }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * get_FilterNameIgnoreCase_2() const { return ___FilterNameIgnoreCase_2; }
inline MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 ** get_address_of_FilterNameIgnoreCase_2() { return &___FilterNameIgnoreCase_2; }
inline void set_FilterNameIgnoreCase_2(MemberFilter_t48D0AA10105D186AF42428FA532D4B4332CF8B81 * value)
{
___FilterNameIgnoreCase_2 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FilterNameIgnoreCase_2), (void*)value);
}
inline static int32_t get_offset_of_Missing_3() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Missing_3)); }
inline RuntimeObject * get_Missing_3() const { return ___Missing_3; }
inline RuntimeObject ** get_address_of_Missing_3() { return &___Missing_3; }
inline void set_Missing_3(RuntimeObject * value)
{
___Missing_3 = value;
Il2CppCodeGenWriteBarrier((void**)(&___Missing_3), (void*)value);
}
inline static int32_t get_offset_of_Delimiter_4() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Delimiter_4)); }
inline Il2CppChar get_Delimiter_4() const { return ___Delimiter_4; }
inline Il2CppChar* get_address_of_Delimiter_4() { return &___Delimiter_4; }
inline void set_Delimiter_4(Il2CppChar value)
{
___Delimiter_4 = value;
}
inline static int32_t get_offset_of_EmptyTypes_5() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___EmptyTypes_5)); }
inline TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755* get_EmptyTypes_5() const { return ___EmptyTypes_5; }
inline TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755** get_address_of_EmptyTypes_5() { return &___EmptyTypes_5; }
inline void set_EmptyTypes_5(TypeU5BU5D_t85B10489E46F06CEC7C4B1CCBD0E01FAB6649755* value)
{
___EmptyTypes_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___EmptyTypes_5), (void*)value);
}
inline static int32_t get_offset_of_defaultBinder_6() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___defaultBinder_6)); }
inline Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 * get_defaultBinder_6() const { return ___defaultBinder_6; }
inline Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 ** get_address_of_defaultBinder_6() { return &___defaultBinder_6; }
inline void set_defaultBinder_6(Binder_t2BEE27FD84737D1E79BC47FD67F6D3DD2F2DDA30 * value)
{
___defaultBinder_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___defaultBinder_6), (void*)value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// System.Void System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void CompilationRelaxationsAttribute__ctor_mAC3079EBC4EEAB474EED8208EF95DB39C922333B (CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF * __this, int32_t ___relaxations0, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RuntimeCompatibilityAttribute__ctor_m551DDF1438CE97A984571949723F30F44CF7317C (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * __this, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::set_WrapNonExceptionThrows(System.Boolean)
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void RuntimeCompatibilityAttribute_set_WrapNonExceptionThrows_m8562196F90F3EBCEC23B5708EE0332842883C490_inline (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * __this, bool ___value0, const RuntimeMethod* method);
// System.Void System.Diagnostics.DebuggableAttribute::.ctor(System.Diagnostics.DebuggableAttribute/DebuggingModes)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void DebuggableAttribute__ctor_m7FF445C8435494A4847123A668D889E692E55550 (DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B * __this, int32_t ___modes0, const RuntimeMethod* method);
// System.Void UnityEngine.HeaderAttribute::.ctor(System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void HeaderAttribute__ctor_m601319E0BCE8C44A9E79B2C0ABAAD0FEF46A9F1E (HeaderAttribute_t9B431E6BA0524D46406D9C413D6A71CB5F2DD1AB * __this, String_t* ___header0, const RuntimeMethod* method);
// System.Void UnityEngine.RangeAttribute::.ctor(System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void RangeAttribute__ctor_mC74D39A9F20DD2A0D4174F05785ABE4F0DAEF000 (RangeAttribute_t14A6532D68168764C15E7CF1FDABCD99CB32D0C5 * __this, float ___min0, float ___max1, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(System.Type)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void IteratorStateMachineAttribute__ctor_m019CD62C4E5301F55EDF4723107B608AE8F12481 (IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 * __this, Type_t * ___stateMachineType0, const RuntimeMethod* method);
// System.Void System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35 (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * __this, const RuntimeMethod* method);
// System.Void System.Diagnostics.DebuggerHiddenAttribute::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3 (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * __this, const RuntimeMethod* method);
static void AssemblyU2DCSharp_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF * tmp = (CompilationRelaxationsAttribute_t661FDDC06629BDA607A42BD660944F039FE03AFF *)cache->attributes[0];
CompilationRelaxationsAttribute__ctor_mAC3079EBC4EEAB474EED8208EF95DB39C922333B(tmp, 8LL, NULL);
}
{
RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * tmp = (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 *)cache->attributes[1];
RuntimeCompatibilityAttribute__ctor_m551DDF1438CE97A984571949723F30F44CF7317C(tmp, NULL);
RuntimeCompatibilityAttribute_set_WrapNonExceptionThrows_m8562196F90F3EBCEC23B5708EE0332842883C490_inline(tmp, true, NULL);
}
{
DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B * tmp = (DebuggableAttribute_tA8054EBD0FC7511695D494B690B5771658E3191B *)cache->attributes[2];
DebuggableAttribute__ctor_m7FF445C8435494A4847123A668D889E692E55550(tmp, 2LL, NULL);
}
}
static void Audio_t2951637A4DCDD11F9799F68B468E9D49B004953F_CustomAttributesCacheGenerator_musicVolumne(CustomAttributesCache* cache)
{
{
HeaderAttribute_t9B431E6BA0524D46406D9C413D6A71CB5F2DD1AB * tmp = (HeaderAttribute_t9B431E6BA0524D46406D9C413D6A71CB5F2DD1AB *)cache->attributes[0];
HeaderAttribute__ctor_m601319E0BCE8C44A9E79B2C0ABAAD0FEF46A9F1E(tmp, il2cpp_codegen_string_new_wrapper("\x4D\x61\x69\x6E\x20\x53\x65\x74\x74\x69\x6E\x67\x73\x3A"), NULL);
}
{
RangeAttribute_t14A6532D68168764C15E7CF1FDABCD99CB32D0C5 * tmp = (RangeAttribute_t14A6532D68168764C15E7CF1FDABCD99CB32D0C5 *)cache->attributes[1];
RangeAttribute__ctor_mC74D39A9F20DD2A0D4174F05785ABE4F0DAEF000(tmp, 0.0f, 1.0f, NULL);
}
}
static void Audio_t2951637A4DCDD11F9799F68B468E9D49B004953F_CustomAttributesCacheGenerator_sfxVolumn(CustomAttributesCache* cache)
{
{
RangeAttribute_t14A6532D68168764C15E7CF1FDABCD99CB32D0C5 * tmp = (RangeAttribute_t14A6532D68168764C15E7CF1FDABCD99CB32D0C5 *)cache->attributes[0];
RangeAttribute__ctor_mC74D39A9F20DD2A0D4174F05785ABE4F0DAEF000(tmp, 0.0f, 1.0f, NULL);
}
}
static void Audio_t2951637A4DCDD11F9799F68B468E9D49B004953F_CustomAttributesCacheGenerator_shooting(CustomAttributesCache* cache)
{
{
HeaderAttribute_t9B431E6BA0524D46406D9C413D6A71CB5F2DD1AB * tmp = (HeaderAttribute_t9B431E6BA0524D46406D9C413D6A71CB5F2DD1AB *)cache->attributes[0];
HeaderAttribute__ctor_m601319E0BCE8C44A9E79B2C0ABAAD0FEF46A9F1E(tmp, il2cpp_codegen_string_new_wrapper("\x47\x61\x6D\x65\x20\x53\x6F\x75\x6E\x64\x73\x20\x41\x6E\x64\x20\x4D\x75\x73\x69\x63\x3A"), NULL);
}
}
static void GameManager_t9013B33302D2B40A51D0E8059DEE0DC180218AA1_CustomAttributesCacheGenerator_GameManager_TimeCountDown_mEDFC73B7E6395B72C8C302FE406444A3C645C265(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 * tmp = (IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 *)cache->attributes[0];
IteratorStateMachineAttribute__ctor_m019CD62C4E5301F55EDF4723107B608AE8F12481(tmp, il2cpp_codegen_type_get_object(U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_0_0_0_var), NULL);
}
}
static void GameManager_t9013B33302D2B40A51D0E8059DEE0DC180218AA1_CustomAttributesCacheGenerator_GameManager_GameSpawn_m92BFED24CBE86D76043D631C20DB49E71D7FF511(CustomAttributesCache* cache)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_0_0_0_var);
s_Il2CppMethodInitialized = true;
}
{
IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 * tmp = (IteratorStateMachineAttribute_t6C72F3EC15FB34D08D47727AA7A86AB7FEA27830 *)cache->attributes[0];
IteratorStateMachineAttribute__ctor_m019CD62C4E5301F55EDF4723107B608AE8F12481(tmp, il2cpp_codegen_type_get_object(U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_0_0_0_var), NULL);
}
}
static void U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15__ctor_m25B4687F206FE84C08C4E97BC91F240A6104F980(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15_System_IDisposable_Dispose_mC5E2954F068089A0150A985754E748C665BF9410(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_mB89FE22CFB02DAF4962E149B56F5F0726EE153CA(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15_System_Collections_IEnumerator_Reset_mB268B7D59249D9ECC48FC1091ED0D2A0A14307E8(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15_System_Collections_IEnumerator_get_Current_mC14A95331F4DCB73E04C331A8F60115BCFEA5EA7(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator(CustomAttributesCache* cache)
{
{
CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C * tmp = (CompilerGeneratedAttribute_t39106AB982658D7A94C27DEF3C48DB2F5F7CD75C *)cache->attributes[0];
CompilerGeneratedAttribute__ctor_m9DC3E4E2DA76FE93948D44199213E2E924DCBE35(tmp, NULL);
}
}
static void U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16__ctor_mAD5EA505649542DE9D0EC8C663C2EA9205F72C87(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16_System_IDisposable_Dispose_m00AD25698777ED5BAE36C3F52E389D535DCF2CBB(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_mCDBDC3048B29091F93704C4C529E80030C071AAA(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16_System_Collections_IEnumerator_Reset_m5286E008F60DB1651D79BC537CB166A96764C528(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
static void U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16_System_Collections_IEnumerator_get_Current_m5F378E1E62A71ECC23F749DA7C0DC736FC9825D3(CustomAttributesCache* cache)
{
{
DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 * tmp = (DebuggerHiddenAttribute_tD84728997C009D6F540FB29D88F032350E046A88 *)cache->attributes[0];
DebuggerHiddenAttribute__ctor_mB40799BB5DAFE439BEFE895836CF792B8DBEA7F3(tmp, NULL);
}
}
IL2CPP_EXTERN_C const CustomAttributesCacheGenerator g_AssemblyU2DCSharp_AttributeGenerators[];
const CustomAttributesCacheGenerator g_AssemblyU2DCSharp_AttributeGenerators[18] =
{
U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator,
U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator,
Audio_t2951637A4DCDD11F9799F68B468E9D49B004953F_CustomAttributesCacheGenerator_musicVolumne,
Audio_t2951637A4DCDD11F9799F68B468E9D49B004953F_CustomAttributesCacheGenerator_sfxVolumn,
Audio_t2951637A4DCDD11F9799F68B468E9D49B004953F_CustomAttributesCacheGenerator_shooting,
GameManager_t9013B33302D2B40A51D0E8059DEE0DC180218AA1_CustomAttributesCacheGenerator_GameManager_TimeCountDown_mEDFC73B7E6395B72C8C302FE406444A3C645C265,
GameManager_t9013B33302D2B40A51D0E8059DEE0DC180218AA1_CustomAttributesCacheGenerator_GameManager_GameSpawn_m92BFED24CBE86D76043D631C20DB49E71D7FF511,
U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15__ctor_m25B4687F206FE84C08C4E97BC91F240A6104F980,
U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15_System_IDisposable_Dispose_mC5E2954F068089A0150A985754E748C665BF9410,
U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_mB89FE22CFB02DAF4962E149B56F5F0726EE153CA,
U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15_System_Collections_IEnumerator_Reset_mB268B7D59249D9ECC48FC1091ED0D2A0A14307E8,
U3CTimeCountDownU3Ed__15_tE3DB2A5BB1BFE784177FFA481667F8A6E44EDF23_CustomAttributesCacheGenerator_U3CTimeCountDownU3Ed__15_System_Collections_IEnumerator_get_Current_mC14A95331F4DCB73E04C331A8F60115BCFEA5EA7,
U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16__ctor_mAD5EA505649542DE9D0EC8C663C2EA9205F72C87,
U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16_System_IDisposable_Dispose_m00AD25698777ED5BAE36C3F52E389D535DCF2CBB,
U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_mCDBDC3048B29091F93704C4C529E80030C071AAA,
U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16_System_Collections_IEnumerator_Reset_m5286E008F60DB1651D79BC537CB166A96764C528,
U3CGameSpawnU3Ed__16_t46EEF450C452377ED0AEE99AE837E4B8C95A6401_CustomAttributesCacheGenerator_U3CGameSpawnU3Ed__16_System_Collections_IEnumerator_get_Current_m5F378E1E62A71ECC23F749DA7C0DC736FC9825D3,
AssemblyU2DCSharp_CustomAttributesCacheGenerator,
};
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void RuntimeCompatibilityAttribute_set_WrapNonExceptionThrows_m8562196F90F3EBCEC23B5708EE0332842883C490_inline (RuntimeCompatibilityAttribute_tFF99AB2963098F9CBCD47A20D9FD3D51C17C1C80 * __this, bool ___value0, const RuntimeMethod* method)
{
{
bool L_0 = ___value0;
__this->set_m_wrapNonExceptionThrows_0(L_0);
return;
}
}
| [
"phunghocong@gmai.com"
] | phunghocong@gmai.com |
668fb7878605745fb407174d3ce55eb8376d7b07 | 1371149539079f7ce890f4450131f4b651697d8c | /gateway/S_message.h | c81e30e2496220721fc8ecf3c1af9da533f13770 | [] | no_license | shred444/homesensornetwork | 3aa9e8de24c3258a09ad8d118a70da4238978f3a | 365da1edc33314b1cb651a7e504806df30673c20 | refs/heads/master | 2021-01-10T03:49:45.651124 | 2016-02-18T02:44:45 | 2016-02-18T02:44:45 | 51,885,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 730 | h | /*
Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
*/
#ifndef __S_MESSAGE_H__
#define __S_MESSAGE_H__
// STL headers
// C headers
// Framework headers
// Library headers
// Project headers
/**
* Sensor message (type 'S')
*/
struct S_message
{
uint16_t temp_reading;
uint16_t voltage_reading;
uint16_t humidity_reading;
uint8_t lost_packets;
uint8_t reserved;
static char buffer[];
S_message(void): temp_reading(0), voltage_reading(0) {}
char* toString(void);
};
#endif // __S_MESSAGE_H__
// vim:cin:ai:sts=2 sw=2 ft=cpp
| [
"shred444@gmail.com"
] | shred444@gmail.com |
cc18754473a4909d8ee3752be1bc3d6e56fe1e1a | 4ffa82dfd1b6cf9c34c16ab0e70d292cc2615502 | /Mega_Man_Requiem/Motor2D/j1Fonts.h | 60799ebd9d159820fe4f371c7f9cbeb8b9b06946 | [] | no_license | lFreecss/Mega-Man-Requiem | 1e0fb150e1576d0554e397309b972c79fa983558 | 4c38971991366812e955e5578d486485cc742839 | refs/heads/master | 2021-08-30T11:50:15.549110 | 2017-12-17T20:40:00 | 2017-12-17T20:40:00 | 108,882,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | h | #ifndef __j1FONTS_H__
#define __j1FONTS_H__
#include "j1Module.h"
#include "SDL\include\SDL_pixels.h"
#define DEFAULT_FONT "fonts/Mega_Man_2.ttf"
#define DEFAULT_FONT_SIZE 12
struct SDL_Texture;
struct _TTF_Font;
class j1Fonts : public j1Module
{
public:
j1Fonts();
// Destructor
virtual ~j1Fonts();
// Called before render is available
bool Awake(pugi::xml_node&);
// Called before quitting
bool CleanUp();
// Load Font
_TTF_Font* const Load(const char* path, int size = 12);
// Create a surface from text
SDL_Texture* Print(const char* text, SDL_Color color = { 255, 255, 255, 255 }, _TTF_Font* font = NULL);
bool CalcSize(const char* text, int& width, int& height, _TTF_Font* font = NULL) const;
public:
p2List<_TTF_Font*> fonts;
_TTF_Font* default;
};
#endif // __j1FONTS_H__ | [
"d.valdiviamartinez@gmail.com"
] | d.valdiviamartinez@gmail.com |
62d90597285e2635e57a6b67874f02a740a05d98 | e6148031b471d952dbf1615d05eb47013591216f | /code/20190323/K_zayin.cpp | d6aa19034e0065bab177090b0d3fb27d490e96d6 | [] | no_license | Dafenghh/Training_Summary | 1bdc2a3efaf5dd8e71f9c4a566c4245727769c57 | c38f8d2062a87ead98cf65f3255a5960351f6002 | refs/heads/master | 2021-06-03T11:49:03.488574 | 2020-02-09T16:19:53 | 2020-02-09T16:19:53 | 144,736,350 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | #include<bits/stdc++.h>
#define maxn 10005
using namespace std;
int n,m;
int pos[maxn];
int d[maxn],D[maxn];
queue<int> q;
bool cmpd(int i,int j) {
return d[i]<d[j];
}
bool cmpD(int i,int j) {
return D[i]>D[j];
}
int main() {
scanf("%d%d",&n,&m);
while (m--) {
int u,v;
scanf("%d%d",&u,&v);
++d[u],++d[v];
}
for (int i=0;i<n;++i) pos[i]=i;
sort(pos,pos+n,cmpd);
// for (int i=0;i<n;++i) cout<<d[i]<<" "; cout<<endl;
int ans=n,t=2*n-2;
for (int k=0;k<n;++k) {
int i=pos[k];
D[i]=min(t-(n-k-1),d[i]);
if (d[i]==D[i]) --ans;
t-=D[i];
}
printf("%d\n%d %d\n",ans,n,n-1);
sort(pos,pos+n,cmpD);
for (int k=0;k<n;++k) {
int i=pos[k];
if (k) {
assert(q.size());
cout<<i<<" "<<q.front()<<endl;
q.pop();
}
for (int j=1;j<=D[i]-(bool)k;++j)
q.push(i);
}
return 0;
}
| [
"xudafeng88@qq.com"
] | xudafeng88@qq.com |
e11351b3d2a0d4c93edac27afa14279615e54bad | b123b9b5241f88acc5715b85311ae0546d6856d3 | /30_days_tutorial/day_01_data_types.cpp | aa5bb485f0aa0b7334d93b783664cd4542843715 | [
"MIT"
] | permissive | clebsonc/hackerrank | de0a599611938ee8b0e200668b1613adee94dfac | 48076b3e294a2b61b2879b9b06a641b1cca86f44 | refs/heads/master | 2020-09-17T11:41:07.363483 | 2018-10-02T23:14:25 | 2018-10-02T23:14:25 | 67,635,736 | 0 | 0 | null | 2017-03-25T18:03:15 | 2016-09-07T19:09:08 | C++ | UTF-8 | C++ | false | false | 453 | cpp | #include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
cout << setprecision(1) << fixed;
int a=0;
float b=0.0;
string c;
cin >> a;
cin >> b;
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
getline(cin, c);
cout << a+i << "\n";
cout << d+b << "\n";
cout << s.append(c);
return 0;
}
| [
"clebsondm@gmail.com"
] | clebsondm@gmail.com |
965d58b00f7d06ed8fcbf7a27cc8d7970ea4e980 | e90bb6a20665f2b875e047f12bd05839c2396c5d | /blasius_laminar_github/7.6/uniform/functionObjects/functionObjectProperties | e0863d863bb6bda7e0ea0131bdad395f895a7cc4 | [] | no_license | fluidko/laminar_BL_OpenFOAM | 5dabd283090720211ef819367bd92109df068105 | c3e0bf11355d723ed47a3712e121d48edb4e8c92 | refs/heads/master | 2023-03-16T14:30:33.059718 | 2020-06-16T01:59:58 | 2020-06-16T01:59:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 897 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1906 |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "7.6/uniform/functionObjects";
object functionObjectProperties;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// ************************************************************************* //
| [
"tong011@e.ntu.edu.sg"
] | tong011@e.ntu.edu.sg | |
eb48f5c505238ab6a694cbdd3703481b79027aed | 4e44e0eb828c8501999d6e4101c8335d67ddfd70 | /Crimsonite/Crimsonite/source/render/FrameBuffer.h | 7b5e49a72b4e8ead77af1f909409125bbeb2b48a | [
"MIT"
] | permissive | Fletcher-Morris/Crimsonite-Engine | 2cd846285bfba4105db9c3d4deb629a7ce66d1c1 | e07a8183e50def61f1ff4e8dc83c3a72e78d0699 | refs/heads/master | 2021-03-06T01:04:24.836720 | 2019-05-24T08:07:04 | 2019-05-24T08:07:04 | 246,167,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 700 | h | #pragma once
#include <string>
class Texture;
class FrameBuffer
{
public:
FrameBuffer() {};
// The ID of this FrameBuffer.
unsigned int FrameBufferId = 0;
// Set the linked Texture.
void SetTexture(Texture * _tex) { m_linkedTex = _tex; }
Texture * GetLinkedTexture() { return m_linkedTex; }
// The ID of the linked depth buffer.
unsigned int DepthBufferId;
void SetName(std::string _name) { m_name = _name; }
std::string GetName() { return m_name; }
void Bind();
void Unbind() {};
void Resize(int _width, int _height);
int Width() { return m_width; }
int Height() { return m_height; }
private:
Texture * m_linkedTex;
std::string m_name;
int m_width;
int m_height;
}; | [
"odmoandtheboy@gmail.com"
] | odmoandtheboy@gmail.com |
652b79eba0641f33273a024f9512e5be3fcafc6b | 85a7482cbe28d780b7fb465dafb0159c028ab93d | /Serial/huffmanUtil.cpp | 9bd81e74a44daa8bc4cd446b06dcd30ede2a85e7 | [] | no_license | namitapradhan26/GPUProject | 906fdffc57900ed4cff56267d1e05836a198eebd | d5ccb499cf681bca501deef3962a88589ede3a85 | refs/heads/master | 2022-04-11T05:12:11.361438 | 2020-03-26T01:23:55 | 2020-03-26T01:23:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | #include "huffmanUtil.h"
#include <stdio.h>
using namespace std;
bool confirmOverwrite(string filename) {
if (!fileExists(filename)) {
return true;
} else {
char option;
cout << "File already exists. Overwrite ? (y/n): ";
cin >> option;
if(option == 'y'|| option == 'Y') return true;
return false;
}
}
int fileSize(string filename) {
ifstream input;
input.open(filename.c_str(), ifstream::binary);
input.seekg(0, ifstream::end);
return (int) input.tellg();
}
string readEntireFileText(string filename) {
ifstream input;
input.open(filename.c_str());
return readEntireFileText(input);
}
| [
"apatil@bender.engr.ucr.edu"
] | apatil@bender.engr.ucr.edu |
72fcf0d662662d8ab7c4770deb98634b78a46abf | 69791b4d2cd92b0f3b2b7dddbaeb5fc63c245f7f | /include/ThreadPool.h | 5c3fac174cd6c654131e8bf3b2cc60e0e60aff11 | [] | no_license | checkking/http | 891c339540fa8b528bd4d9626bec6d0f9d32a4eb | c129a7ad0fa1992f79d3d55f34ed0182ef2740c1 | refs/heads/master | 2021-01-15T23:53:31.816175 | 2016-02-23T10:42:58 | 2016-02-23T10:42:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | h | #pragma once
#include <atomic>
#include <condition_variable>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
namespace Yam {
namespace Http {
class ThreadPool {
public:
using Work = std::function<void()>;
ThreadPool(int capacity);
~ThreadPool();
std::future<void> Post(Work);
std::size_t GetThreadCount() const;
private:
friend class Worker;
struct WorkContext {
WorkContext(Work&& w) : _work(std::move(w)) {}
std::promise<void> _promise;
Work _work;
};
std::vector<std::unique_ptr<std::thread>> _threads;
std::queue<std::unique_ptr<WorkContext>> _pending;
std::mutex _mutex;
std::condition_variable _workerAlarm;
std::atomic_bool _stop{false};
};
inline std::size_t ThreadPool::GetThreadCount() const {
return _threads.size();
}
} // namespace Http
} // namespace Yam
| [
"ymarcov@gmail.com"
] | ymarcov@gmail.com |
92368ca8b69d55ea5d906cf8b27ac2b1dd66efbe | 7926b330515aa573a810ed9cb298c3de93b007f9 | /陈磊贡献/桥.cpp | 0262888a9f9c819f221489722c3a9524472ee71c | [] | no_license | laijirong/NOIP-C-files | 6f1dceae364e41625f3a4ef0e3897ef1c731d0fe | 951af9aa0b287a8c169b6ba03d618ba8ba2e0ae2 | refs/heads/master | 2020-04-20T11:38:00.485181 | 2019-06-16T03:00:55 | 2019-06-16T03:00:55 | 168,822,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | cpp | #include<cstdio>
using namespace std;
int n,m,zy,red;
int used[2010],map[2010][2010],pos[2010][2010];
struct ss
{
int dfn,low;
} Tarjan[2010];
void search(int a,int b)
{
zy++;
Tarjan[a].dfn=Tarjan[a].low=zy;
for(int i=1;i<=n;i++)
if(map[a][i]!=0&&i!=b)
{
if(used[i]==0)
{
pos[a][i]=1;
used[i]=1;
search(i,a);
if(Tarjan[i].low>Tarjan[a].dfn)
map[a][i]=10;
}
if(used[i]>0&&Tarjan[i].low<Tarjan[a].low)
Tarjan[a].low=Tarjan[i].low;
if(pos[a][i]==1) used[i]=-1;
}
}
int main()
{
int x,y;
freopen("10313.in","r",stdin);
freopen("10313.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
map[x][y]=1;
map[y][x]=1;
}
used[1]=1;
search(1,0);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(map[i][j]==10)
{
map[j][i]=1;
red++;
}
printf("%d\n",red);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(map[i][j]==10)
printf("%d %d\n",i,j);
fclose(stdin);
fclose(stdout);
return 0;
}
| [
"laijirong@outlook.com"
] | laijirong@outlook.com |
c0da411f61ed1758776fd5033619581b1b94b795 | 4457206d4f05e3bdc1f60f35f3e7b34eaa5c7ab1 | /Tracker/Struck/Tracker.h | a211bc2ecc1264480dfbe1af6df809e4a70f9089 | [] | no_license | huzexi/MTM | bf155fd02e48ae89bc0c39d8e6da8d9c15b02f9c | a0af9671406ccfd343fa3996c987fd335ff68346 | refs/heads/master | 2022-06-26T14:57:25.013469 | 2018-10-24T05:28:49 | 2018-10-24T05:28:49 | 154,443,524 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,747 | h | /*
* Struck: Structured Output Tracking with Kernels
*
* Code to accompany the paper:
* Struck: Structured Output Tracking with Kernels
* Sam Hare, Amir Saffari, Philip H. S. Torr
* International Conference on Computer Vision (ICCV), 2011
*
* Copyright (C) 2011 Sam Hare, Oxford Brookes University, Oxford, UK
*
* This file is part of Struck.
*
* Struck is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Struck is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Struck. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef TRACKER_H
#define TRACKER_H
#include "Rect.h"
#include "Features.h"
#include "Kernels.h"
#include "LaRank.h"
#include <vector>
#include <Eigen/Core>
#include <opencv/cv.h>
class Config;
class Features;
class Kernel;
class LaRank;
class ImageRep;
class UpdateInfo
{
public:
UpdateInfo(bool need_update, ImageRep* update_image)
: NeedUpdate(need_update),
UpdateImage(update_image)
{
}
bool NeedUpdate;
ImageRep* UpdateImage;
};
class Tracker
{
public:
Tracker(const Config& conf);
~Tracker();
Tracker(const Tracker& other)
: m_config(other.m_config),
m_initialised(other.m_initialised),
m_pLearner(new LaRank(*(other.m_pLearner))),
m_bb(other.m_bb),
m_debugImage(other.m_debugImage),
m_needsIntegralImage(other.m_needsIntegralImage),
m_needsIntegralHist(other.m_needsIntegralHist)
{
for (Features* t:other.m_features)
{
m_features.push_back(t->clone());
}
for (Kernel* t:other.m_kernels)
{
m_kernels.push_back(t->clone());
}
}
void Initialise(const cv::Mat& frame, FloatRect bb);
void Reset();
void Track(const cv::Mat& frame);
void Debug();
void UpdateLearner(const ImageRep& image);
inline const FloatRect& GetBB() const { return m_bb; }
inline bool IsInitialised() const { return m_initialised; }
const Config& m_config;
FloatRect m_bb;
// Added function
UpdateInfo TrackWithoutUpdate(const cv::Mat& frame);
Tracker* clone();
private:
bool m_initialised;
std::vector<Features*> m_features;
std::vector<Kernel*> m_kernels;
LaRank* m_pLearner;
cv::Mat m_debugImage;
bool m_needsIntegralImage;
bool m_needsIntegralHist;
void UpdateDebugImage(const std::vector<FloatRect>& samples, const FloatRect& centre, const std::vector<double>& scores);
};
#endif
| [
"44811199+huzexi@users.noreply.github.com"
] | 44811199+huzexi@users.noreply.github.com |
fc5ff8f730a85abb682fe4a4ef8afe6afe3beda6 | 89966523ae85f02e2bcc0b33d0c2f63f736b3377 | /milk.cpp | 4fd168c3732ee5057d043ec6e9fdbe46d670b40f | [] | no_license | dibyatanoy/Competitive_Programming | fb19382719ed60156f1501ffe485d8fb5b637f86 | a2818f96bcdfc2da577415b2dc02f29acd0c5b2b | refs/heads/master | 2021-01-15T15:31:02.471777 | 2016-07-20T02:46:12 | 2016-07-20T02:46:12 | 44,463,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cpp | /*
ID: dibyapo2
LANG: C++
TASK: milk
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <fstream>
using namespace std;
struct data{
int rate;
int amount;
bool operator <(const data &p)const{
return rate<p.rate;
}
};
int main(){
freopen("milk.in","r",stdin);
freopen("milk.out","w",stdout);
int N,M,i;
vector <data> milk;
scanf("%d %d",&N,&M);
for(i=0;i<M;i++){
int r,a;
scanf("%d %d",&r,&a);
data temp;
temp.rate=r;temp.amount=a;
milk.push_back(temp);
}
sort(milk.begin(),milk.end());
int cost=0;
for(i=0;i<M;i++){
if(milk[i].amount<=N){
cost+=milk[i].rate*milk[i].amount;
N-=milk[i].amount;
}else {
cost+=milk[i].rate*N;
break;
}
}
printf("%d\n",cost);
return 0;
}
/** AC!!! **/ | [
"noreply@github.com"
] | noreply@github.com |
a7b809e20abc170e84f3e1b2dea8d44f332bf0f3 | 03f037d0f6371856ede958f0c9d02771d5402baf | /graphics/VTK-7.0.0/Interaction/Widgets/vtkPolyLineWidget.cxx | c7e7b703b64ca13caf919a7f94e60c1e1bf92821 | [
"BSD-3-Clause"
] | permissive | hlzz/dotfiles | b22dc2dc5a9086353ed6dfeee884f7f0a9ddb1eb | 0591f71230c919c827ba569099eb3b75897e163e | refs/heads/master | 2021-01-10T10:06:31.018179 | 2016-09-27T08:13:18 | 2016-09-27T08:13:18 | 55,040,954 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,015 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: vtkPolyLineWidget.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPolyLineWidget.h"
#include "vtkCallbackCommand.h"
#include "vtkCommand.h"
#include "vtkEvent.h"
#include "vtkObjectFactory.h"
#include "vtkPolyLineRepresentation.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkWidgetCallbackMapper.h"
#include "vtkWidgetEvent.h"
#include "vtkWidgetEventTranslator.h"
vtkStandardNewMacro(vtkPolyLineWidget);
//----------------------------------------------------------------------------
vtkPolyLineWidget::vtkPolyLineWidget()
{
this->WidgetState = vtkPolyLineWidget::Start;
this->ManagesCursor = 1;
// Define widget events
this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonPressEvent,
vtkWidgetEvent::Select,
this, vtkPolyLineWidget::SelectAction);
this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent,
vtkWidgetEvent::EndSelect,
this, vtkPolyLineWidget::EndSelectAction);
this->CallbackMapper->SetCallbackMethod(vtkCommand::MiddleButtonPressEvent,
vtkWidgetEvent::Translate,
this, vtkPolyLineWidget::TranslateAction);
this->CallbackMapper->SetCallbackMethod(vtkCommand::MiddleButtonReleaseEvent,
vtkWidgetEvent::EndTranslate,
this, vtkPolyLineWidget::EndSelectAction);
this->CallbackMapper->SetCallbackMethod(vtkCommand::RightButtonPressEvent,
vtkWidgetEvent::Scale,
this, vtkPolyLineWidget::ScaleAction);
this->CallbackMapper->SetCallbackMethod(vtkCommand::RightButtonReleaseEvent,
vtkWidgetEvent::EndScale,
this, vtkPolyLineWidget::EndSelectAction);
this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent,
vtkWidgetEvent::Move,
this, vtkPolyLineWidget::MoveAction);
}
//----------------------------------------------------------------------------
vtkPolyLineWidget::~vtkPolyLineWidget()
{
}
//----------------------------------------------------------------------
void vtkPolyLineWidget::SelectAction(vtkAbstractWidget *w)
{
// We are in a static method, cast to ourself
vtkPolyLineWidget *self = vtkPolyLineWidget::SafeDownCast(w);
// Get the event position
int X = self->Interactor->GetEventPosition()[0];
int Y = self->Interactor->GetEventPosition()[1];
// Okay, make sure that the pick is in the current renderer
if ( !self->CurrentRenderer ||
!self->CurrentRenderer->IsInViewport(X,Y) )
{
self->WidgetState = vtkPolyLineWidget::Start;
return;
}
// Begin the widget interaction which has the side effect of setting the
// interaction state.
double e[2];
e[0] = static_cast<double>(X);
e[1] = static_cast<double>(Y);
self->WidgetRep->StartWidgetInteraction(e);
int interactionState = self->WidgetRep->GetInteractionState();
if ( interactionState == vtkPolyLineRepresentation::Outside )
{
return;
}
// We are definitely selected
self->WidgetState = vtkPolyLineWidget::Active;
self->GrabFocus(self->EventCallbackCommand);
if (interactionState == vtkPolyLineRepresentation::OnLine &&
self->Interactor->GetControlKey())
{
// Add point.
reinterpret_cast<vtkPolyLineRepresentation*>(self->WidgetRep)->
SetInteractionState(vtkPolyLineRepresentation::Inserting);
}
else if (interactionState == vtkPolyLineRepresentation::OnHandle &&
self->Interactor->GetShiftKey())
{
// remove point.
reinterpret_cast<vtkPolyLineRepresentation*>(self->WidgetRep)->
SetInteractionState(vtkPolyLineRepresentation::Erasing);
}
else
{
reinterpret_cast<vtkPolyLineRepresentation*>(self->WidgetRep)->
SetInteractionState(vtkPolyLineRepresentation::Moving);
}
// start the interaction
self->EventCallbackCommand->SetAbortFlag(1);
self->StartInteraction();
self->InvokeEvent(vtkCommand::StartInteractionEvent,NULL);
self->Render();
}
//----------------------------------------------------------------------
void vtkPolyLineWidget::TranslateAction(vtkAbstractWidget *w)
{
// Not sure this should be any different that SelectAction
vtkPolyLineWidget::SelectAction(w);
}
//----------------------------------------------------------------------
void vtkPolyLineWidget::ScaleAction(vtkAbstractWidget *w)
{
// We are in a static method, cast to ourself
vtkPolyLineWidget *self = reinterpret_cast<vtkPolyLineWidget*>(w);
// Get the event position
int X = self->Interactor->GetEventPosition()[0];
int Y = self->Interactor->GetEventPosition()[1];
// Okay, make sure that the pick is in the current renderer
if ( !self->CurrentRenderer ||
!self->CurrentRenderer->IsInViewport(X,Y) )
{
self->WidgetState = vtkPolyLineWidget::Start;
return;
}
// Begin the widget interaction which has the side effect of setting the
// interaction state.
double e[2];
e[0] = static_cast<double>(X);
e[1] = static_cast<double>(Y);
self->WidgetRep->StartWidgetInteraction(e);
int interactionState = self->WidgetRep->GetInteractionState();
if ( interactionState == vtkPolyLineRepresentation::Outside )
{
return;
}
// We are definitely selected
self->WidgetState = vtkPolyLineWidget::Active;
self->GrabFocus(self->EventCallbackCommand);
//Scale
reinterpret_cast<vtkPolyLineRepresentation*>(self->WidgetRep)->
SetInteractionState(vtkPolyLineRepresentation::Scaling);
// start the interaction
self->EventCallbackCommand->SetAbortFlag(1);
self->StartInteraction();
self->InvokeEvent(vtkCommand::StartInteractionEvent,NULL);
self->Render();
}
//----------------------------------------------------------------------
void vtkPolyLineWidget::MoveAction(vtkAbstractWidget *w)
{
vtkPolyLineWidget *self = reinterpret_cast<vtkPolyLineWidget*>(w);
// See whether we're active
if ( self->WidgetState == vtkPolyLineWidget::Start )
{
return;
}
// compute some info we need for all cases
int X = self->Interactor->GetEventPosition()[0];
int Y = self->Interactor->GetEventPosition()[1];
// Okay, adjust the representation
double e[2];
e[0] = static_cast<double>(X);
e[1] = static_cast<double>(Y);
self->WidgetRep->WidgetInteraction(e);
// moving something
self->EventCallbackCommand->SetAbortFlag(1);
self->InvokeEvent(vtkCommand::InteractionEvent,NULL);
self->Render();
}
//----------------------------------------------------------------------
void vtkPolyLineWidget::EndSelectAction(vtkAbstractWidget *w)
{
vtkPolyLineWidget *self = reinterpret_cast<vtkPolyLineWidget*>(w);
if ( self->WidgetState == vtkPolyLineWidget::Start )
{
return;
}
// compute some info we need for all cases
int X = self->Interactor->GetEventPosition()[0];
int Y = self->Interactor->GetEventPosition()[1];
// Okay, adjust the representation
double e[2];
e[0] = static_cast<double>(X);
e[1] = static_cast<double>(Y);
self->WidgetRep->EndWidgetInteraction(e);
// Return state to not active
self->WidgetState = vtkPolyLineWidget::Start;
reinterpret_cast<vtkPolyLineRepresentation*>(self->WidgetRep)->
SetInteractionState(vtkPolyLineRepresentation::Outside);
self->ReleaseFocus();
self->EventCallbackCommand->SetAbortFlag(1);
self->EndInteraction();
self->InvokeEvent(vtkCommand::EndInteractionEvent,NULL);
self->Render();
}
//----------------------------------------------------------------------
void vtkPolyLineWidget::CreateDefaultRepresentation()
{
if ( ! this->WidgetRep )
{
this->WidgetRep = vtkPolyLineRepresentation::New();
}
}
//----------------------------------------------------------------------------
void vtkPolyLineWidget::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
| [
"shentianweipku@gmail.com"
] | shentianweipku@gmail.com |
c7cc7f7f3cbb97845300049b984787c6ae6ef905 | a29f5a6eb5eb2bd562868c179248e63223039699 | /VideoSource.h | 76d5168a5abac2c839477382f38b2c65734fdde3 | [] | no_license | omar-Fouad/gptam | 115d5ef96780675d300fbb277883d2bc78cdd3b4 | 0cd9f9de5d749b33d9e05206d243d76b3ce89ff4 | refs/heads/master | 2022-04-02T08:10:33.039810 | 2020-01-26T18:57:46 | 2020-01-26T18:57:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | h | // -*- c++ *--
// Copyright 2008 Isis Innovation Limited
//
// VideoSource.h
// Declares the VideoSource class
//
// This is a very simple class to provide video input; this can be
// replaced with whatever form of video input that is needed. It
// should open the video input on construction, and provide two
// function calls after construction: Size() must return the video
// format as an ImageRef, and GetAndFillFrameBWandRGB should wait for
// a new frame and then overwrite the passed-as-reference images with
// GreyScale and Colour versions of the new frame.
#include "OpenCV.h"
using namespace cv;
struct VideoSourceData;
class VideoSource
{
public:
VideoSource(int camera_index = -1);
void GetAndFillFrameBWandRGB(cv::Mat_<uchar> &imBW, cv::Mat &imRGB);
cv::Size2i getSize();
private:
int camera_index_;
cv::VideoCapture *pcap;
cv::Size2i mirSize;
};
| [
"terzakig@hotmail.com"
] | terzakig@hotmail.com |
ab32465c7cfa09b1b9b1fa49a8cb7eafb73fc388 | f8e700a629111fa551ea4be7fad5b3d9c76d2903 | /Lib/pch.h | b6bee0b10e5eaed762222fbb219c1187f52dea5a | [
"MIT"
] | permissive | GihanSoft/NaturalStringComparer-cpp | 4dec4d39ff2e6a43e8e8b7a03c20f2b2b233f0e7 | 8e32e370233eac09f28e8bc2b14d6de026ef6ccf | refs/heads/master | 2020-04-01T07:43:31.423691 | 2019-09-30T18:43:58 | 2019-09-30T18:43:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 629 | h | // pch.h: This is a precompiled header file.
// Files listed below are compiled only once, improving build performance for future builds.
// This also affects IntelliSense performance, including code completion and many code browsing features.
// However, files listed here are ALL re-compiled if any one of them is updated between builds.
// Do not add files here that you will be updating frequently as this negates the performance advantage.
#ifndef PCH_H
#define PCH_H
// add headers that you want to pre-compile here
#include "framework.h"
#include <string>
#define EXPORT extern "C" __declspec(dllexport)
#endif //PCH_H
| [
"chief.mb1976@gmail.com"
] | chief.mb1976@gmail.com |
403c3bb52ac204f0b8cbbb00f4d3f24de68fbc7d | a1abe87ee9e276ba60d26a63378c4ea3e35d7517 | /Source/Test/ISpriteRenderTestUtils/IMPL/Utils/RenTextureUtils.h | 3adcc52e22028502b87b1a93a0c4a7fd2feea5af | [] | no_license | AlexeyOgurtsov/SpriteRender | c3b1f855c4f869d3b60091a048beecf270577908 | f3eb9945dbc1f059fd0b0398ffc5557f7c086f13 | refs/heads/master | 2020-03-30T23:29:59.105528 | 2019-02-14T08:05:01 | 2019-02-14T08:05:01 | 151,702,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,534 | h | #pragma once
#include <d3d11.h>
#include <cassert>
#include <cstdlib>
#include "Exception.h"
#include "RenHRUtils.h"
#include "../../Utils/TexelColor.h"
#include "../../Utils/MathUtils.h"
namespace Test::IMPL
{
/**
* Returns true if the given MIP-level of the fiven texture is filled with the given color.
*
* @NOTE: InSubresource: mip level for non-array (or mip level or array element)
*/
bool TextureFilledWithColor(ID3D11DeviceContext* pDevCon, ID3D11Texture2D* pTex, UINT InSubresource, const TexelColor& InRefColor, bool bMatchAlpha);
/**
* Returns texel color at the given point from the given texture.
*
* @NOTE: InSubresource: mip level for non-array (or mip level or array element)
*/
TexelColor GetTexelColorAt(ID3D11DeviceContext* pDevCon, ID3D11Texture2D* pTex, const IntVec& InCoord, UINT InSubresource);
/**
* Returns texel color at the given point from the given mapped subresource.
*/
TexelColor GetTexelColor(const D3D11_MAPPED_SUBRESOURCE& InSubresource, DXGI_FORMAT InFormat, const IntVec& InCoord);
/**
* Returns texel color at the given point from the given subresource.
*/
TexelColor GetTexelColor(const void* pInData, DXGI_FORMAT InFormat, UINT InRowPitch, const IntVec& InCoord);
/**
* Fills content of the texture with zeroes
*/
void ZeroMainMip_ByMap(ID3D11DeviceContext* pDevCon, ID3D11Texture2D* pInTexture, D3D11_MAP InMap);
bool TexelMatches(const void* pInRefTexel, DXGI_FORMAT InRefTexelFormat, ID3D11DeviceContext* pInDevCon, ID3D11Texture2D* pTexture, UINT InRow, UINT InX);
} // Test::IMPL | [
"alexey_eng@mail.ru"
] | alexey_eng@mail.ru |
56c895cb903c31011a3362a70adb6a57390b158a | 362895164b21bb1c378896c5a6a9d0711ada3aeb | /1.2.cpp | 828d6739e1dadaa3520274cea6f5841b04907701 | [] | no_license | SanityTR/Lab.Raboti | e6223f2d8b75d93d9ccc11820e7959fd6c56911e | cba975d044e6b2b6272fa574e66fb18b8223ae97 | refs/heads/main | 2023-06-10T01:21:48.294840 | 2021-07-01T13:56:16 | 2021-07-01T13:56:16 | 382,049,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | cpp | #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a[3][3]; float d;
cout << "Enter matrix:" << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
cin >> a[i][j];
cout << "Enter next string" << endl;
}
cout << endl << endl << "Your matrix:" << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
cout << setw(5) << a[i][j];
cout << endl << endl;;
}
d = a[0][0] * a[1][1] * a[2][2] + a[0][1] * a[1][2] * a[2][0] + a[0][2] * a[1][0] * a[2][1] - a[0][2] * a[1][1] * a[2][0] - a[0][0] * a[1][2] * a[2][1] - a[0][1] * a[1][0] * a[2][2];
cout << setprecision(4) << d;
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
c3c6f621cedaec2059854a25266c52b8030e52aa | 256d43ee1fa529120a27fbbf5673242afa3cc672 | /BurstBollons.h | 037b82c5383d25048d05b780494dc54fdf857881 | [] | no_license | qian2729/leetcodecpp | 1a3a03093996fc7b9ab66a1d7892d4116008fad1 | a340f5450feec509e6155274f7733aa09e367868 | refs/heads/master | 2016-09-14T11:51:10.141864 | 2016-05-04T13:30:18 | 2016-05-04T13:30:18 | 58,054,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | h | //
// Created by 刘宗前 on 16/4/23.
//
#ifndef LEETCODE_BURSTBOLLONS_H
#define LEETCODE_BURSTBOLLONS_H
#include <vector>
using namespace std;
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n;
int r;
vector<int> new_num;
new_num.push_back(1);
for(int i = 0; i < nums.size(); ++i){
new_num.push_back(nums[i]);
}
new_num.push_back(1);
n = new_num.size();
vector<vector<int>> dp(n,vector<int>(n,0));
for (int range = 2; range < n; ++ range){
for (int l = 0; l < n - range; ++l){
r = l + range;
for (int m = l + 1; m < r; ++m){
dp[l][r] = max(dp[l][r], dp[l][m] + new_num[l] * new_num[m] * new_num[r] + dp[m][r]);
cout << l << "\t" << r << "\t" << dp[l][r] << endl;
}
}
}
return dp[0][n-1];
}
};
#endif //LEETCODE_BURSTBOLLONS_H
| [
"qian2729@163.com"
] | qian2729@163.com |
8d7be7456873cfdd26ba2535661c6ddabceee716 | dc57d617393613a8e99cb793a9ce3bf45620a7a0 | /CExercises17/Exercises01_6.cpp | fec703b0128557be1eec988e314ebe1a0adf73ed | [] | no_license | tfcpanda/cBaseExercises | 147e1dceff8a905a763bb4cc210692d73998460b | aeb89e194b3da8c8d8185db883be3ddf258bdcf1 | refs/heads/master | 2022-08-27T21:26:11.679189 | 2020-05-21T13:03:55 | 2020-05-21T13:03:55 | 258,239,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | #include<stdio.h>
int main()
{
int num, n, a[99], m = 0;
scanf("%d %d", &num, &n);
for(int i = 0;i < 99; i++)
{
if(num%n > 9)
{
a[i] = num%n + 55;
}
else
{
a[i] = num%n;
}
m++;
num = num/n;
if(num == 0)
{
break;
}
}
for(int j = m-1; j >= 0; j--)
{
if(a[j] > 9)
{
printf("%c", a[j]);
}
else
{
printf("%d", a[j]);
}
}
} | [
"tfcpanda@outlook.com"
] | tfcpanda@outlook.com |
d12f73a28fb770de5a8b63ea1eb7f01742280666 | 4c958d966495f7886c89b101f65cf968712139ef | /DNSServer/tags/ver_1.0_CName/tags/v1.0/DNSServer/include/ServerException.h | d81aed0453383d60f6509f1df27a51a2cdd1c86a | [] | no_license | van76007/SecureDNS | 94ca27e1aa37f7b6537961ee6293138e8879af51 | db8df79c85aa8d5cec94e8c48cfe201ee49f4e33 | refs/heads/master | 2016-09-06T10:21:21.873168 | 2015-01-25T08:34:26 | 2015-01-25T08:34:26 | 29,673,454 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,117 | h | /**
* @file
* @author snu <snu@csis.mu>
*
* @brief Header file for logging initialization
*
* @section Description
* Initializes the logging framework log4cxx.
* Implemented as a simple function.
*
*/
#ifndef NameServer_INITLOGGING_H
#define NameServer_INITLOGGING_H
#include <log4cxx/logstring.h>
#include <stdlib.h>
#include <log4cxx/logger.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/level.h>
#include <log4cxx/fileappender.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/simplelayout.h>
#include <log4cxx/patternlayout.h>
#include <iostream>
/**
* @brief Defines the available LogLayouts
*/
enum LogLayout { DEBUGLOG, PRODUCTIONLOG };
/**
* @brief Initialize a logger
*
* @param logDomain The logger which recieves the information
* @param logFileName The log file or the string "console" if console logging is desired
* @param LogLayout The logLayout, See LogLayout.
*
*/
log4cxx::FileAppenderPtr Server_logging(std::string logDomain, std::string logFileName, enum LogLayout loglayout);
#endif //NameServer_INITLOGGING_H
| [
"vanvu7609@gmail.com"
] | vanvu7609@gmail.com |
e9f21578d175d23c982903df5ac2c283ed333e2f | 69fda66cf52605e59dd8a212176612bb8956f947 | /ECEC622/HW8/CUDA_Gaussian_elim/gauss_eliminate_gold.cpp | 9df728e1c59beb5ff54acfdf286445151733e86e | [] | no_license | skore11/ECEC622 | a30c42485e737b067dbe79efc4e25851319cc509 | c31cdcf40b7d2ac6dfef8ad69eb3b4bff3ec3e8c | refs/heads/main | 2023-08-29T06:10:38.861099 | 2021-11-16T17:28:06 | 2021-11-16T17:28:06 | 428,751,530 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,282 | cpp | #include <stdio.h>
#include <stdlib.h>
extern "C" int compute_gold(float*, const float*, unsigned int);
int compute_gold(float* U, const float* A, unsigned int matrix_dim)
{
unsigned int i, j, k;
float pivot;
/* Copy contents of the A matrix into the U matrix */
for (i = 0; i < matrix_dim; i ++)
for(j = 0; j < matrix_dim; j++)
U[matrix_dim * i + j] = A[matrix_dim * i + j];
/* Perform Gaussian elimination in place on the U matrix */
for (k = 0; k < matrix_dim; k++) {
pivot = U[matrix_dim * k + k];
/* DO NOT HAVE TO PERFORM THIS CHECK IN YOUR PARALLEL CODE. */
if (pivot == 0) {
printf("Numerical instability detected. Principle diagonal element is zero at row %d\n", matrix_dim);
return 0;
}
for (j = (k + 1); j < matrix_dim; j++) /* Reduce current row */
U[matrix_dim * k + j] = (float) U[matrix_dim * k + j] / pivot; /* Division step */
U[matrix_dim * k + k] = 1; /* Set pivot element to 1 */
for (i = (k+1); i < matrix_dim; i++){ /* Elimination step. */
for (j = (k+1); j < matrix_dim; j++)
U[matrix_dim * i + j] = U[matrix_dim * i + j] - (U[matrix_dim * i + k] * U[matrix_dim * k + j]);
U[matrix_dim * i + k] = 0;
}
}
return 1;
}
| [
"abishek110790@gmail.com"
] | abishek110790@gmail.com |
f8584f8c17f5e50cb37e2b164ec5bacae6699119 | 17adb0e72c9dd190124a8d21171d9c8fcb23e333 | /ui/CxRun/LocalServer.cpp | e17bf8499e918278d74eb11f53fe96b8d51fdc75 | [
"MIT"
] | permissive | jafo2128/SuperCxHMI | 16dc0abb56da80db0f207d9194a37258575276b5 | 5a5afe2de68dc9a0c06e2eec945a579467ef51ff | refs/heads/master | 2020-04-01T16:30:20.771434 | 2016-02-06T00:40:53 | 2016-02-06T00:40:53 | 48,529,344 | 1 | 0 | null | 2015-12-24T06:45:45 | 2015-12-24T06:45:45 | null | GB18030 | C++ | false | false | 11,784 | cpp | // LocalServer.cpp: implementation of the CLocalServer class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "LocalServer.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CLocalServer::CLocalServer()
{
m_clsidLocalServer = CLSID_NULL;
m_pfnServerProc = NULL;
m_hServerThread = NULL;
m_pfnHandlerProc = NULL;
m_dwStatus = CX_SERVER_STOPPED; // 初始为停止状态
m_hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
}
CLocalServer::~CLocalServer()
{
if (m_hStopEvent != NULL)
SetEvent(m_hStopEvent);
if (m_hServerThread != NULL)
{
WaitForSingleObject(m_hServerThread, 10000);
CloseHandle(m_hServerThread);
m_hServerThread = NULL;
}
if (m_hStopEvent != NULL)
CloseHandle(m_hStopEvent);
}
BOOL CLocalServer::StartCtrlDispatcher(LPCTSTR lpszName, ServerMainProc pfnServerProc, BOOL bStartServerPorc)
{
m_bstrName = lpszName;
m_pfnServerProc = pfnServerProc;
if (bStartServerPorc)
m_hServerThread = ::CreateThread(NULL, 0, _ServerThreadProc, this, 0, NULL);
if (ControlDispatcher() != 0)
return FALSE;
return TRUE;
}
void CLocalServer::GetPipeName(CComBSTR& bstrName)
{
bstrName = L"\\\\.\\pipe\\CxBackgroundServer_";
bstrName += m_bstrName;
}
DWORD CLocalServer::ControlDispatcher()
{
USES_CONVERSION;
HANDLE hPipe = INVALID_HANDLE_VALUE;
HANDLE hEvents[2] = {NULL, NULL};
OVERLAPPED os;
DWORD dwWait;
BOOL bRet;
CComBSTR bstrPipeName;
GetPipeName(bstrPipeName);
hPipe = CreateNamedPipe(W2T(bstrPipeName), FILE_FLAG_OVERLAPPED | PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL);
if (hPipe == INVALID_HANDLE_VALUE)
{
ATLTRACE(_T("failed to create pipe!"));
return 1;
}
// 通知客户进程已经准备好
HANDLE hEevent = GetEventHandle();
SetEvent(hEevent);
CloseHandle(hEevent);
hEvents[0] = m_hStopEvent;
hEvents[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
if (hEvents[1] == NULL)
goto cleanup;
while (1)
{
memset(&os, 0, sizeof(OVERLAPPED));
os.hEvent = hEvents[1];
ResetEvent(hEvents[1]);
ConnectNamedPipe(hPipe, &os);
if (GetLastError() == ERROR_IO_PENDING)
{
dwWait = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
if (dwWait != WAIT_OBJECT_0 + 1) // not overlapped i/o event - error occurred,
break; // or server stop signaled
}
DWORD cbRead;
DWORD buff[2] = {0, 0};
memset(&os, 0, sizeof(OVERLAPPED));
os.hEvent = hEvents[1];
ResetEvent(hEvents[1]);
bRet = ReadFile(hPipe, &buff, sizeof(buff), &cbRead, &os);
if (!bRet && (GetLastError() == ERROR_IO_PENDING))
{
dwWait = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);
if (dwWait != WAIT_OBJECT_0 + 1) // not overlapped i/o event - error occurred,
break; // or server stop signaled
}
switch (buff[0])
{
case 1:
ServerStart(hPipe, buff[1]);
break;
case 2:
ServerGetStatus(hPipe);
break;
case 3:
ServerControl(hPipe, buff[1]);
break;
default:
ATLASSERT(false);
}
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
}
cleanup:
if (hPipe != INVALID_HANDLE_VALUE )
CloseHandle(hPipe);
if (hEvents[1]) // overlapped i/o event
CloseHandle(hEvents[1]);
return 0;
}
DWORD _stdcall CLocalServer::_ServerThreadProc(LPVOID pParam)
{
return ((CLocalServer *)pParam)->ServerThreadProc();
}
DWORD CLocalServer::ServerThreadProc()
{
USES_CONVERSION;
LPWSTR psz = m_bstrServerThreadArgs;
DWORD argc = 0;
int nLen = 0;
LPTSTR pszT;
LPTSTR* argv;
LPTSTR p;
if (psz != NULL)
{
while (psz[nLen])
{
nLen += wcslen(&psz[nLen]) + 1;
argc++;
}
}
if (!argc)
{
m_pfnServerProc(0, NULL);
goto onexit;
}
pszT = W2T(psz);
argv = (LPTSTR*)alloca((argc + 1) * sizeof(LPTSTR*));
p;
for (argc = 0, p = pszT; *p; p += strlen(p) + 1)
argv[argc++] = p;
argv[argc] = NULL;
m_pfnServerProc(argc, argv);
onexit:
if (m_hStopEvent != NULL)
SetEvent(m_hStopEvent);
return 0;
}
void CLocalServer::RegisterCtrlHandler(ServerHandlerProc pfnHandlerProc)
{
m_pfnHandlerProc = pfnHandlerProc;
}
BOOL CLocalServer::SetStatus(DWORD dwStatus)
{
m_dwStatus = dwStatus;
return TRUE;
}
BOOL CLocalServer::ServerStart(HANDLE hPipe, DWORD dwCount)
{
BOOL bRet;
DWORD dwResult = 0;
LPWSTR pszArgs = (LPWSTR)alloca(dwCount * sizeof(WCHAR));
DWORD cbRead = 0;
bRet = ReadFile(hPipe, pszArgs, dwCount * sizeof(WCHAR), &cbRead, NULL);
if (!bRet || dwCount != cbRead / sizeof(WCHAR) || pszArgs[dwCount - 1])
goto onexit;
if (m_hServerThread != NULL)
goto onexit;
m_bstrServerThreadArgs = pszArgs;
m_hServerThread = ::CreateThread(NULL, 0, _ServerThreadProc, this, 0, NULL);
onexit:
WriteFile(hPipe, &dwResult, sizeof(DWORD), &cbRead, NULL);
return TRUE;
}
BOOL CLocalServer::ServerGetStatus(HANDLE hPipe)
{
DWORD cbWrite = 0;
return WriteFile(hPipe, &m_dwStatus, sizeof(DWORD), &cbWrite, NULL);
}
BOOL CLocalServer::ServerControl(HANDLE hPipe, DWORD dwControl)
{
DWORD dwRet = ERROR_INVALID_SERVICE_CONTROL;
if (m_pfnHandlerProc != NULL)
{
m_pfnHandlerProc(dwControl);
dwRet = ERROR_SUCCESS;
}
DWORD cbWrite = 0;
return WriteFile(hPipe, &dwRet, sizeof(DWORD), &cbWrite, NULL);
}
BOOL CLocalServer::RegisterServiceCtrlHandler(ServerHandlerProc lpHandlerProc)
{
m_pfnHandlerProc = lpHandlerProc;
return TRUE;
}
HANDLE CLocalServer::GetEventHandle()
{
CComBSTR bstrName = L"CxBackgroundServer_";
bstrName += m_bstrName;
return CreateEventW(NULL, TRUE, FALSE, bstrName);
}
BOOL CLocalServer::GetClassServerPath(REFCLSID clsid, CComBSTR& bstrServerPath)
{
USES_CONVERSION;
HKEY hKey;
HKEY hServerKey;
WCHAR szCLSID[64];
LONG nResult;
ULONG nBytes;
DWORD dwType;
LPTSTR pszServerPath;
BOOL bRet;
StringFromGUID2(clsid, szCLSID, 64);
hKey = NULL;
hServerKey = NULL;
bRet = FALSE;
CComBSTR bstrKey = L"CLSID\\";
bstrKey += szCLSID;
nResult = RegOpenKeyEx(HKEY_CLASSES_ROOT, W2T(bstrKey), 0, KEY_READ, &hKey);
if (nResult != ERROR_SUCCESS)
goto onexit;
nResult = RegOpenKeyEx(hKey, _T("InprocServer32"), 0, KEY_READ, &hServerKey);
if (nResult != ERROR_SUCCESS)
{
nResult = RegOpenKeyEx( hKey, _T("InprocHandler32"), 0, KEY_READ, &hServerKey);
if (nResult != ERROR_SUCCESS)
{
nResult = RegOpenKeyEx(hKey, _T("LocalServer32"), 0, KEY_READ, &hServerKey);
if (nResult != ERROR_SUCCESS)
goto onexit;
}
}
nBytes = 0;
nResult = RegQueryValueEx(hServerKey, NULL, NULL, &dwType, NULL, &nBytes);
if (nResult != ERROR_SUCCESS || dwType != REG_SZ)
goto onexit;
pszServerPath = LPTSTR(_alloca(nBytes));
nResult = RegQueryValueEx(hServerKey, NULL, NULL, &dwType, LPBYTE(pszServerPath), &nBytes);
if (nResult != ERROR_SUCCESS || dwType != REG_SZ)
goto onexit;
bstrServerPath = pszServerPath;
bRet = TRUE;
onexit:
if (hKey != NULL)
RegCloseKey(hKey );
if (hServerKey != NULL )
RegCloseKey(hServerKey);
return bRet;
}
DWORD CLocalServer::StartProcess()
{
HANDLE hEvents[2] = {NULL, NULL};
PROCESS_INFORMATION pi;
STARTUPINFOW si;
BOOL bRet;
DWORD dwRet;
hEvents[0] = GetEventHandle();
ZeroMemory(&si, sizeof(STARTUPINFOW));
si.cb = sizeof(STARTUPINFOW);
CComBSTR bstrPath;
GetClassServerPath(m_clsidLocalServer, bstrPath);
bRet = CreateProcessW(NULL, bstrPath, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (bRet)
{
hEvents[1] = pi.hProcess;
dwRet = WaitForMultipleObjects(2, hEvents, FALSE, 30000);
if (dwRet != WAIT_OBJECT_0)
bRet = FALSE;
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
CloseHandle(hEvents[0]);
return bRet;
}
BOOL CLocalServer::SendStartMessage(HANDLE hPipe, LPCWSTR *argv, DWORD argc)
{
DWORD dwLen = 1;
for (DWORD dw = 0; dw < argc; dw++)
dwLen += wcslen(argv[dw]) + 1;
BYTE* pCmdBuf = (BYTE*)alloca(8 + dwLen * sizeof(WCHAR));
*(DWORD *)pCmdBuf = 1;
*(DWORD *)(pCmdBuf + 4) = dwLen;
LPWSTR p = (LPWSTR)(pCmdBuf + 8);
for (dw = 0; dw < argc; dw++)
{
wcscpy(p, argv[dw]);
p += wcslen(p) + 1;
}
*p = 0;
DWORD cbBytes = 0;
BOOL bRet = WriteFile(hPipe, pCmdBuf, 8 + dwLen * sizeof(WCHAR), &cbBytes, NULL);
if (bRet)
{
DWORD dwResult;
bRet = ReadFile(hPipe, &dwResult, sizeof(DWORD), &cbBytes, NULL);
}
return bRet;
}
BOOL CLocalServer::GetStatus(HANDLE hPipe, DWORD* pdwStatus)
{
DWORD cmd[2];
DWORD cbBytes = 0;
BOOL bRet;
cmd[0] = 2;
cmd[1] = 0;
bRet = WriteFile(hPipe, cmd, sizeof(cmd), &cbBytes, NULL );
if (!bRet || cbBytes != sizeof(cmd))
return bRet;
bRet = ReadFile( hPipe, pdwStatus, sizeof(DWORD), &cbBytes, NULL );
return bRet;
}
BOOL CLocalServer::QueryStatus(DWORD* pdwStatus)
{
HANDLE hPipe = OpenPipe();
if (hPipe != INVALID_HANDLE_VALUE)
{
BOOL bRet = GetStatus(hPipe, pdwStatus);
CloseHandle(hPipe);
if (bRet)
return TRUE;
}
*pdwStatus = CX_SERVER_STOPPED;
return TRUE;
}
BOOL CLocalServer::WaitForStartup()
{
DWORD dwStatus;
BOOL bRet = FALSE;
for (int i = 0; i < 30; i++)
{
dwStatus = 0;
bRet = QueryStatus(&dwStatus);
if (!bRet)
break;
if (dwStatus == CX_SERVER_RUNNING)
break;
bRet = FALSE;
Sleep(300);
}
return bRet;
}
BOOL CLocalServer::Start(DWORD dwNumArgs, LPCWSTR* lpArgVectors)
{
BOOL bRet = FALSE;
HANDLE hPipe = OpenPipe();
if (hPipe == INVALID_HANDLE_VALUE)
{
/* start the service process */
if (StartProcess())
hPipe = OpenPipe();
}
if (hPipe != INVALID_HANDLE_VALUE)
{
SendStartMessage(hPipe, lpArgVectors, dwNumArgs);
CloseHandle(hPipe);
bRet = TRUE;
}
if (bRet)
WaitForStartup();
return bRet;
}
HANDLE CLocalServer::OpenPipe()
{
CComBSTR bstrPipeName;
GetPipeName(bstrPipeName);
HANDLE hPipe = INVALID_HANDLE_VALUE;
do {
hPipe = CreateFileW(bstrPipeName, GENERIC_READ|GENERIC_WRITE,
0, NULL, OPEN_ALWAYS, 0, NULL);
if (hPipe != INVALID_HANDLE_VALUE)
break;
if (GetLastError() != ERROR_PIPE_BUSY)
break;
} while (WaitNamedPipeW(bstrPipeName, NMPWAIT_WAIT_FOREVER));
return hPipe;
}
BOOL CLocalServer::SendControl(HANDLE hPipe, DWORD dwControl, DWORD* pdwResult)
{
DWORD cmd[2];
DWORD cbBytes = 0;
BOOL rRet;
cmd[0] = 3;
cmd[1] = dwControl;
rRet = WriteFile(hPipe, cmd, sizeof(cmd), &cbBytes, NULL);
if (!rRet || cbBytes != sizeof(cmd))
return rRet;
rRet = ReadFile(hPipe, pdwResult, sizeof(DWORD), &cbBytes, NULL);
return rRet;
}
BOOL CLocalServer::ControlServer(DWORD dwControl, DWORD* pdwStatus)
{
BOOL bRet = FALSE;
HANDLE hPipe;
bRet = QueryStatus(pdwStatus);
if (!bRet)
return FALSE;
switch (*pdwStatus)
{
case SERVICE_STOPPED:
return FALSE;
case SERVICE_START_PENDING:
if (dwControl == SERVICE_CONTROL_STOP)
break;
/* fall thru */
case SERVICE_STOP_PENDING:
return FALSE;
}
hPipe = OpenPipe();
if (hPipe != INVALID_HANDLE_VALUE)
{
DWORD dwResult = ERROR_SUCCESS;
bRet = SendControl(hPipe, dwControl, &dwResult);
CloseHandle(hPipe);
if (dwResult != ERROR_SUCCESS)
bRet = FALSE;
}
return bRet;
} | [
"qinyong99@126.com"
] | qinyong99@126.com |
0456ee44af672fe4811c2362655e1809bf829dda | a6bab4e28684d6bc235599cc2a1bdf1086f99e3b | /addnewuser.h | cb73d254d50625b09fbb97d4cffcdc669a5fa87f | [] | no_license | vinnadipo09/bullet | a23554b32b19d9df398577e5bf600a5fc5314986 | 7d0b0735a5589e7adfe9e592d7a5fe3638a777e4 | refs/heads/master | 2023-01-02T05:15:46.347540 | 2020-10-27T12:46:36 | 2020-10-27T12:46:36 | 274,897,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,173 | h | #ifndef ADDNEWUSER_H
#define ADDNEWUSER_H
#include <QDialog>
#include<QFileDialog>
#include"debugger.h"
#include"verifynewuser.h"
#include"databaseconnection.h"
#include"viewuser.h"
namespace Ui {
class AddNewUser;
}
class AddNewUser : public QDialog
{
Q_OBJECT
public:
explicit AddNewUser(QWidget *parent, loggedUser ¤tLoggedInUser);
~AddNewUser();
private slots:
void on_btn_cancel_clicked();
void on_btn_okay_clicked();
void on_pb_avatar_clicked();
void on_pushbuttonAvatar_clicked();
private:
VerifyNewUser* verifyUser;
private:
posUser* newUser;
void grabUserDetails();
void checkValidityOfUsername();
void checkIfAllFieldsAreFilled();
void checkIfPasswordsMatch();
void checkIfUsernameTaken();
loggedUser currentUser;
QString avatarFile;
databaseConnection* addNewUserConnection;
bool userNameExists=false;
bool allFieldsFilled=false;
bool passwordsMatch=true;
private:
Ui::AddNewUser *ui;
private:
void clearAllFields();
private slots:
void receiveUserAdditionCompleteFromVerification();
signals:
void sendUserAdditionComplete();
};
#endif // ADDNEWUSER_H
| [
"vinnadipo09@gmail.com"
] | vinnadipo09@gmail.com |
4bfdbccd0ddcbbe84797ab46ede2be68000aaec4 | 100e310f1a03dc8d2ce9240a9bb1659ff7c17fd5 | /src/relay.cpp | 806397f28913ed08710a60b84a0f40bb3db58e37 | [
"MIT"
] | permissive | rafaelbds04/esp-rtc-timer | 761688974fdb2b7937b13cc28483341bee95af39 | 5b674a65d60e1593822003ebb11ad2252debbd7e | refs/heads/master | 2023-07-05T16:11:53.634690 | 2021-08-20T17:09:21 | 2021-08-20T17:09:21 | 397,473,178 | 1 | 0 | null | 2021-08-18T21:55:15 | 2021-08-18T04:34:04 | HTML | UTF-8 | C++ | false | false | 1,595 | cpp | #include <iostream>
#include <sstream>
#include <time.h>
#include "rtc.h"
#include "relay.h"
#include "debug.h"
#include <ArduinoJson.h>
#include "local_storage.h"
bool isRelayEnable = false;
time_t getTimeUnixFromString(std::string timestr)
{
for (std::string::size_type pos = timestr.find(':'); pos != std::string::npos; pos = timestr.find(':', pos))
timestr[pos] = ' ';
std::stringstream iss_time(timestr);
int hour, min, sec = 0;
iss_time >> hour >> min >> sec;
tm t;
time_t now = getActualUnixtime();
memcpy(&t, localtime(&now), sizeof(t));
t.tm_hour = hour;
t.tm_min = min;
t.tm_sec = sec;
return mktime(&t);
}
void handleStartRelay()
{
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, HIGH);
}
void handleTurnRelayOn()
{
digitalWrite(RELAY_PIN, LOW);
}
void handleTurnRelayOff()
{
digitalWrite(RELAY_PIN, HIGH);
}
void handleRelaySchedule()
{
time_t now = getActualUnixtime();
isRelayEnable = false;
for (JsonObject elem : getConfigJson().as<JsonArray>())
{
const char *timeStart = elem["timeStart"]; // "10:45:10", "10:45:10"
const char *timeEnd = elem["timeEnd"]; // "10:45:10", "10:45:10"
time_t t_hour_start = getTimeUnixFromString(timeStart);
time_t t_hour_end = getTimeUnixFromString(timeEnd);
JsonArray days = elem["days"];
for (JsonVariant v : days)
{
if (v.as<int>() == getActualDateTime().dayOfTheWeek() &&
(t_hour_start <= now) && (now <= t_hour_end))
{
isRelayEnable = true;
}
}
}
isRelayEnable ? handleTurnRelayOn() : handleTurnRelayOff();
} | [
"38199191+rafanel2@users.noreply.github.com"
] | 38199191+rafanel2@users.noreply.github.com |
d5cbd6b04416f6e6393c152666987d97567c58aa | 17c6cc6bcaba6a6ac0da95070a088c8bc26d82b1 | /ConfigFile.cpp | 1657b3b5b73bf5a6d3bdb3a63920dcdc12ffc287 | [] | no_license | SegaraRai/SleepPreventer | 70df36f9b08eb4e0bbf02655bbe1d55ba658bca0 | 200484e205ccb7b7685ccdc5fa2a1930a14a5d44 | refs/heads/master | 2023-01-08T00:24:15.227527 | 2020-11-10T12:38:29 | 2020-11-10T12:38:29 | 304,890,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,897 | cpp | #include "ConfigFile.hpp"
#include <filesystem>
#include <fstream>
#include <map>
#include <optional>
#include <shared_mutex>
#include <string>
#include <string_view>
using namespace std::literals;
ConfigFile::ConfigFile(const std::wstring& filepath) :
mFilepath(filepath)
{
Load();
}
ConfigFile::~ConfigFile() {
Save();
}
void ConfigFile::Load() {
std::lock_guard lock(mMutex);
mConfigMap.clear();
std::wfstream wfs;
wfs.open(mFilepath, std::ios_base::in);
if (wfs.fail()) {
return;
}
for (std::wstring line; std::getline(wfs, line); ) {
if (line.empty()) {
continue;
}
const auto eqPos = line.find_first_of(L'=');
if (eqPos == std::wstring::npos) {
continue;
}
std::size_t keyEnd = eqPos;
while (keyEnd > 0 && line[keyEnd - 1] == L' ') {
keyEnd--;
}
std::size_t valueBegin = eqPos + 1;
while (valueBegin < line.size() && line[valueBegin] == L' ') {
valueBegin++;
}
try {
mConfigMap.insert_or_assign(line.substr(0, keyEnd), std::stoi(line.substr(valueBegin)));
} catch (...) {}
}
}
void ConfigFile::Save() {
std::lock_guard lock(mMutex);
std::wfstream wfs;
wfs.open(mFilepath, std::ios_base::out | std::ios_base::trunc);
if (wfs.fail()) {
return;
}
for (const auto& [key, value] : mConfigMap) {
wfs << key << L" = "sv << value << std::endl;
}
wfs << std::flush;
}
std::optional<int> ConfigFile::Get(const std::wstring& key) const {
std::shared_lock lock(mMutex);
const auto itr = mConfigMap.find(key);
if (itr == mConfigMap.cend()) {
return std::nullopt;
}
return std::make_optional(itr->second);
}
void ConfigFile::Set(const std::wstring& key, int value, bool skipIfExists) {
std::lock_guard lock(mMutex);
if (skipIfExists) {
mConfigMap.try_emplace(key, value);
} else {
mConfigMap.insert_or_assign(key, value);
}
}
| [
"SegaraRai@users.noreply.github.com"
] | SegaraRai@users.noreply.github.com |
4a5f7c875335fd4d46902c3e270ad690c0b88b83 | 1c3bc2d44b9615aafd8c7a0fde1137462c76f3cd | /src/TestProject/UnitTest.cpp | 9997f8c5570d3a3945744ec420554589e54ec0ed | [] | no_license | lishenluo/writtenexam | 5c20285532aa3306294d2148e18795eca462620f | 25516032484a13e587b98db612260c8c447ab530 | refs/heads/master | 2022-03-04T15:23:31.589302 | 2019-09-12T02:27:46 | 2019-09-12T02:27:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,220 | cpp | #include "stdafx.h"
#include "IssueOne.h"
#include "IssueTwo.h"
#include "IssueThree.h"
#include "IssueFour.h"
#include <sqlite\sqlite3.h>
using namespace System;
using namespace System::Text;
using namespace System::Collections::Generic;
using namespace Microsoft::VisualStudio::TestTools::UnitTesting;
using namespace csc;
namespace TestProject
{
[TestClass]
public ref class UnitTest
{
private:
TestContext^ testContextInstance;
public:
/// <summary>
///获取或设置测试上下文,该上下文提供
///有关当前测试运行及其功能的信息。
///</summary>
property Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ TestContext
{
Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ get()
{
return testContextInstance;
}
System::Void set(Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ value)
{
testContextInstance = value;
}
};
#pragma region Additional test attributes
//
// 编写测试时,可以使用以下附加特性:
//
// 在运行类中的第一个测试之前使用 ClassInitialize 运行代码
//[ClassInitialize()]
//static void MyClassInitialize(TestContext^ testContext) {};
//
// 在类中的所有测试都已运行之后使用 ClassCleanup 运行代码
//[ClassCleanup()]
//static void MyClassCleanup() {};
//
//在运行每个测试之前,使用 TestInitialize 来运行代码
//[TestInitialize()]
//void MyTestInitialize() {};
//
//在每个测试运行完之后,使用 TestCleanup 来运行代码
//[TestCleanup()]
//void MyTestCleanup() {};
//
#pragma endregion
[TestMethod]
void TestMethod1()
{
//测试IssueOne
IssueOne issueOne = IssueOne("../datadir/data.csv");
issueOne.showIssueOneResult();
Assert::AreEqual(issueOne.isEmpeyOfNeedCalcData(), false);
issueOne = IssueOne("");
vector<double> indexData = { 1,1,1,1,1 };
vector<double> stockData = { -1,-1,-1,-1,-1 };
issueOne.setNeedCalcData("index", "stock", indexData, stockData);
Assert::IsFalse(issueOne.isEmpeyOfNeedCalcData());
Assert::AreEqual(0.0, issueOne.getMathValue(INDEX, STD_DATA));
Assert::AreEqual(0.0, issueOne.getMathValue(STOCK, STD_DATA));
Assert::AreEqual(0.0, issueOne.getMathValue(STOCK, CORR_DATA));
indexData = { 1,2,3,4,5 };
stockData = { -1,-2,-3,-4,-5 };
issueOne.setNeedCalcData("index", "stock", indexData, stockData);
Assert::IsFalse(issueOne.isEmpeyOfNeedCalcData());
Assert::AreEqual(5.0, issueOne.getMathValue(INDEX, MAX_DATA));
Assert::AreEqual(1.0, issueOne.getMathValue(INDEX, MIN_DATA));
Assert::AreEqual(3.0, issueOne.getMathValue(INDEX, MEDIAN_DATA));
Assert::AreEqual(3.0, issueOne.getMathValue(INDEX, AVG_DATA));
Assert::AreEqual(-3.0, issueOne.getMathValue(STOCK, MEDIAN_DATA));
bool corrDiff = abs(issueOne.getMathValue(STOCK, CORR_DATA) +1.0) < FLOAT_ERROR;//-1
Assert::IsTrue(corrDiff);
indexData = { 10,8,6,4,2 };
stockData = { 5,4,3,2,1 };
issueOne.setNeedCalcData("index", "stock", indexData, stockData);
Assert::IsFalse(issueOne.isEmpeyOfNeedCalcData());
corrDiff = abs(issueOne.getMathValue(STOCK, CORR_DATA) - 1.0) < FLOAT_ERROR;//1
Assert::IsTrue(corrDiff);
};
[TestMethod]
void TestMethod2()
{
//测试IssueTwo
IssueTwo issueTwo;
vector<double> testlist = { -1,-1,-1,-1,-1 };
issueTwo.setList(testlist);
Assert::AreEqual(-1.0, issueTwo.getMaxSubSum());
Assert::AreEqual(5, issueTwo.getSizeOfMaxSubListPosition());
testlist = { -1,-1,2,-1,-1,1,1,0};
issueTwo.setList(testlist);
Assert::AreEqual(2.0, issueTwo.getMaxSubSum());
Assert::AreEqual(5, issueTwo.getSizeOfMaxSubListPosition());//2;2 -1 -1 1 1;2 -1 -1 1 1 0;1 1;1 1 0
testlist = {0,0,0,0};
issueTwo.setList(testlist);
Assert::AreEqual(0.0, issueTwo.getMaxSubSum());
Assert::AreEqual(10, issueTwo.getSizeOfMaxSubListPosition());
testlist = { 0,1.5,0};
issueTwo.setList(testlist);
Assert::AreEqual(1.5, issueTwo.getMaxSubSum());
Assert::AreEqual(4, issueTwo.getSizeOfMaxSubListPosition());//0 1.5;1.5;1.5 0;0 1.5 0
};
[TestMethod]
void TestMethod3()
{
//测试IssueThree
};
[TestMethod]
void TestMethod4()
{
//测试IssueFour
IssueFour issueFour("../datadir/MarketDataCSC.db");
issueFour.openSqliteDatabase();
const char* sql = "CREATE TABLE MarketData("\
"StockCode CAHR(9) NOT NULL, "\
"DateTime TEXT(20) NOT NULL, "\
"close REAL(11, 4) NOT NULL, "\
"volume INTEGER(11) NOT NULL );";
issueFour.deleteTable("MarketData");
Assert::IsTrue(issueFour.creatTable(sql));
issueFour.readMarketDataFromCSV("../datadir/SZ000002.csv", "000002.SZ");
Assert::IsTrue(issueFour.insertDataToDB("MarketData", "StockCode,DateTime,close,volume"));
issueFour.selectOptim("MarketData","DateTime");
//issueFour.showSelectData();
Assert::IsTrue(issueFour.showMovingAvg(5, NORMAL));
Assert::IsTrue(issueFour.showMovingAvg(5, VOL_WEIGHT));
//容错测试
Assert::IsFalse(issueFour.showMovingAvg(-1, NORMAL));//周期不对
Assert::IsFalse(issueFour.showMovingAvg(-5, VOL_WEIGHT));//周期不对
Assert::IsFalse(issueFour.creatTable(sql));//创建数据库表失败//重复创建
sql = "CREATE TABLE MarketDataAnother("\
"StockCode CHAR(9) NOT NULL, "\
"DateTime TEXT(20) NOT NULL, "\
"close REAL(11, 4) NOT NULL, "\
"volume INTEGER(11) NOT NULL );";
issueFour.deleteTable("MarketDataAnother");//有没有表都尝试删除
Assert::IsTrue(issueFour.creatTable(sql));//创建数据库表成功//另一张表
sql = "CREAT TABLE MarketDataOther("\
"StockCode CHAR(9) NOT NULL, "\
"DateTime TEXT(20) NOT NULL, "\
"close REAL(11, 4) NOT NULL, "\
"volume INTEGER(11) NOT NULL );";
issueFour.deleteTable("MarketDataOther");//有没有表都尝试删除
Assert::IsFalse(issueFour.creatTable(sql));//创建数据库表成功//sql语句错误
issueFour.closeSqliteDatabase();
};
};
}
| [
"lishenluo@163.com"
] | lishenluo@163.com |
02170f8123bebd2e0c035394ef702faa4ca1febe | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/ICU/icu4c-53_1/source/common/locbased.cpp | b3d911d0edc1a66b2471fe95e5ad6fba5f1f6dee | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"ICU",
"NAIST-2003",
"LicenseRef-scancode-unicode",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 1,379 | cpp | /*
**********************************************************************
* Copyright (c) 2004-2014, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: January 16 2004
* Since: ICU 2.8
**********************************************************************
*/
#include "locbased.h"
#include "cstring.h"
U_NAMESPACE_BEGIN
Locale LocaleBased::getLocale(ULocDataLocaleType type, UErrorCode& status) const {
const char* id = getLocaleID(type, status);
return Locale((id != 0) ? id : "");
}
const char* LocaleBased::getLocaleID(ULocDataLocaleType type, UErrorCode& status) const {
if (U_FAILURE(status)) {
return NULL;
}
switch(type) {
case ULOC_VALID_LOCALE:
return valid;
case ULOC_ACTUAL_LOCALE:
return actual;
default:
status = U_ILLEGAL_ARGUMENT_ERROR;
return NULL;
}
}
void LocaleBased::setLocaleIDs(const char* validID, const char* actualID) {
if (validID != 0) {
uprv_strcpy(valid, validID);
}
if (actualID != 0) {
uprv_strcpy(actual, actualID);
}
}
void LocaleBased::setLocaleIDs(const Locale& validID, const Locale& actualID) {
uprv_strcpy(valid, validID.getName());
uprv_strcpy(actual, actualID.getName());
}
U_NAMESPACE_END
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
0e17f728060da886b9253d806523b482c170fc05 | 37421acb6ab434bf46afc30fe20397892b55fd93 | /code/l3lib/include/log4cplus/hierarchylocker.h | 8a0a6837b49f35d2859ddb0c5f276adfd54c51bc | [] | no_license | achishex/thunder | cd7f78b23eaf87a83b258eb2c930d97eccbe7e81 | e07135f6c496f268c8b0b043148b9a30bcc60a64 | refs/heads/master | 2021-05-06T10:27:23.416594 | 2017-09-01T16:35:36 | 2017-09-01T16:35:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,226 | h | // -*- C++ -*-
// Module: Log4CPLUS
// File: hierarchylocker.h
// Created: 8/2003
// Author: Tad E. Smith
//
//
// Copyright 2003-2013 Tad E. Smith
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** @file */
#ifndef LOG4CPLUS_HIERARCHY_LOCKER_HEADER_
#define LOG4CPLUS_HIERARCHY_LOCKER_HEADER_
#include "../../../l3lib/include/log4cplus/config.hxx"
#if defined (LOG4CPLUS_HAVE_PRAGMA_ONCE)
#pragma once
#endif
#include "../../../l3lib/include/log4cplus/tstring.h"
#include "../../../l3lib/include/log4cplus/appender.h"
#include "../../../l3lib/include/log4cplus/logger.h"
namespace log4cplus
{
class Hierarchy;
/**
* This is used to lock a Hierarchy. The dtor unlocks the Hierarchy.
*/
class LOG4CPLUS_EXPORT HierarchyLocker {
public:
// ctor & dtor
HierarchyLocker(Hierarchy& h);
~HierarchyLocker();
/**
* Calls the <code>resetConfiguration()</code> method on the locked Hierarchy.
*/
void resetConfiguration();
/**
* Calls the <code>getInstance()</code> method on the locked Hierarchy.
*/
Logger getInstance(const log4cplus::tstring& name);
/**
* Calls the <code>getInstance()</code> method on the locked Hierarchy.
*/
Logger getInstance(const log4cplus::tstring& name, spi::LoggerFactory& factory);
void addAppender(Logger &logger, log4cplus::SharedAppenderPtr& appender);
private:
// Data
Hierarchy& h;
log4cplus::thread::MutexGuard hierarchyLocker;
LoggerList loggerList;
};
} // end namespace log4cplus
#endif // LOG4CPLUS_HIERARCHY_LOCKER_HEADER_
| [
"“chenjiayi@tuandai.com”"
] | “chenjiayi@tuandai.com” |
3ce89347a898e9e4089d0f26a5ba347ec1cbfc66 | d1b92aabd9de5df261b8bbaf41d3495d40268dcc | /include/Tools/Shader.hpp | 997f30834b32246fd6ac75afdb13ce72d419860e | [] | no_license | yang851992774/Framework | 75be94bfe50e20ac0d38504d309effbdf8a80240 | 4d084c19167d9fa64b542145793b0a31b4f605ba | refs/heads/main | 2022-11-15T12:04:23.122250 | 2022-10-24T02:08:30 | 2022-10-24T02:08:30 | 78,084,486 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | hpp | //
// Shader.hpp
// LearnOpenGL
//
// Created by Johnson on 2022/10/22.
//
#ifndef Shader_hpp
#define Shader_hpp
#include <glad/glad.h>; // 包含glad来获取所有的必须OpenGL头文件
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
class Shader
{
public:
// 程序ID
unsigned int ID;
// 构造器读取并构建着色器
Shader(const char* vertexPath, const char* fragmentPath);
// 使用/激活程序
void use();
// uniform工具函数
void setBool(const std::string &name, bool value) const;
void setInt(const std::string &name, int value) const;
void setFloat(const std::string &name, float value) const;
private:
void checkCompileErrors(unsigned int shader, std::string type);
};
#endif /* Shader_hpp */
| [
"851992774@qq.com"
] | 851992774@qq.com |
2159381f664295718d166f5307e84ac13fa10c41 | ea171f38a17177eb83c10afefa63dbaf1e49ff0d | /src/integrators/pssmlt/pssmlt.h | df90c55b9c2d75b2211f9a61aab9345c54eaba59 | [
"MIT"
] | permissive | Ilinite/MiyukiRenderer | 2a08ebf4620fa03ab527617db088ae799ded11f1 | 40ed7a36ac1d71cfe112a98182fa232f446da4e2 | refs/heads/master | 2020-05-04T15:50:16.746012 | 2019-04-01T19:05:21 | 2019-04-01T19:05:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,635 | h | //
// Created by Shiina Miyuki on 2019/3/22.
//
#ifndef MIYUKI_PSSMLT_H
#define MIYUKI_PSSMLT_H
#include <integrators/volpath/volpath.h>
#include <samplers/mltsampler.h>
#include <integrators/mmlt/mmlt.h>
namespace Miyuki {
// Unidirectional PSSMLT only makes things worse
class PSSMLT : public VolPath {
protected:
int nBootstrap;
int nChains;
int64_t nMutations;
Float b;
Float largeStep;
int nDirect;
std::vector<Seed> mltSeeds;
DECLARE_STATS_MEMBER(uint64_t, acceptanceCounter);
DECLARE_STATS_MEMBER(uint64_t, mutationCounter);
std::vector<std::shared_ptr<MLTSampler>> samplers;
std::unique_ptr<ProgressReporter<uint64_t>> reporter;
std::mutex mutex;
Spectrum radiance(Scene &scene, MemoryArena *arena, MLTSampler *sampler, Point2i *raster);
void handleDirect(Scene &scene);
public:
PSSMLT(const ParameterSet &set) : VolPath(set) {
nBootstrap = set.findInt("integrator.nBootstrap", 100000);
nDirect = set.findInt("integrator.nDirect", 16);
nChains = set.findInt("integrator.nChains", 1000);
largeStep = set.findFloat("integrator.largeStep", 0.25f);
b = 0;
}
void render(Scene &scene) override;
void renderProgressive(Scene &scene);
void renderNonProgressive(Scene &scene);
void recoverImage(Scene &scene);
private:
void generateBootstrapSamples(Scene &scene);
void runMC(Scene &scene, MLTSampler *sampler, MemoryArena *arena);
};
}
#endif //MIYUKI_PSSMLT_H
| [
"38184032+xt271828@users.noreply.github.com"
] | 38184032+xt271828@users.noreply.github.com |
4358b5be347d0c326ffe7e233c7ad09e798845c2 | e238869413e90ed411f63f35ce7a05f23d2d0c1b | /EveOverview.hpp | 40cbd700e13309cfbc7ec7805fd208cace21eb9d | [] | no_license | creepyfun/bro-driver | 56f9c9eee64b98edb4ea6df8e97f06938eb79d72 | ffca36e13b0ac991000ac5869f284edee76a2bfc | refs/heads/master | 2020-06-05T05:19:10.827074 | 2019-06-17T12:19:36 | 2019-06-17T12:19:36 | 192,325,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | hpp | #include <opencv2/opencv.hpp>
#include "EveIngameWindow.hpp"
class EveWindow;
class EveOverview : public EveIngameWindow
{
public:
EveOverview( EveWindow* eveWindow,
std::string fileNameFragmentTopLeft,
std::string fileNameFragmentBottomRight,
int refreshCount, int refreshDevider );
void refresh();
private:
};
| [
"wsd@comec92.ru"
] | wsd@comec92.ru |
02ed5f7ae3d3942efcce0b927b38ac5955664f19 | f34b735b45f647b286a5e791ab6ea228807fd897 | /SDDD/mainwindow.h | c1c9dfa3312371a1a27401d3f74ad2b0d91bc76b | [
"MIT"
] | permissive | hux8/SDD-Project | 223ac377c3fced793f9976e72bac22ee35f2e066 | 1d589f88655f5a565f0c2efb5d60a3dd8ccc5c06 | refs/heads/master | 2020-04-02T03:07:10.046775 | 2019-03-15T17:28:53 | 2019-03-15T17:28:53 | 153,947,071 | 0 | 5 | MIT | 2019-03-15T17:28:54 | 2018-10-20T20:48:55 | C++ | UTF-8 | C++ | false | false | 725 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "verification.h"
#include "homepage.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
/**
* @brief verify opens the verification page
*/
void verify();
/**
* @brief enterMain opens the homepage
*/
void enterMain();
/**
* @brief setInstructor sets the access
*/
void setInstructor();
/**
* @brief quit closes the program
*/
void quit();
private:
Ui::MainWindow *ui;
bool isInstructor;
Verification* v;
};
#endif // MAINWINDOW_H
| [
"xingjianzhao124@gmail.com"
] | xingjianzhao124@gmail.com |
9ce326fb3cd8de81e101e7885143916b488722cc | 59e3e89b1bc840b18d804c61d06bb3e8358f2c8d | /prime-number-problems/Miller_Rabin-test.cpp | b356504b1e2b072b1037b16fe741b9806627f924 | [] | no_license | youstair/C-_algorithm | 09a5d4cded393fcba1d7471b41233365d29e9e92 | 589418170599c4f951e06182f4bf1bddb6cc2f7e | refs/heads/master | 2020-03-28T23:26:36.154353 | 2019-04-10T14:17:12 | 2019-04-10T14:17:12 | 149,291,374 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,270 | cpp | #include"stdafx.h"
#include<cstdio>
#define LL long long
//18位素数:154590409516822759
//19位素数:2305843009213693951 (梅森素数)
//19位素数:4384957924686954497
LL prime[6] = { 2, 3, 5, 233, 331 };
LL qmul(LL x, LL y, LL mod) { // 乘法防止溢出, 如果p * p不爆LL的话可以直接乘; O(1)乘法或者转化成二进制加法
return (x * y - (long long)(x / (long double)mod * y + 1e-3) *mod + mod) % mod;
/*
LL ret = 0;
while(y) {
if(y & 1)
ret = (ret + x) % mod;
x = x * 2 % mod;
y >>= 1;
}
return ret;
*/
}
LL qpow(LL a, LL n, LL mod) {
LL ret = 1;
while (n) {
if (n & 1) ret = qmul(ret, a, mod);
a = qmul(a, a, mod);
n >>= 1;
}
return ret;
}
bool Miller_Rabin(LL p) {
if (p < 2) return 0;
if (p != 2 && p % 2 == 0) return 0;
LL s = p - 1;
while (!(s & 1)) s >>= 1;
for (int i = 0; i < 5; ++i) {
if (p == prime[i]) return 1;
LL t = s, m = qpow(prime[i], s, p);
while (t != p - 1 && m != 1 && m != p - 1)
{
m = qmul(m, m, p);
t <<= 1;
}
if (m != p - 1 && !(t & 1)) return 0;
}
return 1;
}
int main()
{
LL a;
while (scanf_s("%lld", &a))
{
if (Miller_Rabin(a)) puts("1");
else puts("0");
}
return 0;
}
//#include<cstdio>
//int main()
//{
// printf("%lf\n", 1e9+7);
// return 0;
//} | [
"youstair@qq.com"
] | youstair@qq.com |
1ee83daedcdfdac9fb34b7341ec306c3361e661d | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /chrome/browser/chromeos/crostini/crostini_registry_service_unittest.cc | 195d0ce29256e3e488916b212f6b972b2a088e6d | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 13,889 | cc | // Copyright 2018 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/chromeos/crostini/crostini_registry_service.h"
#include <stddef.h>
#include "base/macros.h"
#include "base/test/simple_test_clock.h"
#include "chrome/browser/chromeos/crostini/crostini_util.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/dbus/vm_applications/apps.pb.h"
#include "components/crx_file/id_util.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using vm_tools::apps::App;
using vm_tools::apps::ApplicationList;
namespace crostini {
class CrostiniRegistryServiceTest : public testing::Test {
public:
CrostiniRegistryServiceTest() = default;
// testing::Test:
void SetUp() override {
service_ = std::make_unique<CrostiniRegistryService>(&profile_);
service_->SetClockForTesting(&test_clock_);
}
protected:
class Observer : public CrostiniRegistryService::Observer {
public:
MOCK_METHOD4(OnRegistryUpdated,
void(CrostiniRegistryService*,
const std::vector<std::string>&,
const std::vector<std::string>&,
const std::vector<std::string>&));
};
std::string GenerateAppId(const std::string& desktop_file_id,
const std::string& vm_name,
const std::string& container_name) {
return crx_file::id_util::GenerateId(
"crostini:" + vm_name + "/" + container_name + "/" + desktop_file_id);
}
App BasicApp(const std::string& desktop_file_id,
const std::string& name = "") {
App app;
app.set_desktop_file_id(desktop_file_id);
App::LocaleString::Entry* entry = app.mutable_name()->add_values();
entry->set_locale(std::string());
entry->set_value(name.empty() ? desktop_file_id : name);
return app;
}
// Returns an ApplicationList with a single desktop file
ApplicationList BasicAppList(const std::string& desktop_file_id,
const std::string& vm_name,
const std::string& container_name) {
ApplicationList app_list;
app_list.set_vm_name(vm_name);
app_list.set_container_name(container_name);
*app_list.add_apps() = BasicApp(desktop_file_id);
return app_list;
}
std::string WindowIdForWMClass(const std::string& wm_class) {
return "org.chromium.termina.wmclass." + wm_class;
}
CrostiniRegistryService* service() { return service_.get(); }
protected:
base::SimpleTestClock test_clock_;
private:
content::TestBrowserThreadBundle thread_bundle_;
TestingProfile profile_;
std::unique_ptr<CrostiniRegistryService> service_;
DISALLOW_COPY_AND_ASSIGN(CrostiniRegistryServiceTest);
};
TEST_F(CrostiniRegistryServiceTest, SetAndGetRegistration) {
std::string desktop_file_id = "vim";
std::string vm_name = "awesomevm";
std::string container_name = "awesomecontainer";
std::map<std::string, std::string> name = {{"", "Vim"}};
std::map<std::string, std::string> comment = {
{"", "Edit text files"},
{"en_GB", "Modify files containing textual content"},
};
std::vector<std::string> mime_types = {"text/plain", "text/x-python"};
bool no_display = true;
std::string app_id = GenerateAppId(desktop_file_id, vm_name, container_name);
EXPECT_EQ(nullptr, service()->GetRegistration(app_id));
ApplicationList app_list;
app_list.set_vm_name(vm_name);
app_list.set_container_name(container_name);
App* app = app_list.add_apps();
app->set_desktop_file_id(desktop_file_id);
app->set_no_display(no_display);
for (const auto& localized_name : name) {
App::LocaleString::Entry* entry = app->mutable_name()->add_values();
entry->set_locale(localized_name.first);
entry->set_value(localized_name.second);
}
for (const auto& localized_comment : comment) {
App::LocaleString::Entry* entry = app->mutable_comment()->add_values();
entry->set_locale(localized_comment.first);
entry->set_value(localized_comment.second);
}
for (const std::string& mime_type : mime_types)
app->add_mime_types(mime_type);
service()->UpdateApplicationList(app_list);
auto result = service()->GetRegistration(app_id);
ASSERT_NE(nullptr, result);
EXPECT_EQ(result->desktop_file_id, desktop_file_id);
EXPECT_EQ(result->vm_name, vm_name);
EXPECT_EQ(result->container_name, container_name);
EXPECT_EQ(result->name, name);
EXPECT_EQ(result->comment, comment);
EXPECT_EQ(result->mime_types, mime_types);
EXPECT_EQ(result->no_display, no_display);
}
TEST_F(CrostiniRegistryServiceTest, Observer) {
ApplicationList app_list = BasicAppList("app 1", "vm", "container");
*app_list.add_apps() = BasicApp("app 2");
*app_list.add_apps() = BasicApp("app 3");
std::string app_id_1 = GenerateAppId("app 1", "vm", "container");
std::string app_id_2 = GenerateAppId("app 2", "vm", "container");
std::string app_id_3 = GenerateAppId("app 3", "vm", "container");
std::string app_id_4 = GenerateAppId("app 4", "vm", "container");
Observer observer;
service()->AddObserver(&observer);
EXPECT_CALL(observer,
OnRegistryUpdated(
service(), testing::IsEmpty(), testing::IsEmpty(),
testing::UnorderedElementsAre(app_id_1, app_id_2, app_id_3)));
service()->UpdateApplicationList(app_list);
// Rename desktop file for "app 2" to "app 4" (deletion+insertion)
app_list.mutable_apps(1)->set_desktop_file_id("app 4");
// Rename name for "app 3" to "banana"
app_list.mutable_apps(2)->mutable_name()->mutable_values(0)->set_value(
"banana");
EXPECT_CALL(observer,
OnRegistryUpdated(service(), testing::ElementsAre(app_id_3),
testing::ElementsAre(app_id_2),
testing::ElementsAre(app_id_4)));
service()->UpdateApplicationList(app_list);
}
TEST_F(CrostiniRegistryServiceTest, InstallAndLaunchTime) {
ApplicationList app_list = BasicAppList("app", "vm", "container");
std::string app_id = GenerateAppId("app", "vm", "container");
test_clock_.Advance(base::TimeDelta::FromHours(1));
Observer observer;
service()->AddObserver(&observer);
EXPECT_CALL(observer, OnRegistryUpdated(service(), testing::IsEmpty(),
testing::IsEmpty(),
testing::ElementsAre(app_id)));
service()->UpdateApplicationList(app_list);
auto result = service()->GetRegistration(app_id);
base::Time install_time = test_clock_.Now();
EXPECT_EQ(result->install_time, install_time);
EXPECT_EQ(result->last_launch_time, base::Time());
// UpdateApplicationList with nothing changed. Times shouldn't be updated and
// the observer shouldn't fire.
test_clock_.Advance(base::TimeDelta::FromHours(1));
EXPECT_CALL(observer, OnRegistryUpdated(_, _, _, _)).Times(0);
service()->UpdateApplicationList(app_list);
result = service()->GetRegistration(app_id);
EXPECT_EQ(result->install_time, install_time);
EXPECT_EQ(result->last_launch_time, base::Time());
// Launch the app
test_clock_.Advance(base::TimeDelta::FromHours(1));
service()->AppLaunched(app_id);
result = service()->GetRegistration(app_id);
EXPECT_EQ(result->install_time, install_time);
EXPECT_EQ(result->last_launch_time,
base::Time() + base::TimeDelta::FromHours(3));
// The install time shouldn't change if fields change.
test_clock_.Advance(base::TimeDelta::FromHours(1));
app_list.mutable_apps(0)->set_no_display(true);
EXPECT_CALL(observer,
OnRegistryUpdated(service(), testing::ElementsAre(app_id),
testing::IsEmpty(), testing::IsEmpty()));
service()->UpdateApplicationList(app_list);
result = service()->GetRegistration(app_id);
EXPECT_EQ(result->install_time, install_time);
EXPECT_EQ(result->last_launch_time,
base::Time() + base::TimeDelta::FromHours(3));
}
// Test that UpdateApplicationList doesn't clobber apps from different VMs or
// containers.
TEST_F(CrostiniRegistryServiceTest, MultipleContainers) {
service()->UpdateApplicationList(BasicAppList("app", "vm 1", "container 1"));
service()->UpdateApplicationList(BasicAppList("app", "vm 1", "container 2"));
service()->UpdateApplicationList(BasicAppList("app", "vm 2", "container 1"));
std::string app_id_1 = GenerateAppId("app", "vm 1", "container 1");
std::string app_id_2 = GenerateAppId("app", "vm 1", "container 2");
std::string app_id_3 = GenerateAppId("app", "vm 2", "container 1");
EXPECT_THAT(service()->GetRegisteredAppIds(),
testing::UnorderedElementsAre(app_id_1, app_id_2, app_id_3,
kCrostiniTerminalId));
// Clobber app_id_2
service()->UpdateApplicationList(
BasicAppList("app 2", "vm 1", "container 2"));
std::string new_app_id = GenerateAppId("app 2", "vm 1", "container 2");
EXPECT_THAT(service()->GetRegisteredAppIds(),
testing::UnorderedElementsAre(app_id_1, app_id_3, new_app_id,
kCrostiniTerminalId));
}
// Test that ClearApplicationList works, and only removes apps from the
// specified container.
TEST_F(CrostiniRegistryServiceTest, ClearApplicationList) {
service()->UpdateApplicationList(BasicAppList("app", "vm 1", "container 1"));
service()->UpdateApplicationList(BasicAppList("app", "vm 1", "container 2"));
ApplicationList app_list = BasicAppList("app", "vm 2", "container 1");
*app_list.add_apps() = BasicApp("app 2");
service()->UpdateApplicationList(app_list);
std::string app_id_1 = GenerateAppId("app", "vm 1", "container 1");
std::string app_id_2 = GenerateAppId("app", "vm 1", "container 2");
std::string app_id_3 = GenerateAppId("app", "vm 2", "container 1");
std::string app_id_4 = GenerateAppId("app 2", "vm 2", "container 1");
EXPECT_THAT(service()->GetRegisteredAppIds(),
testing::UnorderedElementsAre(app_id_1, app_id_2, app_id_3,
app_id_4, kCrostiniTerminalId));
service()->ClearApplicationList("vm 2", "container 1");
EXPECT_THAT(
service()->GetRegisteredAppIds(),
testing::UnorderedElementsAre(app_id_1, app_id_2, kCrostiniTerminalId));
}
TEST_F(CrostiniRegistryServiceTest, GetCrostiniAppIdNoStartupID) {
ApplicationList app_list = BasicAppList("app", "vm", "container");
*app_list.add_apps() = BasicApp("cool.app");
*app_list.add_apps() = BasicApp("super");
service()->UpdateApplicationList(app_list);
service()->UpdateApplicationList(BasicAppList("super", "vm 2", "container"));
EXPECT_THAT(service()->GetRegisteredAppIds(), testing::SizeIs(5));
EXPECT_EQ(
service()->GetCrostiniShelfAppId(WindowIdForWMClass("App"), nullptr),
GenerateAppId("app", "vm", "container"));
EXPECT_EQ(
service()->GetCrostiniShelfAppId(WindowIdForWMClass("cool.app"), nullptr),
GenerateAppId("cool.app", "vm", "container"));
EXPECT_EQ(
service()->GetCrostiniShelfAppId(WindowIdForWMClass("super"), nullptr),
"crostini:" + WindowIdForWMClass("super"));
EXPECT_EQ(service()->GetCrostiniShelfAppId(
"org.chromium.termina.wmclientleader.1234", nullptr),
"crostini:org.chromium.termina.wmclientleader.1234");
EXPECT_EQ(service()->GetCrostiniShelfAppId("org.chromium.termina.xid.654321",
nullptr),
"crostini:org.chromium.termina.xid.654321");
EXPECT_EQ(service()->GetCrostiniShelfAppId("cool.app", nullptr),
GenerateAppId("cool.app", "vm", "container"));
EXPECT_EQ(service()->GetCrostiniShelfAppId("fancy.app", nullptr),
"crostini:fancy.app");
EXPECT_EQ(service()->GetCrostiniShelfAppId("org.chromium.arc.h", nullptr),
std::string());
}
TEST_F(CrostiniRegistryServiceTest, GetCrostiniAppIdStartupWMClass) {
ApplicationList app_list = BasicAppList("app", "vm", "container");
app_list.mutable_apps(0)->set_startup_wm_class("app_start");
*app_list.add_apps() = BasicApp("app2");
*app_list.add_apps() = BasicApp("app3");
app_list.mutable_apps(1)->set_startup_wm_class("app2");
app_list.mutable_apps(2)->set_startup_wm_class("app2");
service()->UpdateApplicationList(app_list);
EXPECT_THAT(service()->GetRegisteredAppIds(), testing::SizeIs(4));
EXPECT_EQ(service()->GetCrostiniShelfAppId(WindowIdForWMClass("app_start"),
nullptr),
GenerateAppId("app", "vm", "container"));
EXPECT_EQ(
service()->GetCrostiniShelfAppId(WindowIdForWMClass("app2"), nullptr),
"crostini:" + WindowIdForWMClass("app2"));
}
TEST_F(CrostiniRegistryServiceTest, GetCrostiniAppIdStartupNotify) {
ApplicationList app_list = BasicAppList("app", "vm", "container");
app_list.mutable_apps(0)->set_startup_notify(true);
*app_list.add_apps() = BasicApp("app2");
service()->UpdateApplicationList(app_list);
std::string startup_id = "app";
EXPECT_EQ(service()->GetCrostiniShelfAppId("whatever", &startup_id),
GenerateAppId("app", "vm", "container"));
startup_id = "app2";
EXPECT_EQ(service()->GetCrostiniShelfAppId("whatever", &startup_id),
"crostini:whatever");
}
TEST_F(CrostiniRegistryServiceTest, GetCrostiniAppIdName) {
ApplicationList app_list = BasicAppList("app", "vm", "container");
*app_list.add_apps() = BasicApp("app2", "name2");
service()->UpdateApplicationList(app_list);
EXPECT_EQ(
service()->GetCrostiniShelfAppId(WindowIdForWMClass("name2"), nullptr),
GenerateAppId("app2", "vm", "container"));
}
} // namespace crostini
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
4dfecb155d67103eb9a19a79731096b895343c4d | d27ea19257497dec0988ebeb18b65ef9c9d9b911 | /branches/Emma/mezzo_lib/src/route.cpp | df00963338a3d9524c27781e97ffd213aec999ff | [] | no_license | burghout/mezzo | 4e11407b4b6a932bdc6b63ce8935f0c4f0918c51 | f0ac1ec6eb271ca8100ff6d97125c6b18413463f | refs/heads/busmezzo_test | 2022-09-28T01:36:30.802861 | 2019-02-11T17:42:26 | 2019-02-11T17:42:26 | 24,588,881 | 2 | 2 | null | 2020-11-30T14:11:40 | 2014-09-29T09:48:42 | C++ | UTF-8 | C++ | false | false | 9,531 | cpp | #include "route.h"
#include <algorithm>
#include <math.h>
#include "parameters.h"
// TEMPORARY EMMAROUTES
std::ofstream rroutes("realized_routes.txt"); // for all route debugging output
template<class T>
struct compare
{
compare(int id_):id(id_) {}
bool operator () (T* thing)
{
return (thing->get_id()==id);
}
int id;
};
Route::Route(const int id_, Origin* const origin_, Destination* const destination_, vector <Link*> & links_): id(id_), origin(origin_), destination(destination_),sumcost(0.0)
{
last_calc_time=0.0;
links=links_;
vector <Link*>::iterator iter = links.begin();
for (iter; iter < links.end(); iter++)
{
Link* link=(*iter);
link->register_route(this);
// linkmap [link->get_id()]=link;
}
#ifdef _DEBUG_ROUTE
eout << "new route: rid,oid,did : lid* " << id << ","<< origin->get_id();
eout << "," << destination->get_id() << " : ";
for (vector<Link*>::iterator iter=links.begin();iter<links.end();iter++)
{
eout << (*iter)->get_id() << " ";
}
eout << endl;
#endif // _DEBUG_ROUTE
routeflows=vector <int> (theParameters->od_loadtimes.size(),0);
}
Route::Route(const int id_, Route* const route, const vector<Link*> & links_): id(id_)
{
sumcost=0.0;
last_calc_time=0.0;
links=links_;
origin=route->get_origin();
destination=route->get_destination();
vector<Link*> oldlinks=route->get_links();
vector<Link*>::iterator stop=(find_if(oldlinks.begin(), oldlinks.end(), compare <Link> ((links_.front())->get_id()) ));
if (stop > oldlinks.begin() )
{
stop--;
for (vector<Link*>::iterator iter=stop;iter !=oldlinks.begin(); iter--)
links.insert(links.begin(),(*iter));
}
// int me=(links.front())->get_id();
if ( (links.front())->get_id() != (oldlinks.front())->get_id() )
links.insert(links.begin(), oldlinks.front() );
routeflows=vector <int> (theParameters->od_loadtimes.size(),0);
}
void Route::reset()
{
sumcost=0.0;
last_calc_time=0.0;
prev_routeflows=routeflows;
routeflows=vector <int> (theParameters->od_loadtimes.size(),0);
}
const ODVal Route::get_oid_did() const
{return ODVal(origin->get_id(), destination->get_id());}
const int Route::get_od_period(const double time) const
{
int i = 0;
int max_i=theParameters->od_loadtimes.size();
for (i; i < max_i ; i++)
{
if (theParameters->od_loadtimes[i] > time)
return (i-1);
}
return max_i-1;
}
const int Route::get_abs_diff_routeflows() const
{
int abs_diff=0;
int i = 0;
int max_i=min (routeflows.size(), prev_routeflows.size());
for (i ;i < max_i; i++)
{
abs_diff += abs(routeflows [i]-prev_routeflows [i]);
}
return abs_diff;
}
const int Route::get_sum_prev_routeflows() const
{
int sum=0;
int i = 0;
int max_i= prev_routeflows.size();
for (i ;i < max_i; i++)
{
sum+= prev_routeflows [i];
}
return sum;
}
const int Route::get_sum_routeflows() const
{
int sum=0;
int i = 0;
int max_i= routeflows.size();
for (i ;i < max_i; i++)
{
sum+= routeflows [i];
}
return sum;
}
void Route::register_veh_departure(const double time)
{
int period = get_od_period(time);
routeflows [period] = routeflows [period] +1;
}
const bool Route::check (const int oid, const int did) const
{ return ( (origin->get_id()==oid) && (destination->get_id()==did) );}
const bool Route::less_than (const Route*const route) const
// returns true if origin_id of this route is less than origin_id of the "route" parameter, or
// if the origins are equal, if the destination_id is less than that of the "route" parameter provided
{
int id_or1=origin->get_id();
int id_or2= route->get_origin()->get_id();
if (id_or1 > id_or2 )
return false;
else
{
if (id_or1 < id_or2)
return true;
else // same origins
{
if (destination ->get_id() >= route->get_destination()->get_id())
return false;
else
return true;
}
}
}
const vector<Link*> Route::get_upstream_links(const int link_id)const
{
return (vector <Link*> (links.begin(), find_if (links.begin(),links.end(), compare <Link> (link_id))));
}
const vector<Link*> Route::get_downstream_links(const int link_id) const
{
return (vector <Link*> (find_if (links.begin(),links.end(), compare <Link> (link_id)),links.end() ));
}
void Route::set_selected(const bool selected) // sets the links' selected attribute
{
vector <Link*>::iterator iter = links.begin();
for (iter;iter < links.end(); iter++)
{
(*iter)->set_selected(selected);
}
}
#ifndef _NO_GUI
void Route::set_selected_color(const QColor & selcolor)
{
vector <Link*>::iterator iter = links.begin();
for (iter;iter < links.end(); iter++)
{
(*iter)->set_selected_color(selcolor);
}
}
#endif
const bool Route::equals (const Route& route) const // returns true if same route
{
ODVal val=route.get_oid_did();
if ((val.first != origin->get_id()) || (val.second != destination->get_id()))
return false;
else
return ( (route.get_links())==(get_links()) );
}
Link* const Route::nextlink(Link* const currentlink) const
{
vector<Link*>::const_iterator iter=find(links.begin(), links.end(), currentlink);
iter++;
if (iter<links.end())
{
return *iter;
}
eout << "Route::nextlink: error! there is no next link! Current link " << currentlink->get_id() << endl;
return NULL;
}
vector <Link*>::const_iterator Route::nextlink_iter(Link* const currentlink)
{
vector<Link*>::const_iterator iter=find(links.begin(), links.end(), currentlink);
iter++;
if (iter==links.end())
eout << "Route::nextlink_iter: error! there is no next link! route id "<< id << ", current link " << currentlink->get_id() << endl;
return iter;
}
const bool Route::has_link(const int lid) const
{
return ( (find_if (links.begin(),links.end(), compare <Link> (lid))) < links.end() ); // the link exists
/* if (linkmap.count(lid))
return true;
else
return false;*/
}
const bool Route::has_link_after(const int lid, const int curr_lid) const
{
vector <Link*>:: const_iterator iter =(find_if (links.begin(),links.end(), compare <Link> (curr_lid))) ; // find curr_lid
iter++;
if (iter < links.end())
return ((find_if (iter,links.end(), compare <Link> (lid))) < links.end() ); // the link lid exists after curr_lid
return false;
}
const double Route::cost(const double time)
{
if ((sumcost>0.0) & (last_calc_time+theParameters->update_interval_routes < time))
return sumcost;// this means the cost has already been calculated once this update interval, return cached value.
else
{
double temp_time=time;
last_calc_time=time;
for(vector<Link*>::iterator iter=links.begin();iter<links.end();iter++)
{
#ifdef _DISTANCE_BASED
sumcost+=(*iter)->get_length();
#else
LinkTime* lt=(*iter)->get_histtimes();
if (lt)
temp_time+=lt->cost(temp_time);
else
temp_time+=(*iter)->get_freeflow_time();
//sumcost+=(*iter)->get_hist_time();
#endif //_DISTANCE_BASED
}
sumcost=temp_time-time;
return sumcost;
}
}
const double Route::utility (const double time)
{
#ifdef _MULTINOMIAL_LOGIT
return exp(theParameters->mnl_theta*(cost(time)) );
#else
return pow (cost(time),theParameters->kirchoff_alpha);
#endif
}
/**
* compute the length of the route
**/
const int Route::computeRouteLength() const
{
int routelength=0;
for(unsigned i=0; i<links.size();i++)
routelength+=links[i]->get_length();
return routelength;
}
void Route::write(ostream& out) const
{
out << "{ " << id << " " << origin->get_id() << " " << destination->get_id() << " " << links.size() << "{";
for (vector <Link*>::const_iterator iter=links.begin(); iter<links.end();iter++)
{
out <<" " <<(*iter)->get_id();
}
out << "} }" << endl;
}
void Route::write_routeflows(ostream &out) const
{
out << id << '\t' ;
vector <int>::const_iterator iter;
for ( iter = routeflows.begin(); iter != routeflows.end(); iter++)
{
out << (*iter) << '\t' ;
}
out << endl;
}
// EmmaRoute
EmmaRoute::EmmaRoute(const int id_, Origin*const origin_, Destination* const destination_, vector <Link*> & links_) :
Route (id_, origin_, destination_, links_) {links.push_back(origin_->get_links().front());} // EMMAROUTE !!! TO FIX FOR OTHER NETWORKS!!!
/*
Link* const EmmaRoute::nextlink(Link* const currentlink) const
{
return NULL;
}*/
/*vector <Link*>::const_iterator EmmaRoute::nextlink_iter(Link* const currentlink) //!< returns const_iterator to the next link of the route, given currentlink.
{
vector<Link*>::const_iterator iter=find(links.begin(), links.end(), currentlink);
return ++iter;
}*/
void EmmaRoute::generate_nextlink(Link* const currentlink)
{
if (currentlink->get_out_node_id() == get_destination()->get_id())
{
this->write(rroutes);
return;
}
vector<Link*>::const_iterator iter=find(links.begin(), links.end(), currentlink);
int cur_id=currentlink->get_id();
int nextlinkid= probas.sample_nextlink(cur_id);
if (probas.linkmap.count(nextlinkid))
links.push_back(probas.linkmap [nextlinkid]);
else
eout << "EmmaRoute::generate_nextlink Error: no link with id " << nextlinkid << " found from current link " << cur_id << endl;
}
void Route::generate_nextlink(Link* const currentlink) // Dummy
{} | [
"wilco@be8bedfb-b93a-dc11-ad5b-00609709f61e"
] | wilco@be8bedfb-b93a-dc11-ad5b-00609709f61e |
baf84e8d30d6cdba661d528de20910139169641d | ffe36d7138244879c29b33547e0102a6a46bf8e6 | /third_party/protobuf/src/google/protobuf/extension_set_heavy.cc | 78134c59b37c22d71020732e5a70cb35b6fb64f5 | [] | no_license | randydom/webrtc_port | cba6ec533acda026556ba5737e5589f2864b908a | a9d19fa643dbb684308ae1320c71d3207965df47 | refs/heads/master | 2020-08-21T14:17:52.676597 | 2016-01-26T01:18:09 | 2016-01-26T01:18:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,182 | cc | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// Contains methods defined in extension_set.h which cannot be part of the
// lite library because they use descriptors or reflection.
#include <google/protobuf/extension_set.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/wire_format_lite_inl.h>
namespace google {
namespace protobuf {
namespace internal {
// Implementation of ExtensionFinder which finds extensions in a given
// DescriptorPool, using the given MessageFactory to construct sub-objects.
// This class is implemented in extension_set_heavy.cc.
class DescriptorPoolExtensionFinder : public ExtensionFinder {
public:
DescriptorPoolExtensionFinder(const DescriptorPool* pool,
MessageFactory* factory,
const Descriptor* containing_type)
: pool_(pool), factory_(factory), containing_type_(containing_type) {}
virtual ~DescriptorPoolExtensionFinder() {}
virtual bool Find(int number, ExtensionInfo* output);
private:
const DescriptorPool* pool_;
MessageFactory* factory_;
const Descriptor* containing_type_;
};
void ExtensionSet::AppendToList(const Descriptor* containing_type,
const DescriptorPool* pool,
vector<const FieldDescriptor*>* output) const {
for (map<int, Extension>::const_iterator iter = extensions_.begin();
iter != extensions_.end(); ++iter) {
bool has = false;
if (iter->second.is_repeated) {
has = iter->second.GetSize() > 0;
} else {
has = !iter->second.is_cleared;
}
if (has) {
// TODO(kenton): Looking up each field by number is somewhat unfortunate.
// Is there a better way? The problem is that descriptors are lazily-
// initialized, so they might not even be constructed until
// AppendToList() is called.
if (iter->second.descriptor == NULL) {
output->push_back(pool->FindExtensionByNumber(
containing_type, iter->first));
} else {
output->push_back(iter->second.descriptor);
}
}
}
}
inline FieldDescriptor::Type real_type(FieldType type) {
GOOGLE_DCHECK(type > 0 && type <= FieldDescriptor::MAX_TYPE);
return static_cast<FieldDescriptor::Type>(type);
}
inline FieldDescriptor::CppType cpp_type(FieldType type) {
return FieldDescriptor::TypeToCppType(
static_cast<FieldDescriptor::Type>(type));
}
#define GOOGLE_DCHECK_TYPE(EXTENSION, LABEL, CPPTYPE) \
GOOGLE_DCHECK_EQ((EXTENSION).is_repeated ? FieldDescriptor::LABEL_REPEATED \
: FieldDescriptor::LABEL_OPTIONAL, \
FieldDescriptor::LABEL_##LABEL); \
GOOGLE_DCHECK_EQ(cpp_type((EXTENSION).type), FieldDescriptor::CPPTYPE_##CPPTYPE)
const MessageLite& ExtensionSet::GetMessage(int number,
const Descriptor* message_type,
MessageFactory* factory) const {
map<int, Extension>::const_iterator iter = extensions_.find(number);
if (iter == extensions_.end() || iter->second.is_cleared) {
// Not present. Return the default value.
return *factory->GetPrototype(message_type);
} else {
GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE);
return *iter->second.message_value;
}
}
MessageLite* ExtensionSet::MutableMessage(const FieldDescriptor* descriptor,
MessageFactory* factory) {
Extension* extension;
if (MaybeNewExtension(descriptor->number(), descriptor, &extension)) {
extension->type = descriptor->type();
GOOGLE_DCHECK_EQ(cpp_type(extension->type), FieldDescriptor::CPPTYPE_MESSAGE);
extension->is_repeated = false;
extension->is_packed = false;
const MessageLite* prototype =
factory->GetPrototype(descriptor->message_type());
GOOGLE_CHECK(prototype != NULL);
extension->message_value = prototype->New();
} else {
GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE);
}
extension->is_cleared = false;
return extension->message_value;
}
MessageLite* ExtensionSet::AddMessage(const FieldDescriptor* descriptor,
MessageFactory* factory) {
Extension* extension;
if (MaybeNewExtension(descriptor->number(), descriptor, &extension)) {
extension->type = descriptor->type();
GOOGLE_DCHECK_EQ(cpp_type(extension->type), FieldDescriptor::CPPTYPE_MESSAGE);
extension->is_repeated = true;
extension->repeated_message_value =
new RepeatedPtrField<MessageLite>();
} else {
GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE);
}
// RepeatedPtrField<Message> does not know how to Add() since it cannot
// allocate an abstract object, so we have to be tricky.
MessageLite* result = extension->repeated_message_value
->AddFromCleared<internal::GenericTypeHandler<MessageLite> >();
if (result == NULL) {
const MessageLite* prototype;
if (extension->repeated_message_value->size() == 0) {
prototype = factory->GetPrototype(descriptor->message_type());
GOOGLE_CHECK(prototype != NULL);
} else {
prototype = &extension->repeated_message_value->Get(0);
}
result = prototype->New();
extension->repeated_message_value->AddAllocated(result);
}
return result;
}
static bool ValidateEnumUsingDescriptor(const void* arg, int number) {
return reinterpret_cast<const EnumDescriptor*>(arg)
->FindValueByNumber(number) != NULL;
}
bool DescriptorPoolExtensionFinder::Find(int number, ExtensionInfo* output) {
const FieldDescriptor* extension =
pool_->FindExtensionByNumber(containing_type_, number);
if (extension == NULL) {
return false;
} else {
output->type = extension->type();
output->is_repeated = extension->is_repeated();
output->is_packed = extension->options().packed();
output->descriptor = extension;
if (extension->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
output->message_prototype =
factory_->GetPrototype(extension->message_type());
GOOGLE_CHECK(output->message_prototype != NULL)
<< "Extension factory's GetPrototype() returned NULL for extension: "
<< extension->full_name();
} else if (extension->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
output->enum_validity_check.func = ValidateEnumUsingDescriptor;
output->enum_validity_check.arg = extension->enum_type();
}
return true;
}
}
bool ExtensionSet::ParseFieldHeavy(uint32 tag, io::CodedInputStream* input,
const Message* containing_type,
UnknownFieldSet* unknown_fields) {
FieldSkipper skipper(unknown_fields);
if (input->GetExtensionPool() == NULL) {
GeneratedExtensionFinder finder(containing_type);
return ParseField(tag, input, &finder, &skipper);
} else {
DescriptorPoolExtensionFinder finder(input->GetExtensionPool(),
input->GetExtensionFactory(),
containing_type->GetDescriptor());
return ParseField(tag, input, &finder, &skipper);
}
}
bool ExtensionSet::ParseMessageSetHeavy(io::CodedInputStream* input,
const Message* containing_type,
UnknownFieldSet* unknown_fields) {
FieldSkipper skipper(unknown_fields);
if (input->GetExtensionPool() == NULL) {
GeneratedExtensionFinder finder(containing_type);
return ParseMessageSet(input, &finder, &skipper);
} else {
DescriptorPoolExtensionFinder finder(input->GetExtensionPool(),
input->GetExtensionFactory(),
containing_type->GetDescriptor());
return ParseMessageSet(input, &finder, &skipper);
}
}
int ExtensionSet::SpaceUsedExcludingSelf() const {
int total_size =
extensions_.size() * sizeof(map<int, Extension>::value_type);
for (map<int, Extension>::const_iterator iter = extensions_.begin(),
end = extensions_.end();
iter != end;
++iter) {
total_size += iter->second.SpaceUsedExcludingSelf();
}
return total_size;
}
inline int ExtensionSet::RepeatedMessage_SpaceUsedExcludingSelf(
RepeatedPtrFieldBase* field) {
return field->SpaceUsedExcludingSelf<GenericTypeHandler<Message> >();
}
int ExtensionSet::Extension::SpaceUsedExcludingSelf() const {
int total_size = 0;
if (is_repeated) {
switch (cpp_type(type)) {
#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
case FieldDescriptor::CPPTYPE_##UPPERCASE: \
total_size += sizeof(*repeated_##LOWERCASE##_value) + \
repeated_##LOWERCASE##_value->SpaceUsedExcludingSelf();\
break
HANDLE_TYPE( INT32, int32);
HANDLE_TYPE( INT64, int64);
HANDLE_TYPE( UINT32, uint32);
HANDLE_TYPE( UINT64, uint64);
HANDLE_TYPE( FLOAT, float);
HANDLE_TYPE( DOUBLE, double);
HANDLE_TYPE( BOOL, bool);
HANDLE_TYPE( ENUM, enum);
HANDLE_TYPE( STRING, string);
#undef HANDLE_TYPE
case FieldDescriptor::CPPTYPE_MESSAGE:
// repeated_message_value is actually a RepeatedPtrField<MessageLite>,
// but MessageLite has no SpaceUsed(), so we must directly call
// RepeatedPtrFieldBase::SpaceUsedExcludingSelf() with a different type
// handler.
total_size += sizeof(*repeated_message_value) +
RepeatedMessage_SpaceUsedExcludingSelf(repeated_message_value);
break;
}
} else {
switch (cpp_type(type)) {
case FieldDescriptor::CPPTYPE_STRING:
total_size += sizeof(*string_value) +
StringSpaceUsedExcludingSelf(*string_value);
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
total_size += down_cast<Message*>(message_value)->SpaceUsed();
break;
default:
// No extra storage costs for primitive types.
break;
}
}
return total_size;
}
// The Serialize*ToArray methods are only needed in the heavy library, as
// the lite library only generates SerializeWithCachedSizes.
uint8* ExtensionSet::SerializeWithCachedSizesToArray(
int start_field_number, int end_field_number,
uint8* target) const {
map<int, Extension>::const_iterator iter;
for (iter = extensions_.lower_bound(start_field_number);
iter != extensions_.end() && iter->first < end_field_number;
++iter) {
target = iter->second.SerializeFieldWithCachedSizesToArray(iter->first,
target);
}
return target;
}
uint8* ExtensionSet::SerializeMessageSetWithCachedSizesToArray(
uint8* target) const {
map<int, Extension>::const_iterator iter;
for (iter = extensions_.begin(); iter != extensions_.end(); ++iter) {
target = iter->second.SerializeMessageSetItemWithCachedSizesToArray(
iter->first, target);
}
return target;
}
uint8* ExtensionSet::Extension::SerializeFieldWithCachedSizesToArray(
int number, uint8* target) const {
if (is_repeated) {
if (is_packed) {
if (cached_size == 0) return target;
target = WireFormatLite::WriteTagToArray(number,
WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target);
target = WireFormatLite::WriteInt32NoTagToArray(cached_size, target);
switch (real_type(type)) {
#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \
case FieldDescriptor::TYPE_##UPPERCASE: \
for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \
target = WireFormatLite::Write##CAMELCASE##NoTagToArray( \
repeated_##LOWERCASE##_value->Get(i), target); \
} \
break
HANDLE_TYPE( INT32, Int32, int32);
HANDLE_TYPE( INT64, Int64, int64);
HANDLE_TYPE( UINT32, UInt32, uint32);
HANDLE_TYPE( UINT64, UInt64, uint64);
HANDLE_TYPE( SINT32, SInt32, int32);
HANDLE_TYPE( SINT64, SInt64, int64);
HANDLE_TYPE( FIXED32, Fixed32, uint32);
HANDLE_TYPE( FIXED64, Fixed64, uint64);
HANDLE_TYPE(SFIXED32, SFixed32, int32);
HANDLE_TYPE(SFIXED64, SFixed64, int64);
HANDLE_TYPE( FLOAT, Float, float);
HANDLE_TYPE( DOUBLE, Double, double);
HANDLE_TYPE( BOOL, Bool, bool);
HANDLE_TYPE( ENUM, Enum, enum);
#undef HANDLE_TYPE
case WireFormatLite::TYPE_STRING:
case WireFormatLite::TYPE_BYTES:
case WireFormatLite::TYPE_GROUP:
case WireFormatLite::TYPE_MESSAGE:
GOOGLE_LOG(FATAL) << "Non-primitive types can't be packed.";
break;
}
} else {
switch (real_type(type)) {
#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \
case FieldDescriptor::TYPE_##UPPERCASE: \
for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \
target = WireFormatLite::Write##CAMELCASE##ToArray(number, \
repeated_##LOWERCASE##_value->Get(i), target); \
} \
break
HANDLE_TYPE( INT32, Int32, int32);
HANDLE_TYPE( INT64, Int64, int64);
HANDLE_TYPE( UINT32, UInt32, uint32);
HANDLE_TYPE( UINT64, UInt64, uint64);
HANDLE_TYPE( SINT32, SInt32, int32);
HANDLE_TYPE( SINT64, SInt64, int64);
HANDLE_TYPE( FIXED32, Fixed32, uint32);
HANDLE_TYPE( FIXED64, Fixed64, uint64);
HANDLE_TYPE(SFIXED32, SFixed32, int32);
HANDLE_TYPE(SFIXED64, SFixed64, int64);
HANDLE_TYPE( FLOAT, Float, float);
HANDLE_TYPE( DOUBLE, Double, double);
HANDLE_TYPE( BOOL, Bool, bool);
HANDLE_TYPE( STRING, String, string);
HANDLE_TYPE( BYTES, Bytes, string);
HANDLE_TYPE( ENUM, Enum, enum);
HANDLE_TYPE( GROUP, Group, message);
HANDLE_TYPE( MESSAGE, Message, message);
#undef HANDLE_TYPE
}
}
} else if (!is_cleared) {
switch (real_type(type)) {
#define HANDLE_TYPE(UPPERCASE, CAMELCASE, VALUE) \
case FieldDescriptor::TYPE_##UPPERCASE: \
target = WireFormatLite::Write##CAMELCASE##ToArray( \
number, VALUE, target); \
break
HANDLE_TYPE( INT32, Int32, int32_value);
HANDLE_TYPE( INT64, Int64, int64_value);
HANDLE_TYPE( UINT32, UInt32, uint32_value);
HANDLE_TYPE( UINT64, UInt64, uint64_value);
HANDLE_TYPE( SINT32, SInt32, int32_value);
HANDLE_TYPE( SINT64, SInt64, int64_value);
HANDLE_TYPE( FIXED32, Fixed32, uint32_value);
HANDLE_TYPE( FIXED64, Fixed64, uint64_value);
HANDLE_TYPE(SFIXED32, SFixed32, int32_value);
HANDLE_TYPE(SFIXED64, SFixed64, int64_value);
HANDLE_TYPE( FLOAT, Float, float_value);
HANDLE_TYPE( DOUBLE, Double, double_value);
HANDLE_TYPE( BOOL, Bool, bool_value);
HANDLE_TYPE( STRING, String, *string_value);
HANDLE_TYPE( BYTES, Bytes, *string_value);
HANDLE_TYPE( ENUM, Enum, enum_value);
HANDLE_TYPE( GROUP, Group, *message_value);
HANDLE_TYPE( MESSAGE, Message, *message_value);
#undef HANDLE_TYPE
}
}
return target;
}
uint8* ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizesToArray(
int number,
uint8* target) const {
if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) {
// Not a valid MessageSet extension, but serialize it the normal way.
GOOGLE_LOG(WARNING) << "Invalid message set extension.";
return SerializeFieldWithCachedSizesToArray(number, target);
}
if (is_cleared) return target;
// Start group.
target = io::CodedOutputStream::WriteTagToArray(
WireFormatLite::kMessageSetItemStartTag, target);
// Write type ID.
target = WireFormatLite::WriteUInt32ToArray(
WireFormatLite::kMessageSetTypeIdNumber, number, target);
// Write message.
target = WireFormatLite::WriteMessageToArray(
WireFormatLite::kMessageSetMessageNumber, *message_value, target);
// End group.
target = io::CodedOutputStream::WriteTagToArray(
WireFormatLite::kMessageSetItemEndTag, target);
return target;
}
} // namespace internal
} // namespace protobuf
} // namespace google
| [
"wonktnodiq@gmail.com"
] | wonktnodiq@gmail.com |
31b30f504f5cc8e48b7b712e9ea0416d40ae70f5 | 70d56762752de85a35fbb0aae0f583695472ba10 | /lib/deps/v8/src/arm/code-stubs-arm.cc | 4eb08a1eebb0d7b0145166244f28414b497f604c | [
"MIT",
"BSD-3-Clause",
"bzip2-1.0.6"
] | permissive | tempbottle/redis-v8 | e6c15046383ddd169c1a598cf1b0f34ffe389ce3 | a671b7fc0028241826373e40ddf1f7fbe90d1956 | refs/heads/master | 2021-01-15T20:44:06.403155 | 2013-12-18T22:26:07 | 2013-12-18T22:26:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220,215 | cc | // Copyright 2012 the V8 project authors. 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#if V8_TARGET_ARCH_ARM
#include "bootstrapper.h"
#include "code-stubs.h"
#include "regexp-macro-assembler.h"
#include "stub-cache.h"
namespace v8 {
namespace internal {
void FastNewClosureStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r2 };
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
Runtime::FunctionForId(Runtime::kNewClosureFromStubFailure)->entry;
}
void ToNumberStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r0 };
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ = NULL;
}
void NumberToStringStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r0 };
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
Runtime::FunctionForId(Runtime::kNumberToString)->entry;
}
void FastCloneShallowArrayStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r3, r2, r1 };
descriptor->register_param_count_ = 3;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
Runtime::FunctionForId(Runtime::kCreateArrayLiteralStubBailout)->entry;
}
void FastCloneShallowObjectStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r3, r2, r1, r0 };
descriptor->register_param_count_ = 4;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
Runtime::FunctionForId(Runtime::kCreateObjectLiteral)->entry;
}
void CreateAllocationSiteStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r2 };
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ = NULL;
}
void KeyedLoadFastElementStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r1, r0 };
descriptor->register_param_count_ = 2;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
FUNCTION_ADDR(KeyedLoadIC_MissFromStubFailure);
}
void KeyedLoadDictionaryElementStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r1, r0 };
descriptor->register_param_count_ = 2;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
FUNCTION_ADDR(KeyedLoadIC_MissFromStubFailure);
}
void LoadFieldStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r0 };
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ = NULL;
}
void KeyedLoadFieldStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r1 };
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ = NULL;
}
void KeyedArrayCallStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r2 };
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers;
descriptor->continuation_type_ = TAIL_CALL_CONTINUATION;
descriptor->handler_arguments_mode_ = PASS_ARGUMENTS;
descriptor->deoptimization_handler_ =
FUNCTION_ADDR(KeyedCallIC_MissFromStubFailure);
}
void KeyedStoreFastElementStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r2, r1, r0 };
descriptor->register_param_count_ = 3;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
FUNCTION_ADDR(KeyedStoreIC_MissFromStubFailure);
}
void TransitionElementsKindStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r0, r1 };
descriptor->register_param_count_ = 2;
descriptor->register_params_ = registers;
Address entry =
Runtime::FunctionForId(Runtime::kTransitionElementsKind)->entry;
descriptor->deoptimization_handler_ = FUNCTION_ADDR(entry);
}
void CompareNilICStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r0 };
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
FUNCTION_ADDR(CompareNilIC_Miss);
descriptor->SetMissHandler(
ExternalReference(IC_Utility(IC::kCompareNilIC_Miss), isolate));
}
void BinaryOpICStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r1, r0 };
descriptor->register_param_count_ = 2;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ = FUNCTION_ADDR(BinaryOpIC_Miss);
descriptor->SetMissHandler(
ExternalReference(IC_Utility(IC::kBinaryOpIC_Miss), isolate));
}
static void InitializeArrayConstructorDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor,
int constant_stack_parameter_count) {
// register state
// r0 -- number of arguments
// r1 -- function
// r2 -- type info cell with elements kind
static Register registers_variable_args[] = { r1, r2, r0 };
static Register registers_no_args[] = { r1, r2 };
if (constant_stack_parameter_count == 0) {
descriptor->register_param_count_ = 2;
descriptor->register_params_ = registers_no_args;
} else {
// stack param count needs (constructor pointer, and single argument)
descriptor->handler_arguments_mode_ = PASS_ARGUMENTS;
descriptor->stack_parameter_count_ = r0;
descriptor->register_param_count_ = 3;
descriptor->register_params_ = registers_variable_args;
}
descriptor->hint_stack_parameter_count_ = constant_stack_parameter_count;
descriptor->function_mode_ = JS_FUNCTION_STUB_MODE;
descriptor->deoptimization_handler_ =
Runtime::FunctionForId(Runtime::kArrayConstructor)->entry;
}
static void InitializeInternalArrayConstructorDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor,
int constant_stack_parameter_count) {
// register state
// r0 -- number of arguments
// r1 -- constructor function
static Register registers_variable_args[] = { r1, r0 };
static Register registers_no_args[] = { r1 };
if (constant_stack_parameter_count == 0) {
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers_no_args;
} else {
// stack param count needs (constructor pointer, and single argument)
descriptor->handler_arguments_mode_ = PASS_ARGUMENTS;
descriptor->stack_parameter_count_ = r0;
descriptor->register_param_count_ = 2;
descriptor->register_params_ = registers_variable_args;
}
descriptor->hint_stack_parameter_count_ = constant_stack_parameter_count;
descriptor->function_mode_ = JS_FUNCTION_STUB_MODE;
descriptor->deoptimization_handler_ =
Runtime::FunctionForId(Runtime::kInternalArrayConstructor)->entry;
}
void ArrayNoArgumentConstructorStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
InitializeArrayConstructorDescriptor(isolate, descriptor, 0);
}
void ArraySingleArgumentConstructorStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
InitializeArrayConstructorDescriptor(isolate, descriptor, 1);
}
void ArrayNArgumentsConstructorStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
InitializeArrayConstructorDescriptor(isolate, descriptor, -1);
}
void ToBooleanStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r0 };
descriptor->register_param_count_ = 1;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
FUNCTION_ADDR(ToBooleanIC_Miss);
descriptor->SetMissHandler(
ExternalReference(IC_Utility(IC::kToBooleanIC_Miss), isolate));
}
void InternalArrayNoArgumentConstructorStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
InitializeInternalArrayConstructorDescriptor(isolate, descriptor, 0);
}
void InternalArraySingleArgumentConstructorStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
InitializeInternalArrayConstructorDescriptor(isolate, descriptor, 1);
}
void InternalArrayNArgumentsConstructorStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
InitializeInternalArrayConstructorDescriptor(isolate, descriptor, -1);
}
void StoreGlobalStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r1, r2, r0 };
descriptor->register_param_count_ = 3;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
FUNCTION_ADDR(StoreIC_MissFromStubFailure);
}
void ElementsTransitionAndStoreStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r0, r3, r1, r2 };
descriptor->register_param_count_ = 4;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
FUNCTION_ADDR(ElementsTransitionAndStoreIC_Miss);
}
void NewStringAddStub::InitializeInterfaceDescriptor(
Isolate* isolate,
CodeStubInterfaceDescriptor* descriptor) {
static Register registers[] = { r1, r0 };
descriptor->register_param_count_ = 2;
descriptor->register_params_ = registers;
descriptor->deoptimization_handler_ =
Runtime::FunctionForId(Runtime::kStringAdd)->entry;
}
#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) {
// Update the static counter each time a new code stub is generated.
Isolate* isolate = masm->isolate();
isolate->counters()->code_stubs()->Increment();
CodeStubInterfaceDescriptor* descriptor = GetInterfaceDescriptor(isolate);
int param_count = descriptor->register_param_count_;
{
// Call the runtime system in a fresh internal frame.
FrameScope scope(masm, StackFrame::INTERNAL);
ASSERT(descriptor->register_param_count_ == 0 ||
r0.is(descriptor->register_params_[param_count - 1]));
// Push arguments
for (int i = 0; i < param_count; ++i) {
__ push(descriptor->register_params_[i]);
}
ExternalReference miss = descriptor->miss_handler();
__ CallExternalReference(miss, descriptor->register_param_count_);
}
__ Ret();
}
void FastNewContextStub::Generate(MacroAssembler* masm) {
// Try to allocate the context in new space.
Label gc;
int length = slots_ + Context::MIN_CONTEXT_SLOTS;
// Attempt to allocate the context in new space.
__ Allocate(FixedArray::SizeFor(length), r0, r1, r2, &gc, TAG_OBJECT);
// Load the function from the stack.
__ ldr(r3, MemOperand(sp, 0));
// Set up the object header.
__ LoadRoot(r1, Heap::kFunctionContextMapRootIndex);
__ mov(r2, Operand(Smi::FromInt(length)));
__ str(r2, FieldMemOperand(r0, FixedArray::kLengthOffset));
__ str(r1, FieldMemOperand(r0, HeapObject::kMapOffset));
// Set up the fixed slots, copy the global object from the previous context.
__ ldr(r2, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
__ mov(r1, Operand(Smi::FromInt(0)));
__ str(r3, MemOperand(r0, Context::SlotOffset(Context::CLOSURE_INDEX)));
__ str(cp, MemOperand(r0, Context::SlotOffset(Context::PREVIOUS_INDEX)));
__ str(r1, MemOperand(r0, Context::SlotOffset(Context::EXTENSION_INDEX)));
__ str(r2, MemOperand(r0, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
// Initialize the rest of the slots to undefined.
__ LoadRoot(r1, Heap::kUndefinedValueRootIndex);
for (int i = Context::MIN_CONTEXT_SLOTS; i < length; i++) {
__ str(r1, MemOperand(r0, Context::SlotOffset(i)));
}
// Remove the on-stack argument and return.
__ mov(cp, r0);
__ pop();
__ Ret();
// Need to collect. Call into runtime system.
__ bind(&gc);
__ TailCallRuntime(Runtime::kNewFunctionContext, 1, 1);
}
void FastNewBlockContextStub::Generate(MacroAssembler* masm) {
// Stack layout on entry:
//
// [sp]: function.
// [sp + kPointerSize]: serialized scope info
// Try to allocate the context in new space.
Label gc;
int length = slots_ + Context::MIN_CONTEXT_SLOTS;
__ Allocate(FixedArray::SizeFor(length), r0, r1, r2, &gc, TAG_OBJECT);
// Load the function from the stack.
__ ldr(r3, MemOperand(sp, 0));
// Load the serialized scope info from the stack.
__ ldr(r1, MemOperand(sp, 1 * kPointerSize));
// Set up the object header.
__ LoadRoot(r2, Heap::kBlockContextMapRootIndex);
__ str(r2, FieldMemOperand(r0, HeapObject::kMapOffset));
__ mov(r2, Operand(Smi::FromInt(length)));
__ str(r2, FieldMemOperand(r0, FixedArray::kLengthOffset));
// If this block context is nested in the native context we get a smi
// sentinel instead of a function. The block context should get the
// canonical empty function of the native context as its closure which
// we still have to look up.
Label after_sentinel;
__ JumpIfNotSmi(r3, &after_sentinel);
if (FLAG_debug_code) {
__ cmp(r3, Operand::Zero());
__ Assert(eq, kExpected0AsASmiSentinel);
}
__ ldr(r3, GlobalObjectOperand());
__ ldr(r3, FieldMemOperand(r3, GlobalObject::kNativeContextOffset));
__ ldr(r3, ContextOperand(r3, Context::CLOSURE_INDEX));
__ bind(&after_sentinel);
// Set up the fixed slots, copy the global object from the previous context.
__ ldr(r2, ContextOperand(cp, Context::GLOBAL_OBJECT_INDEX));
__ str(r3, ContextOperand(r0, Context::CLOSURE_INDEX));
__ str(cp, ContextOperand(r0, Context::PREVIOUS_INDEX));
__ str(r1, ContextOperand(r0, Context::EXTENSION_INDEX));
__ str(r2, ContextOperand(r0, Context::GLOBAL_OBJECT_INDEX));
// Initialize the rest of the slots to the hole value.
__ LoadRoot(r1, Heap::kTheHoleValueRootIndex);
for (int i = 0; i < slots_; i++) {
__ str(r1, ContextOperand(r0, i + Context::MIN_CONTEXT_SLOTS));
}
// Remove the on-stack argument and return.
__ mov(cp, r0);
__ add(sp, sp, Operand(2 * kPointerSize));
__ Ret();
// Need to collect. Call into runtime system.
__ bind(&gc);
__ TailCallRuntime(Runtime::kPushBlockContext, 2, 1);
}
// Takes a Smi and converts to an IEEE 64 bit floating point value in two
// registers. The format is 1 sign bit, 11 exponent bits (biased 1023) and
// 52 fraction bits (20 in the first word, 32 in the second). Zeros is a
// scratch register. Destroys the source register. No GC occurs during this
// stub so you don't have to set up the frame.
class ConvertToDoubleStub : public PlatformCodeStub {
public:
ConvertToDoubleStub(Register result_reg_1,
Register result_reg_2,
Register source_reg,
Register scratch_reg)
: result1_(result_reg_1),
result2_(result_reg_2),
source_(source_reg),
zeros_(scratch_reg) { }
private:
Register result1_;
Register result2_;
Register source_;
Register zeros_;
// Minor key encoding in 16 bits.
class ModeBits: public BitField<OverwriteMode, 0, 2> {};
class OpBits: public BitField<Token::Value, 2, 14> {};
Major MajorKey() { return ConvertToDouble; }
int MinorKey() {
// Encode the parameters in a unique 16 bit value.
return result1_.code() +
(result2_.code() << 4) +
(source_.code() << 8) +
(zeros_.code() << 12);
}
void Generate(MacroAssembler* masm);
};
void ConvertToDoubleStub::Generate(MacroAssembler* masm) {
Register exponent = result1_;
Register mantissa = result2_;
Label not_special;
__ SmiUntag(source_);
// Move sign bit from source to destination. This works because the sign bit
// in the exponent word of the double has the same position and polarity as
// the 2's complement sign bit in a Smi.
STATIC_ASSERT(HeapNumber::kSignMask == 0x80000000u);
__ and_(exponent, source_, Operand(HeapNumber::kSignMask), SetCC);
// Subtract from 0 if source was negative.
__ rsb(source_, source_, Operand::Zero(), LeaveCC, ne);
// We have -1, 0 or 1, which we treat specially. Register source_ contains
// absolute value: it is either equal to 1 (special case of -1 and 1),
// greater than 1 (not a special case) or less than 1 (special case of 0).
__ cmp(source_, Operand(1));
__ b(gt, ¬_special);
// For 1 or -1 we need to or in the 0 exponent (biased to 1023).
const uint32_t exponent_word_for_1 =
HeapNumber::kExponentBias << HeapNumber::kExponentShift;
__ orr(exponent, exponent, Operand(exponent_word_for_1), LeaveCC, eq);
// 1, 0 and -1 all have 0 for the second word.
__ mov(mantissa, Operand::Zero());
__ Ret();
__ bind(¬_special);
__ clz(zeros_, source_);
// Compute exponent and or it into the exponent register.
// We use mantissa as a scratch register here. Use a fudge factor to
// divide the constant 31 + HeapNumber::kExponentBias, 0x41d, into two parts
// that fit in the ARM's constant field.
int fudge = 0x400;
__ rsb(mantissa, zeros_, Operand(31 + HeapNumber::kExponentBias - fudge));
__ add(mantissa, mantissa, Operand(fudge));
__ orr(exponent,
exponent,
Operand(mantissa, LSL, HeapNumber::kExponentShift));
// Shift up the source chopping the top bit off.
__ add(zeros_, zeros_, Operand(1));
// This wouldn't work for 1.0 or -1.0 as the shift would be 32 which means 0.
__ mov(source_, Operand(source_, LSL, zeros_));
// Compute lower part of fraction (last 12 bits).
__ mov(mantissa, Operand(source_, LSL, HeapNumber::kMantissaBitsInTopWord));
// And the top (top 20 bits).
__ orr(exponent,
exponent,
Operand(source_, LSR, 32 - HeapNumber::kMantissaBitsInTopWord));
__ Ret();
}
void DoubleToIStub::Generate(MacroAssembler* masm) {
Label out_of_range, only_low, negate, done;
Register input_reg = source();
Register result_reg = destination();
int double_offset = offset();
// Account for saved regs if input is sp.
if (input_reg.is(sp)) double_offset += 2 * kPointerSize;
// Immediate values for this stub fit in instructions, so it's safe to use ip.
Register scratch = ip;
Register scratch_low =
GetRegisterThatIsNotOneOf(input_reg, result_reg, scratch);
Register scratch_high =
GetRegisterThatIsNotOneOf(input_reg, result_reg, scratch, scratch_low);
LowDwVfpRegister double_scratch = kScratchDoubleReg;
__ Push(scratch_high, scratch_low);
if (!skip_fastpath()) {
// Load double input.
__ vldr(double_scratch, MemOperand(input_reg, double_offset));
__ vmov(scratch_low, scratch_high, double_scratch);
// Do fast-path convert from double to int.
__ vcvt_s32_f64(double_scratch.low(), double_scratch);
__ vmov(result_reg, double_scratch.low());
// If result is not saturated (0x7fffffff or 0x80000000), we are done.
__ sub(scratch, result_reg, Operand(1));
__ cmp(scratch, Operand(0x7ffffffe));
__ b(lt, &done);
} else {
// We've already done MacroAssembler::TryFastTruncatedDoubleToILoad, so we
// know exponent > 31, so we can skip the vcvt_s32_f64 which will saturate.
if (double_offset == 0) {
__ ldm(ia, input_reg, scratch_low.bit() | scratch_high.bit());
} else {
__ ldr(scratch_low, MemOperand(input_reg, double_offset));
__ ldr(scratch_high, MemOperand(input_reg, double_offset + kIntSize));
}
}
__ Ubfx(scratch, scratch_high,
HeapNumber::kExponentShift, HeapNumber::kExponentBits);
// Load scratch with exponent - 1. This is faster than loading
// with exponent because Bias + 1 = 1024 which is an *ARM* immediate value.
STATIC_ASSERT(HeapNumber::kExponentBias + 1 == 1024);
__ sub(scratch, 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).
__ cmp(scratch, Operand(83));
__ b(ge, &out_of_range);
// 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)).
__ rsb(scratch, scratch, Operand(51), SetCC);
__ b(ls, &only_low);
// 21 <= exponent <= 51, shift scratch_low and scratch_high
// to generate the result.
__ mov(scratch_low, Operand(scratch_low, LSR, scratch));
// Scratch contains: 52 - exponent.
// We needs: exponent - 20.
// So we use: 32 - scratch = 32 - 52 + exponent = exponent - 20.
__ rsb(scratch, scratch, Operand(32));
__ Ubfx(result_reg, scratch_high,
0, HeapNumber::kMantissaBitsInTopWord);
// Set the implicit 1 before the mantissa part in scratch_high.
__ orr(result_reg, result_reg,
Operand(1 << HeapNumber::kMantissaBitsInTopWord));
__ orr(result_reg, scratch_low, Operand(result_reg, LSL, scratch));
__ b(&negate);
__ bind(&out_of_range);
__ mov(result_reg, Operand::Zero());
__ b(&done);
__ bind(&only_low);
// 52 <= exponent <= 83, shift only scratch_low.
// On entry, scratch contains: 52 - exponent.
__ rsb(scratch, scratch, Operand::Zero());
__ mov(result_reg, Operand(scratch_low, LSL, 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.
__ eor(result_reg, result_reg, Operand(scratch_high, ASR, 31));
__ add(result_reg, result_reg, Operand(scratch_high, LSR, 31));
__ bind(&done);
__ Pop(scratch_high, scratch_low);
__ Ret();
}
void WriteInt32ToHeapNumberStub::GenerateFixedRegStubsAheadOfTime(
Isolate* isolate) {
WriteInt32ToHeapNumberStub stub1(r1, r0, r2);
WriteInt32ToHeapNumberStub stub2(r2, r0, r3);
stub1.GetCode(isolate);
stub2.GetCode(isolate);
}
// See comment for class.
void WriteInt32ToHeapNumberStub::Generate(MacroAssembler* masm) {
Label max_negative_int;
// the_int_ has the answer which is a signed int32 but not a Smi.
// We test for the special value that has a different exponent. This test
// has the neat side effect of setting the flags according to the sign.
STATIC_ASSERT(HeapNumber::kSignMask == 0x80000000u);
__ cmp(the_int_, Operand(0x80000000u));
__ b(eq, &max_negative_int);
// Set up the correct exponent in scratch_. All non-Smi int32s have the same.
// A non-Smi integer is 1.xxx * 2^30 so the exponent is 30 (biased).
uint32_t non_smi_exponent =
(HeapNumber::kExponentBias + 30) << HeapNumber::kExponentShift;
__ mov(scratch_, Operand(non_smi_exponent));
// Set the sign bit in scratch_ if the value was negative.
__ orr(scratch_, scratch_, Operand(HeapNumber::kSignMask), LeaveCC, cs);
// Subtract from 0 if the value was negative.
__ rsb(the_int_, the_int_, Operand::Zero(), LeaveCC, cs);
// We should be masking the implict first digit of the mantissa away here,
// but it just ends up combining harmlessly with the last digit of the
// exponent that happens to be 1. The sign bit is 0 so we shift 10 to get
// the most significant 1 to hit the last bit of the 12 bit sign and exponent.
ASSERT(((1 << HeapNumber::kExponentShift) & non_smi_exponent) != 0);
const int shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 2;
__ orr(scratch_, scratch_, Operand(the_int_, LSR, shift_distance));
__ str(scratch_, FieldMemOperand(the_heap_number_,
HeapNumber::kExponentOffset));
__ mov(scratch_, Operand(the_int_, LSL, 32 - shift_distance));
__ str(scratch_, FieldMemOperand(the_heap_number_,
HeapNumber::kMantissaOffset));
__ Ret();
__ bind(&max_negative_int);
// The max negative int32 is stored as a positive number in the mantissa of
// a double because it uses a sign bit instead of using two's complement.
// The actual mantissa bits stored are all 0 because the implicit most
// significant 1 bit is not stored.
non_smi_exponent += 1 << HeapNumber::kExponentShift;
__ mov(ip, Operand(HeapNumber::kSignMask | non_smi_exponent));
__ str(ip, FieldMemOperand(the_heap_number_, HeapNumber::kExponentOffset));
__ mov(ip, Operand::Zero());
__ str(ip, FieldMemOperand(the_heap_number_, HeapNumber::kMantissaOffset));
__ 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;
__ cmp(r0, r1);
__ b(ne, ¬_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) {
__ CompareObjectType(r0, r4, r4, FIRST_SPEC_OBJECT_TYPE);
__ b(ge, slow);
} else {
__ CompareObjectType(r0, r4, r4, HEAP_NUMBER_TYPE);
__ b(eq, &heap_number);
// Comparing JS objects with <=, >= is complicated.
if (cond != eq) {
__ cmp(r4, Operand(FIRST_SPEC_OBJECT_TYPE));
__ b(ge, 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) {
__ cmp(r4, Operand(ODDBALL_TYPE));
__ b(ne, &return_equal);
__ LoadRoot(r2, Heap::kUndefinedValueRootIndex);
__ cmp(r0, r2);
__ b(ne, &return_equal);
if (cond == le) {
// undefined <= undefined should fail.
__ mov(r0, Operand(GREATER));
} else {
// undefined >= undefined should fail.
__ mov(r0, Operand(LESS));
}
__ Ret();
}
}
}
__ bind(&return_equal);
if (cond == lt) {
__ mov(r0, Operand(GREATER)); // Things aren't less than themselves.
} else if (cond == gt) {
__ mov(r0, Operand(LESS)); // Things aren't greater than themselves.
} else {
__ mov(r0, 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).
__ ldr(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
// Test that exponent bits are all set.
__ Sbfx(r3, r2, HeapNumber::kExponentShift, HeapNumber::kExponentBits);
// NaNs have all-one exponents so they sign extend to -1.
__ cmp(r3, Operand(-1));
__ b(ne, &return_equal);
// Shift out flag and all exponent bits, retaining only mantissa.
__ mov(r2, Operand(r2, LSL, HeapNumber::kNonMantissaBitsInTopWord));
// Or with all low-bits of mantissa.
__ ldr(r3, FieldMemOperand(r0, HeapNumber::kMantissaOffset));
__ orr(r0, r3, Operand(r2), SetCC);
// For equal we already have the right value in r0: 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) {
// All-zero means Infinity means equal.
__ Ret(eq);
if (cond == le) {
__ mov(r0, Operand(GREATER)); // NaN <= NaN should fail.
} else {
__ mov(r0, 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) {
ASSERT((lhs.is(r0) && rhs.is(r1)) ||
(lhs.is(r1) && rhs.is(r0)));
Label rhs_is_smi;
__ JumpIfSmi(rhs, &rhs_is_smi);
// Lhs is a Smi. Check whether the rhs is a heap number.
__ CompareObjectType(rhs, r4, r4, 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 r0 then there is already a non zero value in it.
if (!rhs.is(r0)) {
__ mov(r0, Operand(NOT_EQUAL), LeaveCC, ne);
}
__ Ret(ne);
} else {
// Smi compared non-strictly with a non-Smi non-heap-number. Call
// the runtime.
__ b(ne, 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 r0, to d6.
__ vldr(d6, rhs, HeapNumber::kValueOffset - kHeapObjectTag);
// We now have both loaded as doubles but we can skip the lhs nan check
// since it's a smi.
__ jmp(lhs_not_nan);
__ bind(&rhs_is_smi);
// Rhs is a smi. Check whether the non-smi lhs is a heap number.
__ CompareObjectType(lhs, r4, r4, 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 r0 then there is already a non zero value in it.
if (!lhs.is(r0)) {
__ mov(r0, Operand(NOT_EQUAL), LeaveCC, ne);
}
__ Ret(ne);
} else {
// Smi compared non-strictly with a non-smi non-heap-number. Call
// the runtime.
__ b(ne, slow);
}
// Rhs is a smi, lhs is a heap number.
// Load the double from lhs, tagged HeapNumber r1, to d7.
__ vldr(d7, lhs, HeapNumber::kValueOffset - kHeapObjectTag);
// 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) {
ASSERT((lhs.is(r0) && rhs.is(r1)) ||
(lhs.is(r1) && rhs.is(r0)));
// 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_SPEC_OBJECT_TYPE);
Label first_non_object;
// Get the type of the first operand into r2 and compare it with
// FIRST_SPEC_OBJECT_TYPE.
__ CompareObjectType(rhs, r2, r2, FIRST_SPEC_OBJECT_TYPE);
__ b(lt, &first_non_object);
// Return non-zero (r0 is not zero)
Label return_not_equal;
__ bind(&return_not_equal);
__ Ret();
__ bind(&first_non_object);
// Check for oddballs: true, false, null, undefined.
__ cmp(r2, Operand(ODDBALL_TYPE));
__ b(eq, &return_not_equal);
__ CompareObjectType(lhs, r3, r3, FIRST_SPEC_OBJECT_TYPE);
__ b(ge, &return_not_equal);
// Check for oddballs: true, false, null, undefined.
__ cmp(r3, Operand(ODDBALL_TYPE));
__ b(eq, &return_not_equal);
// Now that we have the types we might as well check for
// internalized-internalized.
STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
__ orr(r2, r2, Operand(r3));
__ tst(r2, Operand(kIsNotStringMask | kIsNotInternalizedMask));
__ b(eq, &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) {
ASSERT((lhs.is(r0) && rhs.is(r1)) ||
(lhs.is(r1) && rhs.is(r0)));
__ CompareObjectType(rhs, r3, r2, HEAP_NUMBER_TYPE);
__ b(ne, not_heap_numbers);
__ ldr(r2, FieldMemOperand(lhs, HeapObject::kMapOffset));
__ cmp(r2, r3);
__ b(ne, 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.
__ vldr(d6, rhs, HeapNumber::kValueOffset - kHeapObjectTag);
__ vldr(d7, lhs, HeapNumber::kValueOffset - kHeapObjectTag);
__ jmp(both_loaded_as_doubles);
}
// Fast negative check for internalized-to-internalized equality.
static void EmitCheckForInternalizedStringsOrObjects(MacroAssembler* masm,
Register lhs,
Register rhs,
Label* possible_strings,
Label* not_both_strings) {
ASSERT((lhs.is(r0) && rhs.is(r1)) ||
(lhs.is(r1) && rhs.is(r0)));
// r2 is object type of rhs.
Label object_test;
STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
__ tst(r2, Operand(kIsNotStringMask));
__ b(ne, &object_test);
__ tst(r2, Operand(kIsNotInternalizedMask));
__ b(ne, possible_strings);
__ CompareObjectType(lhs, r3, r3, FIRST_NONSTRING_TYPE);
__ b(ge, not_both_strings);
__ tst(r3, Operand(kIsNotInternalizedMask));
__ b(ne, possible_strings);
// Both are internalized. We already checked they weren't the same pointer
// so they are not equal.
__ mov(r0, Operand(NOT_EQUAL));
__ Ret();
__ bind(&object_test);
__ cmp(r2, Operand(FIRST_SPEC_OBJECT_TYPE));
__ b(lt, not_both_strings);
__ CompareObjectType(lhs, r2, r3, FIRST_SPEC_OBJECT_TYPE);
__ b(lt, not_both_strings);
// If both objects are undetectable, they are equal. Otherwise, they
// are not equal, since they are different objects and an object is not
// equal to undefined.
__ ldr(r3, FieldMemOperand(rhs, HeapObject::kMapOffset));
__ ldrb(r2, FieldMemOperand(r2, Map::kBitFieldOffset));
__ ldrb(r3, FieldMemOperand(r3, Map::kBitFieldOffset));
__ and_(r0, r2, Operand(r3));
__ and_(r0, r0, Operand(1 << Map::kIsUndetectable));
__ eor(r0, r0, Operand(1 << Map::kIsUndetectable));
__ Ret();
}
static void ICCompareStub_CheckInputType(MacroAssembler* masm,
Register input,
Register scratch,
CompareIC::State expected,
Label* fail) {
Label ok;
if (expected == CompareIC::SMI) {
__ JumpIfNotSmi(input, fail);
} else if (expected == CompareIC::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 r1 and r2 are the values to be compared.
// On exit r0 is 0, positive or negative to indicate the result of
// the comparison.
void ICCompareStub::GenerateGeneric(MacroAssembler* masm) {
Register lhs = r1;
Register rhs = r0;
Condition cc = GetCondition();
Label miss;
ICCompareStub_CheckInputType(masm, lhs, r2, left_, &miss);
ICCompareStub_CheckInputType(masm, rhs, r3, right_, &miss);
Label slow; // Call builtin.
Label not_smis, both_loaded_as_doubles, lhs_not_nan;
Label not_two_smis, smi_done;
__ orr(r2, r1, r0);
__ JumpIfNotSmi(r2, ¬_two_smis);
__ mov(r1, Operand(r1, ASR, 1));
__ sub(r0, r1, Operand(r0, ASR, 1));
__ 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);
ASSERT_EQ(0, Smi::FromInt(0));
__ and_(r2, lhs, Operand(rhs));
__ JumpIfNotSmi(r2, ¬_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. If VFP3 is supported the double values of the numbers have
// been loaded into d7 and d6. Otherwise, the double values have been loaded
// into r0, r1, r2, and r3.
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, if
// VFP3 is supported, or in r0, r1, r2, and r3.
Isolate* isolate = masm->isolate();
__ bind(&lhs_not_nan);
Label no_nan;
// ARMv7 VFP3 instructions to implement double precision comparison.
__ VFPCompareAndSetFlags(d7, d6);
Label nan;
__ b(vs, &nan);
__ mov(r0, Operand(EQUAL), LeaveCC, eq);
__ mov(r0, Operand(LESS), LeaveCC, lt);
__ mov(r0, Operand(GREATER), LeaveCC, gt);
__ Ret();
__ bind(&nan);
// If one of the sides was a NaN then the v flag is set. Load r0 with
// whatever it takes to make the comparison fail, since comparisons with NaN
// always fail.
if (cc == lt || cc == le) {
__ mov(r0, Operand(GREATER));
} else {
__ mov(r0, 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 r0, r1, r2, r3 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 r2 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 r2 is the type of rhs_ on entry.
EmitCheckForInternalizedStringsOrObjects(
masm, lhs, rhs, &flat_string_check, &slow);
}
// Check for both being sequential ASCII strings, and inline if that is the
// case.
__ bind(&flat_string_check);
__ JumpIfNonSmisNotBothSequentialAsciiStrings(lhs, rhs, r2, r3, &slow);
__ IncrementCounter(isolate->counters()->string_compare_native(), 1, r2, r3);
if (cc == eq) {
StringCompareStub::GenerateFlatAsciiStringEquals(masm,
lhs,
rhs,
r2,
r3,
r4);
} else {
StringCompareStub::GenerateCompareFlatAsciiStrings(masm,
lhs,
rhs,
r2,
r3,
r4,
r5);
}
// Never falls through to here.
__ bind(&slow);
__ Push(lhs, rhs);
// Figure out which native to call and setup the arguments.
Builtins::JavaScript native;
if (cc == eq) {
native = strict() ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
} else {
native = Builtins::COMPARE;
int ncr; // NaN compare result
if (cc == lt || cc == le) {
ncr = GREATER;
} else {
ASSERT(cc == gt || cc == ge); // remaining cases
ncr = LESS;
}
__ mov(r0, Operand(Smi::FromInt(ncr)));
__ push(r0);
}
// Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
// tagged as a small integer.
__ InvokeBuiltin(native, JUMP_FUNCTION);
__ 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.
__ stm(db_w, sp, kCallerSaved | lr.bit());
const Register scratch = r1;
if (save_doubles_ == kSaveFPRegs) {
__ SaveFPRegs(sp, scratch);
}
const int argument_count = 1;
const int fp_argument_count = 0;
AllowExternalCallThatCantCauseGC scope(masm);
__ PrepareCallCFunction(argument_count, fp_argument_count, scratch);
__ mov(r0, Operand(ExternalReference::isolate_address(masm->isolate())));
__ CallCFunction(
ExternalReference::store_buffer_overflow_function(masm->isolate()),
argument_count);
if (save_doubles_ == kSaveFPRegs) {
__ RestoreFPRegs(sp, scratch);
}
__ ldm(ia_w, sp, kCallerSaved | pc.bit()); // Also pop pc to get Ret(0).
}
void TranscendentalCacheStub::Generate(MacroAssembler* masm) {
// Untagged case: double input in d2, double result goes
// into d2.
// Tagged case: tagged input on top of stack and in r0,
// tagged result (heap number) goes into r0.
Label input_not_smi;
Label loaded;
Label calculate;
Label invalid_cache;
const Register scratch0 = r9;
Register scratch1 = no_reg; // will be r4
const Register cache_entry = r0;
const bool tagged = (argument_type_ == TAGGED);
if (tagged) {
// Argument is a number and is on stack and in r0.
// Load argument and check if it is a smi.
__ JumpIfNotSmi(r0, &input_not_smi);
// Input is a smi. Convert to double and load the low and high words
// of the double into r2, r3.
__ SmiToDouble(d7, r0);
__ vmov(r2, r3, d7);
__ b(&loaded);
__ bind(&input_not_smi);
// Check if input is a HeapNumber.
__ CheckMap(r0,
r1,
Heap::kHeapNumberMapRootIndex,
&calculate,
DONT_DO_SMI_CHECK);
// Input is a HeapNumber. Load it to a double register and store the
// low and high words into r2, r3.
__ vldr(d0, FieldMemOperand(r0, HeapNumber::kValueOffset));
__ vmov(r2, r3, d0);
} else {
// Input is untagged double in d2. Output goes to d2.
__ vmov(r2, r3, d2);
}
__ bind(&loaded);
// r2 = low 32 bits of double value
// r3 = high 32 bits of double value
// Compute hash (the shifts are arithmetic):
// h = (low ^ high); h ^= h >> 16; h ^= h >> 8; h = h & (cacheSize - 1);
__ eor(r1, r2, Operand(r3));
__ eor(r1, r1, Operand(r1, ASR, 16));
__ eor(r1, r1, Operand(r1, ASR, 8));
ASSERT(IsPowerOf2(TranscendentalCache::SubCache::kCacheSize));
__ And(r1, r1, Operand(TranscendentalCache::SubCache::kCacheSize - 1));
// r2 = low 32 bits of double value.
// r3 = high 32 bits of double value.
// r1 = TranscendentalCache::hash(double value).
Isolate* isolate = masm->isolate();
ExternalReference cache_array =
ExternalReference::transcendental_cache_array_address(isolate);
__ mov(cache_entry, Operand(cache_array));
// cache_entry points to cache array.
int cache_array_index
= type_ * sizeof(isolate->transcendental_cache()->caches_[0]);
__ ldr(cache_entry, MemOperand(cache_entry, cache_array_index));
// r0 points to the cache for the type type_.
// If NULL, the cache hasn't been initialized yet, so go through runtime.
__ cmp(cache_entry, Operand::Zero());
__ b(eq, &invalid_cache);
#ifdef DEBUG
// Check that the layout of cache elements match expectations.
{ TranscendentalCache::SubCache::Element test_elem[2];
char* elem_start = reinterpret_cast<char*>(&test_elem[0]);
char* elem2_start = reinterpret_cast<char*>(&test_elem[1]);
char* elem_in0 = reinterpret_cast<char*>(&(test_elem[0].in[0]));
char* elem_in1 = reinterpret_cast<char*>(&(test_elem[0].in[1]));
char* elem_out = reinterpret_cast<char*>(&(test_elem[0].output));
CHECK_EQ(12, elem2_start - elem_start); // Two uint_32's and a pointer.
CHECK_EQ(0, elem_in0 - elem_start);
CHECK_EQ(kIntSize, elem_in1 - elem_start);
CHECK_EQ(2 * kIntSize, elem_out - elem_start);
}
#endif
// Find the address of the r1'st entry in the cache, i.e., &r0[r1*12].
__ add(r1, r1, Operand(r1, LSL, 1));
__ add(cache_entry, cache_entry, Operand(r1, LSL, 2));
// Check if cache matches: Double value is stored in uint32_t[2] array.
__ ldm(ia, cache_entry, r4.bit() | r5.bit() | r6.bit());
__ cmp(r2, r4);
__ cmp(r3, r5, eq);
__ b(ne, &calculate);
scratch1 = r4; // Start of scratch1 range.
// Cache hit. Load result, cleanup and return.
Counters* counters = masm->isolate()->counters();
__ IncrementCounter(
counters->transcendental_cache_hit(), 1, scratch0, scratch1);
if (tagged) {
// Pop input value from stack and load result into r0.
__ pop();
__ mov(r0, Operand(r6));
} else {
// Load result into d2.
__ vldr(d2, FieldMemOperand(r6, HeapNumber::kValueOffset));
}
__ Ret();
__ bind(&calculate);
__ IncrementCounter(
counters->transcendental_cache_miss(), 1, scratch0, scratch1);
if (tagged) {
__ bind(&invalid_cache);
ExternalReference runtime_function =
ExternalReference(RuntimeFunction(), masm->isolate());
__ TailCallExternalReference(runtime_function, 1, 1);
} else {
Label no_update;
Label skip_cache;
// Call C function to calculate the result and update the cache.
// r0: precalculated cache entry address.
// r2 and r3: parts of the double value.
// Store r0, r2 and r3 on stack for later before calling C function.
__ Push(r3, r2, cache_entry);
GenerateCallCFunction(masm, scratch0);
__ GetCFunctionDoubleResult(d2);
// Try to update the cache. If we cannot allocate a
// heap number, we return the result without updating.
__ Pop(r3, r2, cache_entry);
__ LoadRoot(r5, Heap::kHeapNumberMapRootIndex);
__ AllocateHeapNumber(r6, scratch0, scratch1, r5, &no_update);
__ vstr(d2, FieldMemOperand(r6, HeapNumber::kValueOffset));
__ stm(ia, cache_entry, r2.bit() | r3.bit() | r6.bit());
__ Ret();
__ bind(&invalid_cache);
// The cache is invalid. Call runtime which will recreate the
// cache.
__ LoadRoot(r5, Heap::kHeapNumberMapRootIndex);
__ AllocateHeapNumber(r0, scratch0, scratch1, r5, &skip_cache);
__ vstr(d2, FieldMemOperand(r0, HeapNumber::kValueOffset));
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ push(r0);
__ CallRuntime(RuntimeFunction(), 1);
}
__ vldr(d2, FieldMemOperand(r0, HeapNumber::kValueOffset));
__ Ret();
__ bind(&skip_cache);
// Call C function to calculate the result and answer directly
// without updating the cache.
GenerateCallCFunction(masm, scratch0);
__ GetCFunctionDoubleResult(d2);
__ bind(&no_update);
// We return the value in d2 without adding it to the cache, but
// we cause a scavenging GC so that future allocations will succeed.
{
FrameScope scope(masm, StackFrame::INTERNAL);
// Allocate an aligned object larger than a HeapNumber.
ASSERT(4 * kPointerSize >= HeapNumber::kSize);
__ mov(scratch0, Operand(4 * kPointerSize));
__ push(scratch0);
__ CallRuntimeSaveDoubles(Runtime::kAllocateInNewSpace);
}
__ Ret();
}
}
void TranscendentalCacheStub::GenerateCallCFunction(MacroAssembler* masm,
Register scratch) {
Isolate* isolate = masm->isolate();
__ push(lr);
__ PrepareCallCFunction(0, 1, scratch);
if (masm->use_eabi_hardfloat()) {
__ vmov(d0, d2);
} else {
__ vmov(r0, r1, d2);
}
AllowExternalCallThatCantCauseGC scope(masm);
switch (type_) {
case TranscendentalCache::LOG:
__ CallCFunction(ExternalReference::math_log_double_function(isolate),
0, 1);
break;
default:
UNIMPLEMENTED();
break;
}
__ pop(lr);
}
Runtime::FunctionId TranscendentalCacheStub::RuntimeFunction() {
switch (type_) {
// Add more cases when necessary.
case TranscendentalCache::LOG: return Runtime::kMath_log;
default:
UNIMPLEMENTED();
return Runtime::kAbort;
}
}
void MathPowStub::Generate(MacroAssembler* masm) {
const Register base = r1;
const Register exponent = r2;
const Register heapnumbermap = r5;
const Register heapnumber = r0;
const DwVfpRegister double_base = d0;
const DwVfpRegister double_exponent = d1;
const DwVfpRegister double_result = d2;
const DwVfpRegister double_scratch = d3;
const SwVfpRegister single_scratch = s6;
const Register scratch = r9;
const Register scratch2 = r4;
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.
__ ldr(base, MemOperand(sp, 1 * kPointerSize));
__ ldr(exponent, MemOperand(sp, 0 * kPointerSize));
__ LoadRoot(heapnumbermap, Heap::kHeapNumberMapRootIndex);
__ UntagAndJumpIfSmi(scratch, base, &base_is_smi);
__ ldr(scratch, FieldMemOperand(base, JSObject::kMapOffset));
__ cmp(scratch, heapnumbermap);
__ b(ne, &call_runtime);
__ vldr(double_base, FieldMemOperand(base, HeapNumber::kValueOffset));
__ jmp(&unpack_exponent);
__ bind(&base_is_smi);
__ vmov(single_scratch, scratch);
__ vcvt_f64_s32(double_base, single_scratch);
__ bind(&unpack_exponent);
__ UntagAndJumpIfSmi(scratch, exponent, &int_exponent);
__ ldr(scratch, FieldMemOperand(exponent, JSObject::kMapOffset));
__ cmp(scratch, heapnumbermap);
__ b(ne, &call_runtime);
__ vldr(double_exponent,
FieldMemOperand(exponent, HeapNumber::kValueOffset));
} else if (exponent_type_ == TAGGED) {
// Base is already in double_base.
__ UntagAndJumpIfSmi(scratch, exponent, &int_exponent);
__ vldr(double_exponent,
FieldMemOperand(exponent, HeapNumber::kValueOffset));
}
if (exponent_type_ != INTEGER) {
Label int_exponent_convert;
// Detect integer exponents stored as double.
__ vcvt_u32_f64(single_scratch, double_exponent);
// We do not check for NaN or Infinity here because comparing numbers on
// ARM correctly distinguishes NaNs. We end up calling the built-in.
__ vcvt_f64_u32(double_scratch, single_scratch);
__ VFPCompareAndSetFlags(double_scratch, double_exponent);
__ b(eq, &int_exponent_convert);
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;
// Test for 0.5.
__ vmov(double_scratch, 0.5, scratch);
__ VFPCompareAndSetFlags(double_exponent, double_scratch);
__ b(ne, ¬_plus_half);
// Calculates square root of base. Check for the special case of
// Math.pow(-Infinity, 0.5) == Infinity (ECMA spec, 15.8.2.13).
__ vmov(double_scratch, -V8_INFINITY, scratch);
__ VFPCompareAndSetFlags(double_base, double_scratch);
__ vneg(double_result, double_scratch, eq);
__ b(eq, &done);
// Add +0 to convert -0 to +0.
__ vadd(double_scratch, double_base, kDoubleRegZero);
__ vsqrt(double_result, double_scratch);
__ jmp(&done);
__ bind(¬_plus_half);
__ vmov(double_scratch, -0.5, scratch);
__ VFPCompareAndSetFlags(double_exponent, double_scratch);
__ b(ne, &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).
__ vmov(double_scratch, -V8_INFINITY, scratch);
__ VFPCompareAndSetFlags(double_base, double_scratch);
__ vmov(double_result, kDoubleRegZero, eq);
__ b(eq, &done);
// Add +0 to convert -0 to +0.
__ vadd(double_scratch, double_base, kDoubleRegZero);
__ vmov(double_result, 1.0, scratch);
__ vsqrt(double_scratch, double_scratch);
__ vdiv(double_result, double_result, double_scratch);
__ jmp(&done);
}
__ push(lr);
{
AllowExternalCallThatCantCauseGC scope(masm);
__ PrepareCallCFunction(0, 2, scratch);
__ SetCallCDoubleArguments(double_base, double_exponent);
__ CallCFunction(
ExternalReference::power_double_double_function(masm->isolate()),
0, 2);
}
__ pop(lr);
__ GetCFunctionDoubleResult(double_result);
__ jmp(&done);
__ bind(&int_exponent_convert);
__ vcvt_u32_f64(single_scratch, double_exponent);
__ vmov(scratch, single_scratch);
}
// Calculate power with integer exponent.
__ bind(&int_exponent);
// Get two copies of exponent in the registers scratch and exponent.
if (exponent_type_ == INTEGER) {
__ mov(scratch, exponent);
} else {
// Exponent has previously been stored into scratch as untagged integer.
__ mov(exponent, scratch);
}
__ vmov(double_scratch, double_base); // Back up base.
__ vmov(double_result, 1.0, scratch2);
// Get absolute value of exponent.
__ cmp(scratch, Operand::Zero());
__ mov(scratch2, Operand::Zero(), LeaveCC, mi);
__ sub(scratch, scratch2, scratch, LeaveCC, mi);
Label while_true;
__ bind(&while_true);
__ mov(scratch, Operand(scratch, ASR, 1), SetCC);
__ vmul(double_result, double_result, double_scratch, cs);
__ vmul(double_scratch, double_scratch, double_scratch, ne);
__ b(ne, &while_true);
__ cmp(exponent, Operand::Zero());
__ b(ge, &done);
__ vmov(double_scratch, 1.0, scratch);
__ vdiv(double_result, double_scratch, double_result);
// 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.
__ VFPCompareAndSetFlags(double_result, 0.0);
__ b(ne, &done);
// double_exponent may not containe the exponent value if the input was a
// smi. We set it with exponent value before bailing out.
__ vmov(single_scratch, exponent);
__ vcvt_f64_s32(double_exponent, single_scratch);
// Returning or bailing out.
Counters* counters = masm->isolate()->counters();
if (exponent_type_ == ON_STACK) {
// The arguments are still on the stack.
__ bind(&call_runtime);
__ TailCallRuntime(Runtime::kMath_pow_cfunction, 2, 1);
// 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);
__ vstr(double_result,
FieldMemOperand(heapnumber, HeapNumber::kValueOffset));
ASSERT(heapnumber.is(r0));
__ IncrementCounter(counters->math_pow(), 1, scratch, scratch2);
__ Ret(2);
} else {
__ push(lr);
{
AllowExternalCallThatCantCauseGC scope(masm);
__ PrepareCallCFunction(0, 2, scratch);
__ SetCallCDoubleArguments(double_base, double_exponent);
__ CallCFunction(
ExternalReference::power_double_double_function(masm->isolate()),
0, 2);
}
__ pop(lr);
__ GetCFunctionDoubleResult(double_result);
__ bind(&done);
__ IncrementCounter(counters->math_pow(), 1, scratch, scratch2);
__ Ret();
}
}
bool CEntryStub::NeedsImmovableCode() {
return true;
}
void CodeStub::GenerateStubsAheadOfTime(Isolate* isolate) {
CEntryStub::GenerateAheadOfTime(isolate);
WriteInt32ToHeapNumberStub::GenerateFixedRegStubsAheadOfTime(isolate);
StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(isolate);
StubFailureTrampolineStub::GenerateAheadOfTime(isolate);
ArrayConstructorStubBase::GenerateStubsAheadOfTime(isolate);
CreateAllocationSiteStub::GenerateAheadOfTime(isolate);
BinaryOpICStub::GenerateAheadOfTime(isolate);
}
void CodeStub::GenerateFPStubs(Isolate* isolate) {
SaveFPRegsMode mode = kSaveFPRegs;
CEntryStub save_doubles(1, mode);
StoreBufferOverflowStub stub(mode);
// These stubs might already be in the snapshot, detect that and don't
// regenerate, which would lead to code stub initialization state being messed
// up.
Code* save_doubles_code;
if (!save_doubles.FindCodeInCache(&save_doubles_code, isolate)) {
save_doubles_code = *save_doubles.GetCode(isolate);
}
Code* store_buffer_overflow_code;
if (!stub.FindCodeInCache(&store_buffer_overflow_code, isolate)) {
store_buffer_overflow_code = *stub.GetCode(isolate);
}
isolate->set_fp_stubs_generated(true);
}
void CEntryStub::GenerateAheadOfTime(Isolate* isolate) {
CEntryStub stub(1, kDontSaveFPRegs);
stub.GetCode(isolate);
}
static void JumpIfOOM(MacroAssembler* masm,
Register value,
Register scratch,
Label* oom_label) {
STATIC_ASSERT(Failure::OUT_OF_MEMORY_EXCEPTION == 3);
STATIC_ASSERT(kFailureTag == 3);
__ and_(scratch, value, Operand(0xf));
__ cmp(scratch, Operand(0xf));
__ b(eq, oom_label);
}
void CEntryStub::GenerateCore(MacroAssembler* masm,
Label* throw_normal_exception,
Label* throw_termination_exception,
Label* throw_out_of_memory_exception,
bool do_gc,
bool always_allocate) {
// r0: result parameter for PerformGC, if any
// r4: number of arguments including receiver (C callee-saved)
// r5: pointer to builtin function (C callee-saved)
// r6: pointer to the first argument (C callee-saved)
Isolate* isolate = masm->isolate();
if (do_gc) {
// Passing r0.
__ PrepareCallCFunction(2, 0, r1);
__ mov(r1, Operand(ExternalReference::isolate_address(masm->isolate())));
__ CallCFunction(ExternalReference::perform_gc_function(isolate),
2, 0);
}
ExternalReference scope_depth =
ExternalReference::heap_always_allocate_scope_depth(isolate);
if (always_allocate) {
__ mov(r0, Operand(scope_depth));
__ ldr(r1, MemOperand(r0));
__ add(r1, r1, Operand(1));
__ str(r1, MemOperand(r0));
}
// Call C built-in.
// r0 = argc, r1 = argv
__ mov(r0, Operand(r4));
__ mov(r1, Operand(r6));
#if V8_HOST_ARCH_ARM
int frame_alignment = MacroAssembler::ActivationFrameAlignment();
int frame_alignment_mask = frame_alignment - 1;
if (FLAG_debug_code) {
if (frame_alignment > kPointerSize) {
Label alignment_as_expected;
ASSERT(IsPowerOf2(frame_alignment));
__ tst(sp, Operand(frame_alignment_mask));
__ b(eq, &alignment_as_expected);
// Don't use Check here, as it will call Runtime_Abort re-entering here.
__ stop("Unexpected alignment");
__ bind(&alignment_as_expected);
}
}
#endif
__ mov(r2, Operand(ExternalReference::isolate_address(isolate)));
// 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.
// Compute the return address in lr to return to after the jump below. Pc is
// already at '+ 8' from the current instruction but return is after three
// instructions so add another 4 to pc to get the return address.
{
// Prevent literal pool emission before return address.
Assembler::BlockConstPoolScope block_const_pool(masm);
masm->add(lr, pc, Operand(4));
__ str(lr, MemOperand(sp, 0));
masm->Jump(r5);
}
__ VFPEnsureFPSCRState(r2);
if (always_allocate) {
// It's okay to clobber r2 and r3 here. Don't mess with r0 and r1
// though (contain the result).
__ mov(r2, Operand(scope_depth));
__ ldr(r3, MemOperand(r2));
__ sub(r3, r3, Operand(1));
__ str(r3, MemOperand(r2));
}
// check for failure result
Label failure_returned;
STATIC_ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0);
// Lower 2 bits of r2 are 0 iff r0 has failure tag.
__ add(r2, r0, Operand(1));
__ tst(r2, Operand(kFailureTagMask));
__ b(eq, &failure_returned);
// Exit C frame and return.
// r0:r1: result
// sp: stack pointer
// fp: frame pointer
// Callee-saved register r4 still holds argc.
__ LeaveExitFrame(save_doubles_, r4, true);
__ mov(pc, lr);
// check if we should retry or throw exception
Label retry;
__ bind(&failure_returned);
STATIC_ASSERT(Failure::RETRY_AFTER_GC == 0);
__ tst(r0, Operand(((1 << kFailureTypeTagSize) - 1) << kFailureTagSize));
__ b(eq, &retry);
// Special handling of out of memory exceptions.
JumpIfOOM(masm, r0, ip, throw_out_of_memory_exception);
// Retrieve the pending exception.
__ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
isolate)));
__ ldr(r0, MemOperand(ip));
// See if we just retrieved an OOM exception.
JumpIfOOM(masm, r0, ip, throw_out_of_memory_exception);
// Clear the pending exception.
__ mov(r3, Operand(isolate->factory()->the_hole_value()));
__ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
isolate)));
__ str(r3, MemOperand(ip));
// Special handling of termination exceptions which are uncatchable
// by javascript code.
__ cmp(r0, Operand(isolate->factory()->termination_exception()));
__ b(eq, throw_termination_exception);
// Handle normal exception.
__ jmp(throw_normal_exception);
__ bind(&retry); // pass last failure (r0) as parameter (r0) when retrying
}
void CEntryStub::Generate(MacroAssembler* masm) {
// Called from JavaScript; parameters are on stack as if calling JS function
// r0: number of arguments including receiver
// r1: 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)
ProfileEntryHookStub::MaybeCallEntryHook(masm);
// Result returned in r0 or r0+r1 by default.
// NOTE: Invocations of builtins may return failure objects
// instead of a proper result. The builtin entry handles
// this by performing a garbage collection and retrying the
// builtin once.
// Compute the argv pointer in a callee-saved register.
__ add(r6, sp, Operand(r0, LSL, kPointerSizeLog2));
__ sub(r6, r6, Operand(kPointerSize));
// Enter the exit frame that transitions from JavaScript to C++.
FrameScope scope(masm, StackFrame::MANUAL);
__ EnterExitFrame(save_doubles_);
// Set up argc and the builtin function in callee-saved registers.
__ mov(r4, Operand(r0));
__ mov(r5, Operand(r1));
// r4: number of arguments (C callee-saved)
// r5: pointer to builtin function (C callee-saved)
// r6: pointer to first argument (C callee-saved)
Label throw_normal_exception;
Label throw_termination_exception;
Label throw_out_of_memory_exception;
// Call into the runtime system.
GenerateCore(masm,
&throw_normal_exception,
&throw_termination_exception,
&throw_out_of_memory_exception,
false,
false);
// Do space-specific GC and retry runtime call.
GenerateCore(masm,
&throw_normal_exception,
&throw_termination_exception,
&throw_out_of_memory_exception,
true,
false);
// Do full GC and retry runtime call one final time.
Failure* failure = Failure::InternalError();
__ mov(r0, Operand(reinterpret_cast<int32_t>(failure)));
GenerateCore(masm,
&throw_normal_exception,
&throw_termination_exception,
&throw_out_of_memory_exception,
true,
true);
__ bind(&throw_out_of_memory_exception);
// Set external caught exception to false.
Isolate* isolate = masm->isolate();
ExternalReference external_caught(Isolate::kExternalCaughtExceptionAddress,
isolate);
__ mov(r0, Operand(false, RelocInfo::NONE32));
__ mov(r2, Operand(external_caught));
__ str(r0, MemOperand(r2));
// Set pending exception and r0 to out of memory exception.
Label already_have_failure;
JumpIfOOM(masm, r0, ip, &already_have_failure);
Failure* out_of_memory = Failure::OutOfMemoryException(0x1);
__ mov(r0, Operand(reinterpret_cast<int32_t>(out_of_memory)));
__ bind(&already_have_failure);
__ mov(r2, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
isolate)));
__ str(r0, MemOperand(r2));
// Fall through to the next label.
__ bind(&throw_termination_exception);
__ ThrowUncatchable(r0);
__ bind(&throw_normal_exception);
__ Throw(r0);
}
void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) {
// r0: code entry
// r1: function
// r2: receiver
// r3: argc
// [sp+0]: argv
Label invoke, handler_entry, exit;
ProfileEntryHookStub::MaybeCallEntryHook(masm);
// Called from C, so do not pop argc and args on exit (preserve sp)
// No need to save register-passed args
// Save callee-saved registers (incl. cp and fp), sp, and lr
__ stm(db_w, sp, kCalleeSaved | lr.bit());
// Save callee-saved vfp registers.
__ vstm(db_w, sp, kFirstCalleeSavedDoubleReg, kLastCalleeSavedDoubleReg);
// Set up the reserved register for 0.0.
__ vmov(kDoubleRegZero, 0.0);
__ VFPEnsureFPSCRState(r4);
// Get address of argv, see stm above.
// r0: code entry
// r1: function
// r2: receiver
// r3: argc
// Set up argv in r4.
int offset_to_argv = (kNumCalleeSaved + 1) * kPointerSize;
offset_to_argv += kNumDoubleCalleeSaved * kDoubleSize;
__ ldr(r4, MemOperand(sp, offset_to_argv));
// Push a frame with special values setup to mark it as an entry frame.
// r0: code entry
// r1: function
// r2: receiver
// r3: argc
// r4: argv
Isolate* isolate = masm->isolate();
int marker = is_construct ? StackFrame::ENTRY_CONSTRUCT : StackFrame::ENTRY;
__ mov(r8, Operand(Smi::FromInt(marker)));
__ mov(r6, Operand(Smi::FromInt(marker)));
__ mov(r5,
Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate)));
__ ldr(r5, MemOperand(r5));
__ mov(ip, Operand(-1)); // Push a bad frame pointer to fail if it is used.
__ Push(ip, r8, r6, r5);
// Set up frame pointer for the frame to be pushed.
__ add(fp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
// If this is the outermost JS call, set js_entry_sp value.
Label non_outermost_js;
ExternalReference js_entry_sp(Isolate::kJSEntrySPAddress, isolate);
__ mov(r5, Operand(ExternalReference(js_entry_sp)));
__ ldr(r6, MemOperand(r5));
__ cmp(r6, Operand::Zero());
__ b(ne, &non_outermost_js);
__ str(fp, MemOperand(r5));
__ mov(ip, Operand(Smi::FromInt(StackFrame::OUTERMOST_JSENTRY_FRAME)));
Label cont;
__ b(&cont);
__ bind(&non_outermost_js);
__ mov(ip, Operand(Smi::FromInt(StackFrame::INNER_JSENTRY_FRAME)));
__ bind(&cont);
__ push(ip);
// Jump to a faked try block that does the invoke, with a faked catch
// block that sets the pending exception.
__ jmp(&invoke);
// Block literal pool emission whilst taking the position of the handler
// entry. This avoids making the assumption that literal pools are always
// emitted after an instruction is emitted, rather than before.
{
Assembler::BlockConstPoolScope block_const_pool(masm);
__ 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 PushTryHandler below sets it to 0 to
// signal the existence of the JSEntry frame.
__ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
isolate)));
}
__ str(r0, MemOperand(ip));
__ mov(r0, Operand(reinterpret_cast<int32_t>(Failure::Exception())));
__ b(&exit);
// Invoke: Link this frame into the handler chain. There's only one
// handler block in this code object, so its index is 0.
__ bind(&invoke);
// Must preserve r0-r4, r5-r6 are available.
__ PushTryHandler(StackHandler::JS_ENTRY, 0);
// If an exception not caught by another handler occurs, this handler
// returns control to the code after the bl(&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(r5, Operand(isolate->factory()->the_hole_value()));
__ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
isolate)));
__ str(r5, 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
// r0: code entry
// r1: function
// r2: receiver
// r3: argc
// r4: argv
if (is_construct) {
ExternalReference construct_entry(Builtins::kJSConstructEntryTrampoline,
isolate);
__ mov(ip, Operand(construct_entry));
} else {
ExternalReference entry(Builtins::kJSEntryTrampoline, isolate);
__ mov(ip, Operand(entry));
}
__ ldr(ip, MemOperand(ip)); // deref address
// Branch and link to JSEntryTrampoline. We don't use the double underscore
// macro for the add instruction because we don't want the coverage tool
// inserting instructions here after we read the pc. We block literal pool
// emission for the same reason.
{
Assembler::BlockConstPoolScope block_const_pool(masm);
__ mov(lr, Operand(pc));
masm->add(pc, ip, Operand(Code::kHeaderSize - kHeapObjectTag));
}
// Unlink this frame from the handler chain.
__ PopTryHandler();
__ bind(&exit); // r0 holds result
// Check if the current stack frame is marked as the outermost JS frame.
Label non_outermost_js_2;
__ pop(r5);
__ cmp(r5, Operand(Smi::FromInt(StackFrame::OUTERMOST_JSENTRY_FRAME)));
__ b(ne, &non_outermost_js_2);
__ mov(r6, Operand::Zero());
__ mov(r5, Operand(ExternalReference(js_entry_sp)));
__ str(r6, MemOperand(r5));
__ bind(&non_outermost_js_2);
// Restore the top frame descriptors from the stack.
__ pop(r3);
__ mov(ip,
Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate)));
__ str(r3, MemOperand(ip));
// Reset the stack to the callee saved registers.
__ add(sp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
// Restore callee-saved registers and return.
#ifdef DEBUG
if (FLAG_debug_code) {
__ mov(lr, Operand(pc));
}
#endif
// Restore callee-saved vfp registers.
__ vldm(ia_w, sp, kFirstCalleeSavedDoubleReg, kLastCalleeSavedDoubleReg);
__ ldm(ia_w, sp, kCalleeSaved | pc.bit());
}
// Uses registers r0 to r4.
// Expected input (depending on whether args are in registers or on the stack):
// * object: r0 or at sp + 1 * kPointerSize.
// * function: r1 or at sp.
//
// An inlined call site may have been generated before calling this stub.
// In this case the offset to the inline site to patch is passed on the stack,
// in the safepoint slot for register r4.
// (See LCodeGen::DoInstanceOfKnownGlobal)
void InstanceofStub::Generate(MacroAssembler* masm) {
// Call site inlining and patching implies arguments in registers.
ASSERT(HasArgsInRegisters() || !HasCallSiteInlineCheck());
// ReturnTrueFalse is only implemented for inlined call sites.
ASSERT(!ReturnTrueFalseObject() || HasCallSiteInlineCheck());
// Fixed register usage throughout the stub:
const Register object = r0; // Object (lhs).
Register map = r3; // Map of the object.
const Register function = r1; // Function (rhs).
const Register prototype = r4; // Prototype of the function.
const Register inline_site = r9;
const Register scratch = r2;
const int32_t kDeltaToLoadBoolResult = 4 * kPointerSize;
Label slow, loop, is_instance, is_not_instance, not_js_object;
if (!HasArgsInRegisters()) {
__ ldr(object, MemOperand(sp, 1 * kPointerSize));
__ ldr(function, MemOperand(sp, 0));
}
// Check that the left hand is a JS object and load map.
__ JumpIfSmi(object, ¬_js_object);
__ IsObjectJSObjectType(object, map, scratch, ¬_js_object);
// If there is a call site cache don't look in the global cache, but do the
// real lookup and update the call site cache.
if (!HasCallSiteInlineCheck()) {
Label miss;
__ CompareRoot(function, Heap::kInstanceofCacheFunctionRootIndex);
__ b(ne, &miss);
__ CompareRoot(map, Heap::kInstanceofCacheMapRootIndex);
__ b(ne, &miss);
__ LoadRoot(r0, Heap::kInstanceofCacheAnswerRootIndex);
__ Ret(HasArgsInRegisters() ? 0 : 2);
__ bind(&miss);
}
// Get the prototype of the function.
__ TryGetFunctionPrototype(function, prototype, scratch, &slow, true);
// Check that the function prototype is a JS object.
__ JumpIfSmi(prototype, &slow);
__ IsObjectJSObjectType(prototype, scratch, scratch, &slow);
// Update the global instanceof or call site inlined cache with the current
// map and function. The cached answer will be set when it is known below.
if (!HasCallSiteInlineCheck()) {
__ StoreRoot(function, Heap::kInstanceofCacheFunctionRootIndex);
__ StoreRoot(map, Heap::kInstanceofCacheMapRootIndex);
} else {
ASSERT(HasArgsInRegisters());
// Patch the (relocated) inlined map check.
// The offset was stored in r4 safepoint slot.
// (See LCodeGen::DoDeferredLInstanceOfKnownGlobal)
__ LoadFromSafepointRegisterSlot(scratch, r4);
__ sub(inline_site, lr, scratch);
// Get the map location in scratch and patch it.
__ GetRelocatedValueLocation(inline_site, scratch);
__ ldr(scratch, MemOperand(scratch));
__ str(map, FieldMemOperand(scratch, Cell::kValueOffset));
}
// Register mapping: r3 is object map and r4 is function prototype.
// Get prototype of object into r2.
__ ldr(scratch, FieldMemOperand(map, Map::kPrototypeOffset));
// We don't need map any more. Use it as a scratch register.
Register scratch2 = map;
map = no_reg;
// Loop through the prototype chain looking for the function prototype.
__ LoadRoot(scratch2, Heap::kNullValueRootIndex);
__ bind(&loop);
__ cmp(scratch, Operand(prototype));
__ b(eq, &is_instance);
__ cmp(scratch, scratch2);
__ b(eq, &is_not_instance);
__ ldr(scratch, FieldMemOperand(scratch, HeapObject::kMapOffset));
__ ldr(scratch, FieldMemOperand(scratch, Map::kPrototypeOffset));
__ jmp(&loop);
__ bind(&is_instance);
if (!HasCallSiteInlineCheck()) {
__ mov(r0, Operand(Smi::FromInt(0)));
__ StoreRoot(r0, Heap::kInstanceofCacheAnswerRootIndex);
} else {
// Patch the call site to return true.
__ LoadRoot(r0, Heap::kTrueValueRootIndex);
__ add(inline_site, inline_site, Operand(kDeltaToLoadBoolResult));
// Get the boolean result location in scratch and patch it.
__ GetRelocatedValueLocation(inline_site, scratch);
__ str(r0, MemOperand(scratch));
if (!ReturnTrueFalseObject()) {
__ mov(r0, Operand(Smi::FromInt(0)));
}
}
__ Ret(HasArgsInRegisters() ? 0 : 2);
__ bind(&is_not_instance);
if (!HasCallSiteInlineCheck()) {
__ mov(r0, Operand(Smi::FromInt(1)));
__ StoreRoot(r0, Heap::kInstanceofCacheAnswerRootIndex);
} else {
// Patch the call site to return false.
__ LoadRoot(r0, Heap::kFalseValueRootIndex);
__ add(inline_site, inline_site, Operand(kDeltaToLoadBoolResult));
// Get the boolean result location in scratch and patch it.
__ GetRelocatedValueLocation(inline_site, scratch);
__ str(r0, MemOperand(scratch));
if (!ReturnTrueFalseObject()) {
__ mov(r0, Operand(Smi::FromInt(1)));
}
}
__ Ret(HasArgsInRegisters() ? 0 : 2);
Label object_not_null, object_not_null_or_smi;
__ bind(¬_js_object);
// Before null, smi and string value checks, check that the rhs is a function
// as for a non-function rhs an exception needs to be thrown.
__ JumpIfSmi(function, &slow);
__ CompareObjectType(function, scratch2, scratch, JS_FUNCTION_TYPE);
__ b(ne, &slow);
// Null is not instance of anything.
__ cmp(scratch, Operand(masm->isolate()->factory()->null_value()));
__ b(ne, &object_not_null);
__ mov(r0, Operand(Smi::FromInt(1)));
__ Ret(HasArgsInRegisters() ? 0 : 2);
__ bind(&object_not_null);
// Smi values are not instances of anything.
__ JumpIfNotSmi(object, &object_not_null_or_smi);
__ mov(r0, Operand(Smi::FromInt(1)));
__ Ret(HasArgsInRegisters() ? 0 : 2);
__ bind(&object_not_null_or_smi);
// String values are not instances of anything.
__ IsObjectJSStringType(object, scratch, &slow);
__ mov(r0, Operand(Smi::FromInt(1)));
__ Ret(HasArgsInRegisters() ? 0 : 2);
// Slow-case. Tail call builtin.
__ bind(&slow);
if (!ReturnTrueFalseObject()) {
if (HasArgsInRegisters()) {
__ Push(r0, r1);
}
__ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_FUNCTION);
} else {
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(r0, r1);
__ InvokeBuiltin(Builtins::INSTANCE_OF, CALL_FUNCTION);
}
__ cmp(r0, Operand::Zero());
__ LoadRoot(r0, Heap::kTrueValueRootIndex, eq);
__ LoadRoot(r0, Heap::kFalseValueRootIndex, ne);
__ Ret(HasArgsInRegisters() ? 0 : 2);
}
}
void FunctionPrototypeStub::Generate(MacroAssembler* masm) {
Label miss;
Register receiver;
if (kind() == Code::KEYED_LOAD_IC) {
// ----------- S t a t e -------------
// -- lr : return address
// -- r0 : key
// -- r1 : receiver
// -----------------------------------
__ cmp(r0, Operand(masm->isolate()->factory()->prototype_string()));
__ b(ne, &miss);
receiver = r1;
} else {
ASSERT(kind() == Code::LOAD_IC);
// ----------- S t a t e -------------
// -- r2 : name
// -- lr : return address
// -- r0 : receiver
// -- sp[0] : receiver
// -----------------------------------
receiver = r0;
}
StubCompiler::GenerateLoadFunctionPrototype(masm, receiver, r3, r4, &miss);
__ bind(&miss);
StubCompiler::TailCallBuiltin(
masm, BaseLoadStoreStubCompiler::MissBuiltin(kind()));
}
void StringLengthStub::Generate(MacroAssembler* masm) {
Label miss;
Register receiver;
if (kind() == Code::KEYED_LOAD_IC) {
// ----------- S t a t e -------------
// -- lr : return address
// -- r0 : key
// -- r1 : receiver
// -----------------------------------
__ cmp(r0, Operand(masm->isolate()->factory()->length_string()));
__ b(ne, &miss);
receiver = r1;
} else {
ASSERT(kind() == Code::LOAD_IC);
// ----------- S t a t e -------------
// -- r2 : name
// -- lr : return address
// -- r0 : receiver
// -- sp[0] : receiver
// -----------------------------------
receiver = r0;
}
StubCompiler::GenerateLoadStringLength(masm, receiver, r3, r4, &miss);
__ bind(&miss);
StubCompiler::TailCallBuiltin(
masm, BaseLoadStoreStubCompiler::MissBuiltin(kind()));
}
void StoreArrayLengthStub::Generate(MacroAssembler* masm) {
// This accepts as a receiver anything JSArray::SetElementsLength accepts
// (currently anything except for external arrays which means anything with
// elements of FixedArray type). Value must be a number, but only smis are
// accepted as the most common case.
Label miss;
Register receiver;
Register value;
if (kind() == Code::KEYED_STORE_IC) {
// ----------- S t a t e -------------
// -- lr : return address
// -- r0 : value
// -- r1 : key
// -- r2 : receiver
// -----------------------------------
__ cmp(r1, Operand(masm->isolate()->factory()->length_string()));
__ b(ne, &miss);
receiver = r2;
value = r0;
} else {
ASSERT(kind() == Code::STORE_IC);
// ----------- S t a t e -------------
// -- lr : return address
// -- r0 : value
// -- r1 : receiver
// -- r2 : key
// -----------------------------------
receiver = r1;
value = r0;
}
Register scratch = r3;
// Check that the receiver isn't a smi.
__ JumpIfSmi(receiver, &miss);
// Check that the object is a JS array.
__ CompareObjectType(receiver, scratch, scratch, JS_ARRAY_TYPE);
__ b(ne, &miss);
// Check that elements are FixedArray.
// We rely on StoreIC_ArrayLength below to deal with all types of
// fast elements (including COW).
__ ldr(scratch, FieldMemOperand(receiver, JSArray::kElementsOffset));
__ CompareObjectType(scratch, scratch, scratch, FIXED_ARRAY_TYPE);
__ b(ne, &miss);
// Check that the array has fast properties, otherwise the length
// property might have been redefined.
__ ldr(scratch, FieldMemOperand(receiver, JSArray::kPropertiesOffset));
__ ldr(scratch, FieldMemOperand(scratch, FixedArray::kMapOffset));
__ CompareRoot(scratch, Heap::kHashTableMapRootIndex);
__ b(eq, &miss);
// Check that value is a smi.
__ JumpIfNotSmi(value, &miss);
// Prepare tail call to StoreIC_ArrayLength.
__ Push(receiver, value);
ExternalReference ref =
ExternalReference(IC_Utility(IC::kStoreIC_ArrayLength), masm->isolate());
__ TailCallExternalReference(ref, 2, 1);
__ bind(&miss);
StubCompiler::TailCallBuiltin(
masm, BaseLoadStoreStubCompiler::MissBuiltin(kind()));
}
Register InstanceofStub::left() { return r0; }
Register InstanceofStub::right() { return r1; }
void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
// The displacement is the offset of the last parameter (if any)
// relative to the frame pointer.
const int kDisplacement =
StandardFrameConstants::kCallerSPOffset - kPointerSize;
// Check that the key is a smi.
Label slow;
__ JumpIfNotSmi(r1, &slow);
// Check if the calling frame is an arguments adaptor frame.
Label adaptor;
__ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
__ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
__ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ b(eq, &adaptor);
// Check index against formal parameters count limit passed in
// through register r0. Use unsigned comparison to get negative
// check for free.
__ cmp(r1, r0);
__ b(hs, &slow);
// Read the argument from the stack and return it.
__ sub(r3, r0, r1);
__ add(r3, fp, Operand::PointerOffsetFromSmiKey(r3));
__ ldr(r0, MemOperand(r3, kDisplacement));
__ Jump(lr);
// Arguments adaptor case: Check index against actual arguments
// limit found in the arguments adaptor frame. Use unsigned
// comparison to get negative check for free.
__ bind(&adaptor);
__ ldr(r0, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ cmp(r1, r0);
__ b(cs, &slow);
// Read the argument from the adaptor frame and return it.
__ sub(r3, r0, r1);
__ add(r3, r2, Operand::PointerOffsetFromSmiKey(r3));
__ ldr(r0, MemOperand(r3, kDisplacement));
__ Jump(lr);
// Slow-case: Handle non-smi or out-of-bounds access to arguments
// by calling the runtime system.
__ bind(&slow);
__ push(r1);
__ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1);
}
void ArgumentsAccessStub::GenerateNewNonStrictSlow(MacroAssembler* masm) {
// sp[0] : number of parameters
// sp[4] : receiver displacement
// sp[8] : function
// Check if the calling frame is an arguments adaptor frame.
Label runtime;
__ ldr(r3, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
__ ldr(r2, MemOperand(r3, StandardFrameConstants::kContextOffset));
__ cmp(r2, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ b(ne, &runtime);
// Patch the arguments.length and the parameters pointer in the current frame.
__ ldr(r2, MemOperand(r3, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ str(r2, MemOperand(sp, 0 * kPointerSize));
__ add(r3, r3, Operand(r2, LSL, 1));
__ add(r3, r3, Operand(StandardFrameConstants::kCallerSPOffset));
__ str(r3, MemOperand(sp, 1 * kPointerSize));
__ bind(&runtime);
__ TailCallRuntime(Runtime::kNewArgumentsFast, 3, 1);
}
void ArgumentsAccessStub::GenerateNewNonStrictFast(MacroAssembler* masm) {
// Stack layout:
// sp[0] : number of parameters (tagged)
// sp[4] : address of receiver argument
// sp[8] : function
// Registers used over whole function:
// r6 : allocated object (tagged)
// r9 : mapped parameter count (tagged)
__ ldr(r1, MemOperand(sp, 0 * kPointerSize));
// r1 = parameter count (tagged)
// Check if the calling frame is an arguments adaptor frame.
Label runtime;
Label adaptor_frame, try_allocate;
__ ldr(r3, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
__ ldr(r2, MemOperand(r3, StandardFrameConstants::kContextOffset));
__ cmp(r2, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ b(eq, &adaptor_frame);
// No adaptor, parameter count = argument count.
__ mov(r2, r1);
__ b(&try_allocate);
// We have an adaptor frame. Patch the parameters pointer.
__ bind(&adaptor_frame);
__ ldr(r2, MemOperand(r3, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ add(r3, r3, Operand(r2, LSL, 1));
__ add(r3, r3, Operand(StandardFrameConstants::kCallerSPOffset));
__ str(r3, MemOperand(sp, 1 * kPointerSize));
// r1 = parameter count (tagged)
// r2 = argument count (tagged)
// Compute the mapped parameter count = min(r1, r2) in r1.
__ cmp(r1, Operand(r2));
__ mov(r1, Operand(r2), LeaveCC, gt);
__ 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.
__ cmp(r1, Operand(Smi::FromInt(0)));
__ mov(r9, Operand::Zero(), LeaveCC, eq);
__ mov(r9, Operand(r1, LSL, 1), LeaveCC, ne);
__ add(r9, r9, Operand(kParameterMapHeaderSize), LeaveCC, ne);
// 2. Backing store.
__ add(r9, r9, Operand(r2, LSL, 1));
__ add(r9, r9, Operand(FixedArray::kHeaderSize));
// 3. Arguments object.
__ add(r9, r9, Operand(Heap::kArgumentsObjectSize));
// Do the allocation of all three objects in one go.
__ Allocate(r9, r0, r3, r4, &runtime, TAG_OBJECT);
// r0 = address of new object(s) (tagged)
// r2 = argument count (tagged)
// Get the arguments boilerplate from the current native context into r4.
const int kNormalOffset =
Context::SlotOffset(Context::ARGUMENTS_BOILERPLATE_INDEX);
const int kAliasedOffset =
Context::SlotOffset(Context::ALIASED_ARGUMENTS_BOILERPLATE_INDEX);
__ ldr(r4, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
__ ldr(r4, FieldMemOperand(r4, GlobalObject::kNativeContextOffset));
__ cmp(r1, Operand::Zero());
__ ldr(r4, MemOperand(r4, kNormalOffset), eq);
__ ldr(r4, MemOperand(r4, kAliasedOffset), ne);
// r0 = address of new object (tagged)
// r1 = mapped parameter count (tagged)
// r2 = argument count (tagged)
// r4 = address of boilerplate object (tagged)
// Copy the JS object part.
for (int i = 0; i < JSObject::kHeaderSize; i += kPointerSize) {
__ ldr(r3, FieldMemOperand(r4, i));
__ str(r3, FieldMemOperand(r0, i));
}
// Set up the callee in-object property.
STATIC_ASSERT(Heap::kArgumentsCalleeIndex == 1);
__ ldr(r3, MemOperand(sp, 2 * kPointerSize));
const int kCalleeOffset = JSObject::kHeaderSize +
Heap::kArgumentsCalleeIndex * kPointerSize;
__ str(r3, FieldMemOperand(r0, kCalleeOffset));
// Use the length (smi tagged) and set that as an in-object property too.
STATIC_ASSERT(Heap::kArgumentsLengthIndex == 0);
const int kLengthOffset = JSObject::kHeaderSize +
Heap::kArgumentsLengthIndex * kPointerSize;
__ str(r2, FieldMemOperand(r0, kLengthOffset));
// Set up the elements pointer in the allocated arguments object.
// If we allocated a parameter map, r4 will point there, otherwise
// it will point to the backing store.
__ add(r4, r0, Operand(Heap::kArgumentsObjectSize));
__ str(r4, FieldMemOperand(r0, JSObject::kElementsOffset));
// r0 = address of new object (tagged)
// r1 = mapped parameter count (tagged)
// r2 = argument count (tagged)
// r4 = address of parameter map or backing store (tagged)
// Initialize parameter map. If there are no mapped arguments, we're done.
Label skip_parameter_map;
__ cmp(r1, Operand(Smi::FromInt(0)));
// Move backing store address to r3, because it is
// expected there when filling in the unmapped arguments.
__ mov(r3, r4, LeaveCC, eq);
__ b(eq, &skip_parameter_map);
__ LoadRoot(r6, Heap::kNonStrictArgumentsElementsMapRootIndex);
__ str(r6, FieldMemOperand(r4, FixedArray::kMapOffset));
__ add(r6, r1, Operand(Smi::FromInt(2)));
__ str(r6, FieldMemOperand(r4, FixedArray::kLengthOffset));
__ str(cp, FieldMemOperand(r4, FixedArray::kHeaderSize + 0 * kPointerSize));
__ add(r6, r4, Operand(r1, LSL, 1));
__ add(r6, r6, Operand(kParameterMapHeaderSize));
__ str(r6, FieldMemOperand(r4, FixedArray::kHeaderSize + 1 * kPointerSize));
// 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, parameters_test;
__ mov(r6, r1);
__ ldr(r9, MemOperand(sp, 0 * kPointerSize));
__ add(r9, r9, Operand(Smi::FromInt(Context::MIN_CONTEXT_SLOTS)));
__ sub(r9, r9, Operand(r1));
__ LoadRoot(r5, Heap::kTheHoleValueRootIndex);
__ add(r3, r4, Operand(r6, LSL, 1));
__ add(r3, r3, Operand(kParameterMapHeaderSize));
// r6 = loop variable (tagged)
// r1 = mapping index (tagged)
// r3 = address of backing store (tagged)
// r4 = address of parameter map (tagged), which is also the address of new
// object + Heap::kArgumentsObjectSize (tagged)
// r0 = temporary scratch (a.o., for address calculation)
// r5 = the hole value
__ jmp(¶meters_test);
__ bind(¶meters_loop);
__ sub(r6, r6, Operand(Smi::FromInt(1)));
__ mov(r0, Operand(r6, LSL, 1));
__ add(r0, r0, Operand(kParameterMapHeaderSize - kHeapObjectTag));
__ str(r9, MemOperand(r4, r0));
__ sub(r0, r0, Operand(kParameterMapHeaderSize - FixedArray::kHeaderSize));
__ str(r5, MemOperand(r3, r0));
__ add(r9, r9, Operand(Smi::FromInt(1)));
__ bind(¶meters_test);
__ cmp(r6, Operand(Smi::FromInt(0)));
__ b(ne, ¶meters_loop);
// Restore r0 = new object (tagged)
__ sub(r0, r4, Operand(Heap::kArgumentsObjectSize));
__ bind(&skip_parameter_map);
// r0 = address of new object (tagged)
// r2 = argument count (tagged)
// r3 = address of backing store (tagged)
// r5 = scratch
// Copy arguments header and remaining slots (if there are any).
__ LoadRoot(r5, Heap::kFixedArrayMapRootIndex);
__ str(r5, FieldMemOperand(r3, FixedArray::kMapOffset));
__ str(r2, FieldMemOperand(r3, FixedArray::kLengthOffset));
Label arguments_loop, arguments_test;
__ mov(r9, r1);
__ ldr(r4, MemOperand(sp, 1 * kPointerSize));
__ sub(r4, r4, Operand(r9, LSL, 1));
__ jmp(&arguments_test);
__ bind(&arguments_loop);
__ sub(r4, r4, Operand(kPointerSize));
__ ldr(r6, MemOperand(r4, 0));
__ add(r5, r3, Operand(r9, LSL, 1));
__ str(r6, FieldMemOperand(r5, FixedArray::kHeaderSize));
__ add(r9, r9, Operand(Smi::FromInt(1)));
__ bind(&arguments_test);
__ cmp(r9, Operand(r2));
__ b(lt, &arguments_loop);
// Return and remove the on-stack parameters.
__ add(sp, sp, Operand(3 * kPointerSize));
__ Ret();
// Do the runtime call to allocate the arguments object.
// r0 = address of new object (tagged)
// r2 = argument count (tagged)
__ bind(&runtime);
__ str(r2, MemOperand(sp, 0 * kPointerSize)); // Patch argument count.
__ TailCallRuntime(Runtime::kNewArgumentsFast, 3, 1);
}
void ArgumentsAccessStub::GenerateNewStrict(MacroAssembler* masm) {
// sp[0] : number of parameters
// sp[4] : receiver displacement
// sp[8] : function
// Check if the calling frame is an arguments adaptor frame.
Label adaptor_frame, try_allocate, runtime;
__ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
__ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
__ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
__ b(eq, &adaptor_frame);
// Get the length from the frame.
__ ldr(r1, MemOperand(sp, 0));
__ b(&try_allocate);
// Patch the arguments.length and the parameters pointer.
__ bind(&adaptor_frame);
__ ldr(r1, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
__ str(r1, MemOperand(sp, 0));
__ add(r3, r2, Operand::PointerOffsetFromSmiKey(r1));
__ add(r3, r3, Operand(StandardFrameConstants::kCallerSPOffset));
__ str(r3, MemOperand(sp, 1 * kPointerSize));
// Try the new space allocation. Start out with computing the size
// of the arguments object and the elements array in words.
Label add_arguments_object;
__ bind(&try_allocate);
__ SmiUntag(r1, SetCC);
__ b(eq, &add_arguments_object);
__ add(r1, r1, Operand(FixedArray::kHeaderSize / kPointerSize));
__ bind(&add_arguments_object);
__ add(r1, r1, Operand(Heap::kArgumentsObjectSizeStrict / kPointerSize));
// Do the allocation of both objects in one go.
__ Allocate(r1, r0, r2, r3, &runtime,
static_cast<AllocationFlags>(TAG_OBJECT | SIZE_IN_WORDS));
// Get the arguments boilerplate from the current native context.
__ ldr(r4, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
__ ldr(r4, FieldMemOperand(r4, GlobalObject::kNativeContextOffset));
__ ldr(r4, MemOperand(r4, Context::SlotOffset(
Context::STRICT_MODE_ARGUMENTS_BOILERPLATE_INDEX)));
// Copy the JS object part.
__ CopyFields(r0, r4, d0, JSObject::kHeaderSize / kPointerSize);
// Get the length (smi tagged) and set that as an in-object property too.
STATIC_ASSERT(Heap::kArgumentsLengthIndex == 0);
__ ldr(r1, MemOperand(sp, 0 * kPointerSize));
__ str(r1, FieldMemOperand(r0, JSObject::kHeaderSize +
Heap::kArgumentsLengthIndex * kPointerSize));
// If there are no actual arguments, we're done.
Label done;
__ cmp(r1, Operand::Zero());
__ b(eq, &done);
// Get the parameters pointer from the stack.
__ ldr(r2, MemOperand(sp, 1 * kPointerSize));
// Set up the elements pointer in the allocated arguments object and
// initialize the header in the elements fixed array.
__ add(r4, r0, Operand(Heap::kArgumentsObjectSizeStrict));
__ str(r4, FieldMemOperand(r0, JSObject::kElementsOffset));
__ LoadRoot(r3, Heap::kFixedArrayMapRootIndex);
__ str(r3, FieldMemOperand(r4, FixedArray::kMapOffset));
__ str(r1, FieldMemOperand(r4, FixedArray::kLengthOffset));
__ SmiUntag(r1);
// Copy the fixed array slots.
Label loop;
// Set up r4 to point to the first array slot.
__ add(r4, r4, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
__ bind(&loop);
// Pre-decrement r2 with kPointerSize on each iteration.
// Pre-decrement in order to skip receiver.
__ ldr(r3, MemOperand(r2, kPointerSize, NegPreIndex));
// Post-increment r4 with kPointerSize on each iteration.
__ str(r3, MemOperand(r4, kPointerSize, PostIndex));
__ sub(r1, r1, Operand(1));
__ cmp(r1, Operand::Zero());
__ b(ne, &loop);
// Return and remove the on-stack parameters.
__ bind(&done);
__ add(sp, sp, Operand(3 * kPointerSize));
__ Ret();
// Do the runtime call to allocate the arguments object.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kNewStrictArgumentsFast, 3, 1);
}
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, 4, 1);
#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;
// 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 = r4;
Register regexp_data = r5;
Register last_match_info_elements = no_reg; // will be r6;
// Ensure that a RegExp stack is allocated.
Isolate* isolate = masm->isolate();
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(r0, Operand(address_of_regexp_stack_memory_size));
__ ldr(r0, MemOperand(r0, 0));
__ cmp(r0, Operand::Zero());
__ b(eq, &runtime);
// Check that the first argument is a JSRegExp object.
__ ldr(r0, MemOperand(sp, kJSRegExpOffset));
__ JumpIfSmi(r0, &runtime);
__ CompareObjectType(r0, r1, r1, JS_REGEXP_TYPE);
__ b(ne, &runtime);
// Check that the RegExp has been compiled (data contains a fixed array).
__ ldr(regexp_data, FieldMemOperand(r0, JSRegExp::kDataOffset));
if (FLAG_debug_code) {
__ SmiTst(regexp_data);
__ Check(ne, kUnexpectedTypeForRegExpDataFixedArrayExpected);
__ CompareObjectType(regexp_data, r0, r0, FIXED_ARRAY_TYPE);
__ Check(eq, kUnexpectedTypeForRegExpDataFixedArrayExpected);
}
// regexp_data: RegExp data (FixedArray)
// Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
__ ldr(r0, FieldMemOperand(regexp_data, JSRegExp::kDataTagOffset));
__ cmp(r0, Operand(Smi::FromInt(JSRegExp::IRREGEXP)));
__ b(ne, &runtime);
// regexp_data: RegExp data (FixedArray)
// Check that the number of captures fit in the static offsets vector buffer.
__ ldr(r2,
FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
// Check (number_of_captures + 1) * 2 <= offsets vector size
// Or number_of_captures * 2 <= offsets vector size - 2
// Multiplying by 2 comes for free since r2 is smi-tagged.
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
STATIC_ASSERT(Isolate::kJSRegexpStaticOffsetsVectorSize >= 2);
__ cmp(r2, Operand(Isolate::kJSRegexpStaticOffsetsVectorSize - 2));
__ b(hi, &runtime);
// Reset offset for possibly sliced string.
__ mov(r9, Operand::Zero());
__ ldr(subject, MemOperand(sp, kSubjectOffset));
__ JumpIfSmi(subject, &runtime);
__ mov(r3, subject); // Make a copy of the original subject string.
__ ldr(r0, FieldMemOperand(subject, HeapObject::kMapOffset));
__ ldrb(r0, FieldMemOperand(r0, Map::kInstanceTypeOffset));
// subject: subject string
// r3: subject string
// r0: 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).
__ and_(r1,
r0,
Operand(kIsNotStringMask |
kStringRepresentationMask |
kShortExternalStringMask),
SetCC);
STATIC_ASSERT((kStringTag | kSeqStringTag) == 0);
__ b(eq, &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);
__ cmp(r1, Operand(kExternalStringTag));
__ b(ge, ¬_seq_nor_cons); // Go to (6).
// (3) Cons string. Check that it's flat.
// Replace subject with first string and reload instance type.
__ ldr(r0, FieldMemOperand(subject, ConsString::kSecondOffset));
__ CompareRoot(r0, Heap::kempty_stringRootIndex);
__ b(ne, &runtime);
__ ldr(subject, FieldMemOperand(subject, ConsString::kFirstOffset));
// (4) Is subject external? If yes, go to (7).
__ bind(&check_underlying);
__ ldr(r0, FieldMemOperand(subject, HeapObject::kMapOffset));
__ ldrb(r0, FieldMemOperand(r0, Map::kInstanceTypeOffset));
STATIC_ASSERT(kSeqStringTag == 0);
__ tst(r0, Operand(kStringRepresentationMask));
// The underlying external string is never a short external string.
STATIC_CHECK(ExternalString::kMaxShortLength < ConsString::kMinLength);
STATIC_CHECK(ExternalString::kMaxShortLength < SlicedString::kMinLength);
__ b(ne, &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)
// r3: original subject string
// Load previous index and check range before r3 is overwritten. We have to
// use r3 instead of subject here because subject might have been only made
// to look like a sequential string when it actually is an external string.
__ ldr(r1, MemOperand(sp, kPreviousIndexOffset));
__ JumpIfNotSmi(r1, &runtime);
__ ldr(r3, FieldMemOperand(r3, String::kLengthOffset));
__ cmp(r3, Operand(r1));
__ b(ls, &runtime);
__ SmiUntag(r1);
STATIC_ASSERT(4 == kOneByteStringTag);
STATIC_ASSERT(kTwoByteStringTag == 0);
__ and_(r0, r0, Operand(kStringEncodingMask));
__ mov(r3, Operand(r0, ASR, 2), SetCC);
__ ldr(r6, FieldMemOperand(regexp_data, JSRegExp::kDataAsciiCodeOffset), ne);
__ ldr(r6, FieldMemOperand(regexp_data, JSRegExp::kDataUC16CodeOffset), eq);
// (E) Carry on. String handling is done.
// r6: 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(r6, &runtime);
// r1: previous index
// r3: encoding of subject string (1 if ASCII, 0 if two_byte);
// r6: 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, r0, r2);
// Isolates: note we add an additional parameter here (isolate pointer).
const int kRegExpExecuteArguments = 9;
const int kParameterRegisters = 4;
__ 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 9 (sp[20]): Pass current isolate address.
__ mov(r0, Operand(ExternalReference::isolate_address(isolate)));
__ str(r0, MemOperand(sp, 5 * kPointerSize));
// Argument 8 (sp[16]): Indicate that this is a direct call from JavaScript.
__ mov(r0, Operand(1));
__ str(r0, MemOperand(sp, 4 * kPointerSize));
// Argument 7 (sp[12]): Start (high end) of backtracking stack memory area.
__ mov(r0, Operand(address_of_regexp_stack_memory_address));
__ ldr(r0, MemOperand(r0, 0));
__ mov(r2, Operand(address_of_regexp_stack_memory_size));
__ ldr(r2, MemOperand(r2, 0));
__ add(r0, r0, Operand(r2));
__ str(r0, MemOperand(sp, 3 * kPointerSize));
// Argument 6: Set the number of capture registers to zero to force global
// regexps to behave as non-global. This does not affect non-global regexps.
__ mov(r0, Operand::Zero());
__ str(r0, MemOperand(sp, 2 * kPointerSize));
// Argument 5 (sp[4]): static offsets vector buffer.
__ mov(r0,
Operand(ExternalReference::address_of_static_offsets_vector(isolate)));
__ str(r0, MemOperand(sp, 1 * kPointerSize));
// For arguments 4 and 3 get string length, calculate start of string data and
// calculate the shift of the index (0 for ASCII and 1 for two byte).
__ add(r7, subject, Operand(SeqString::kHeaderSize - kHeapObjectTag));
__ eor(r3, r3, Operand(1));
// Load the length from the original subject string from the previous stack
// frame. Therefore we have to use fp, which points exactly to two 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.)
__ ldr(subject, MemOperand(fp, kSubjectOffset + 2 * kPointerSize));
// If slice offset is not 0, load the length from the original sliced string.
// Argument 4, r3: End of string data
// Argument 3, r2: Start of string data
// Prepare start and end index of the input.
__ add(r9, r7, Operand(r9, LSL, r3));
__ add(r2, r9, Operand(r1, LSL, r3));
__ ldr(r7, FieldMemOperand(subject, String::kLengthOffset));
__ SmiUntag(r7);
__ add(r3, r9, Operand(r7, LSL, r3));
// Argument 2 (r1): Previous index.
// Already there
// Argument 1 (r0): Subject string.
__ mov(r0, subject);
// Locate the code entry and call it.
__ add(r6, r6, Operand(Code::kHeaderSize - kHeapObjectTag));
DirectCEntryStub stub;
stub.GenerateCall(masm, r6);
__ LeaveExitFrame(false, no_reg, true);
last_match_info_elements = r6;
// r0: result
// subject: subject string (callee saved)
// regexp_data: RegExp data (callee saved)
// last_match_info_elements: Last match info elements (callee saved)
// Check the result.
Label success;
__ cmp(r0, Operand(1));
// We expect exactly one result since we force the called regexp to behave
// as non-global.
__ b(eq, &success);
Label failure;
__ cmp(r0, Operand(NativeRegExpMacroAssembler::FAILURE));
__ b(eq, &failure);
__ cmp(r0, Operand(NativeRegExpMacroAssembler::EXCEPTION));
// If not exception it can only be retry. Handle that in the runtime system.
__ b(ne, &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(r1, Operand(isolate->factory()->the_hole_value()));
__ mov(r2, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
isolate)));
__ ldr(r0, MemOperand(r2, 0));
__ cmp(r0, r1);
__ b(eq, &runtime);
__ str(r1, MemOperand(r2, 0)); // Clear pending exception.
// Check if the exception is a termination. If so, throw as uncatchable.
__ CompareRoot(r0, Heap::kTerminationExceptionRootIndex);
Label termination_exception;
__ b(eq, &termination_exception);
__ Throw(r0);
__ bind(&termination_exception);
__ ThrowUncatchable(r0);
__ bind(&failure);
// For failure and exception return null.
__ mov(r0, Operand(masm->isolate()->factory()->null_value()));
__ add(sp, sp, Operand(4 * kPointerSize));
__ Ret();
// Process the result from the native regexp code.
__ bind(&success);
__ ldr(r1,
FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
// Calculate number of capture registers (number_of_captures + 1) * 2.
// Multiplying by 2 comes for free since r1 is smi-tagged.
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
__ add(r1, r1, Operand(2)); // r1 was a smi.
__ ldr(r0, MemOperand(sp, kLastMatchInfoOffset));
__ JumpIfSmi(r0, &runtime);
__ CompareObjectType(r0, r2, r2, JS_ARRAY_TYPE);
__ b(ne, &runtime);
// Check that the JSArray is in fast case.
__ ldr(last_match_info_elements,
FieldMemOperand(r0, JSArray::kElementsOffset));
__ ldr(r0, FieldMemOperand(last_match_info_elements, HeapObject::kMapOffset));
__ CompareRoot(r0, Heap::kFixedArrayMapRootIndex);
__ b(ne, &runtime);
// Check that the last match info has space for the capture registers and the
// additional information.
__ ldr(r0,
FieldMemOperand(last_match_info_elements, FixedArray::kLengthOffset));
__ add(r2, r1, Operand(RegExpImpl::kLastMatchOverhead));
__ cmp(r2, Operand::SmiUntag(r0));
__ b(gt, &runtime);
// r1: number of capture registers
// r4: subject string
// Store the capture count.
__ SmiTag(r2, r1);
__ str(r2, FieldMemOperand(last_match_info_elements,
RegExpImpl::kLastCaptureCountOffset));
// Store last subject and last input.
__ str(subject,
FieldMemOperand(last_match_info_elements,
RegExpImpl::kLastSubjectOffset));
__ mov(r2, subject);
__ RecordWriteField(last_match_info_elements,
RegExpImpl::kLastSubjectOffset,
subject,
r3,
kLRHasNotBeenSaved,
kDontSaveFPRegs);
__ mov(subject, r2);
__ str(subject,
FieldMemOperand(last_match_info_elements,
RegExpImpl::kLastInputOffset));
__ RecordWriteField(last_match_info_elements,
RegExpImpl::kLastInputOffset,
subject,
r3,
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(r2, Operand(address_of_static_offsets_vector));
// r1: number of capture registers
// r2: offsets vector
Label next_capture, done;
// Capture register counter starts from number of capture registers and
// counts down until wraping after zero.
__ add(r0,
last_match_info_elements,
Operand(RegExpImpl::kFirstCaptureOffset - kHeapObjectTag));
__ bind(&next_capture);
__ sub(r1, r1, Operand(1), SetCC);
__ b(mi, &done);
// Read the value from the static offsets vector buffer.
__ ldr(r3, MemOperand(r2, kPointerSize, PostIndex));
// Store the smi value in the last match info.
__ SmiTag(r3);
__ str(r3, MemOperand(r0, kPointerSize, PostIndex));
__ jmp(&next_capture);
__ bind(&done);
// Return last match info.
__ ldr(r0, MemOperand(sp, kLastMatchInfoOffset));
__ add(sp, sp, Operand(4 * kPointerSize));
__ Ret();
// Do the runtime call to execute the regexp.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
// 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.
__ b(gt, ¬_long_external); // Go to (8).
// (7) External string. Make it, offset-wise, look like a sequential string.
__ bind(&external_string);
__ ldr(r0, FieldMemOperand(subject, HeapObject::kMapOffset));
__ ldrb(r0, FieldMemOperand(r0, 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.
__ tst(r0, Operand(kIsIndirectStringMask));
__ Assert(eq, kExternalStringExpectedButNotFound);
}
__ ldr(subject,
FieldMemOperand(subject, ExternalString::kResourceDataOffset));
// Move the pointer so that offset-wise, it looks like a sequential string.
STATIC_ASSERT(SeqTwoByteString::kHeaderSize == SeqOneByteString::kHeaderSize);
__ sub(subject,
subject,
Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
__ jmp(&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);
__ tst(r1, Operand(kIsNotStringMask | kShortExternalStringMask));
__ b(ne, &runtime);
// (9) Sliced string. Replace subject with parent. Go to (4).
// Load offset into r9 and replace subject string with parent.
__ ldr(r9, FieldMemOperand(subject, SlicedString::kOffsetOffset));
__ SmiUntag(r9);
__ ldr(subject, FieldMemOperand(subject, SlicedString::kParentOffset));
__ jmp(&check_underlying); // Go to (4).
#endif // V8_INTERPRETED_REGEXP
}
void RegExpConstructResultStub::Generate(MacroAssembler* masm) {
const int kMaxInlineLength = 100;
Label slowcase;
Label done;
Factory* factory = masm->isolate()->factory();
__ ldr(r1, MemOperand(sp, kPointerSize * 2));
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize == 1);
__ JumpIfNotSmi(r1, &slowcase);
__ cmp(r1, Operand(Smi::FromInt(kMaxInlineLength)));
__ b(hi, &slowcase);
// Smi-tagging is equivalent to multiplying by 2.
// Allocate RegExpResult followed by FixedArray with size in ebx.
// JSArray: [Map][empty properties][Elements][Length-smi][index][input]
// Elements: [Map][Length][..elements..]
// Size of JSArray with two in-object properties and the header of a
// FixedArray.
int objects_size =
(JSRegExpResult::kSize + FixedArray::kHeaderSize) / kPointerSize;
__ SmiUntag(r5, r1);
__ add(r2, r5, Operand(objects_size));
__ Allocate(
r2, // In: Size, in words.
r0, // Out: Start of allocation (tagged).
r3, // Scratch register.
r4, // Scratch register.
&slowcase,
static_cast<AllocationFlags>(TAG_OBJECT | SIZE_IN_WORDS));
// r0: Start of allocated area, object-tagged.
// r1: Number of elements in array, as smi.
// r5: Number of elements, untagged.
// Set JSArray map to global.regexp_result_map().
// Set empty properties FixedArray.
// Set elements to point to FixedArray allocated right after the JSArray.
// Interleave operations for better latency.
__ ldr(r2, ContextOperand(cp, Context::GLOBAL_OBJECT_INDEX));
__ add(r3, r0, Operand(JSRegExpResult::kSize));
__ mov(r4, Operand(factory->empty_fixed_array()));
__ ldr(r2, FieldMemOperand(r2, GlobalObject::kNativeContextOffset));
__ str(r3, FieldMemOperand(r0, JSObject::kElementsOffset));
__ ldr(r2, ContextOperand(r2, Context::REGEXP_RESULT_MAP_INDEX));
__ str(r4, FieldMemOperand(r0, JSObject::kPropertiesOffset));
__ str(r2, FieldMemOperand(r0, HeapObject::kMapOffset));
// Set input, index and length fields from arguments.
__ ldr(r1, MemOperand(sp, kPointerSize * 0));
__ ldr(r2, MemOperand(sp, kPointerSize * 1));
__ ldr(r6, MemOperand(sp, kPointerSize * 2));
__ str(r1, FieldMemOperand(r0, JSRegExpResult::kInputOffset));
__ str(r2, FieldMemOperand(r0, JSRegExpResult::kIndexOffset));
__ str(r6, FieldMemOperand(r0, JSArray::kLengthOffset));
// Fill out the elements FixedArray.
// r0: JSArray, tagged.
// r3: FixedArray, tagged.
// r5: Number of elements in array, untagged.
// Set map.
__ mov(r2, Operand(factory->fixed_array_map()));
__ str(r2, FieldMemOperand(r3, HeapObject::kMapOffset));
// Set FixedArray length.
__ SmiTag(r6, r5);
__ str(r6, FieldMemOperand(r3, FixedArray::kLengthOffset));
// Fill contents of fixed-array with undefined.
__ LoadRoot(r2, Heap::kUndefinedValueRootIndex);
__ add(r3, r3, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
// Fill fixed array elements with undefined.
// r0: JSArray, tagged.
// r2: undefined.
// r3: Start of elements in FixedArray.
// r5: Number of elements to fill.
Label loop;
__ cmp(r5, Operand::Zero());
__ bind(&loop);
__ b(le, &done); // Jump if r5 is negative or zero.
__ sub(r5, r5, Operand(1), SetCC);
__ str(r2, MemOperand(r3, r5, LSL, kPointerSizeLog2));
__ jmp(&loop);
__ bind(&done);
__ add(sp, sp, Operand(3 * kPointerSize));
__ Ret();
__ bind(&slowcase);
__ TailCallRuntime(Runtime::kRegExpConstructResult, 3, 1);
}
static void GenerateRecordCallTarget(MacroAssembler* masm) {
// Cache the called function in a global property cell. Cache states
// are uninitialized, monomorphic (indicated by a JSFunction), and
// megamorphic.
// r0 : number of arguments to the construct function
// r1 : the function to call
// r2 : cache cell for call target
Label initialize, done, miss, megamorphic, not_array_function;
ASSERT_EQ(*TypeFeedbackCells::MegamorphicSentinel(masm->isolate()),
masm->isolate()->heap()->undefined_value());
ASSERT_EQ(*TypeFeedbackCells::UninitializedSentinel(masm->isolate()),
masm->isolate()->heap()->the_hole_value());
// Load the cache state into r3.
__ ldr(r3, FieldMemOperand(r2, Cell::kValueOffset));
// A monomorphic cache hit or an already megamorphic state: invoke the
// function without changing the state.
__ cmp(r3, r1);
__ b(eq, &done);
// 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 cell either some other function or an
// AllocationSite. Do a map check on the object in ecx.
__ ldr(r5, FieldMemOperand(r3, 0));
__ CompareRoot(r5, Heap::kAllocationSiteMapRootIndex);
__ b(ne, &miss);
// Make sure the function is the Array() function
__ LoadArrayFunction(r3);
__ cmp(r1, r3);
__ b(ne, &megamorphic);
__ jmp(&done);
__ bind(&miss);
// A monomorphic miss (i.e, here the cache is not uninitialized) goes
// megamorphic.
__ CompareRoot(r3, Heap::kTheHoleValueRootIndex);
__ b(eq, &initialize);
// MegamorphicSentinel is an immortal immovable object (undefined) so no
// write-barrier is needed.
__ bind(&megamorphic);
__ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
__ str(ip, FieldMemOperand(r2, Cell::kValueOffset));
__ jmp(&done);
// An uninitialized cache is patched with the function or sentinel to
// indicate the ElementsKind if function is the Array constructor.
__ bind(&initialize);
// Make sure the function is the Array() function
__ LoadArrayFunction(r3);
__ cmp(r1, r3);
__ b(ne, ¬_array_function);
// The target function is the Array constructor,
// Create an AllocationSite if we don't already have it, store it in the cell
{
FrameScope scope(masm, StackFrame::INTERNAL);
// Arguments register must be smi-tagged to call out.
__ SmiTag(r0);
__ Push(r2, r1, r0);
CreateAllocationSiteStub create_stub;
__ CallStub(&create_stub);
__ Pop(r2, r1, r0);
__ SmiUntag(r0);
}
__ b(&done);
__ bind(¬_array_function);
__ str(r1, FieldMemOperand(r2, Cell::kValueOffset));
// No need for a write barrier here - cells are rescanned.
__ bind(&done);
}
void CallFunctionStub::Generate(MacroAssembler* masm) {
// r1 : the function to call
// r2 : cache cell for call target
Label slow, non_function;
// The receiver might implicitly be the global object. This is
// indicated by passing the hole as the receiver to the call
// function stub.
if (ReceiverMightBeImplicit()) {
Label call;
// Get the receiver from the stack.
// function, receiver [, arguments]
__ ldr(r4, MemOperand(sp, argc_ * kPointerSize));
// Call as function is indicated with the hole.
__ CompareRoot(r4, Heap::kTheHoleValueRootIndex);
__ b(ne, &call);
// Patch the receiver on the stack with the global receiver object.
__ ldr(r3,
MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
__ ldr(r3, FieldMemOperand(r3, GlobalObject::kGlobalReceiverOffset));
__ str(r3, MemOperand(sp, argc_ * kPointerSize));
__ bind(&call);
}
// Check that the function is really a JavaScript function.
// r1: pushed function (to be verified)
__ JumpIfSmi(r1, &non_function);
// Get the map of the function object.
__ CompareObjectType(r1, r3, r3, JS_FUNCTION_TYPE);
__ b(ne, &slow);
if (RecordCallTarget()) {
GenerateRecordCallTarget(masm);
}
// Fast-case: Invoke the function now.
// r1: pushed function
ParameterCount actual(argc_);
if (ReceiverMightBeImplicit()) {
Label call_as_function;
__ CompareRoot(r4, Heap::kTheHoleValueRootIndex);
__ b(eq, &call_as_function);
__ InvokeFunction(r1,
actual,
JUMP_FUNCTION,
NullCallWrapper(),
CALL_AS_METHOD);
__ bind(&call_as_function);
}
__ InvokeFunction(r1,
actual,
JUMP_FUNCTION,
NullCallWrapper(),
CALL_AS_FUNCTION);
// Slow-case: Non-function called.
__ bind(&slow);
if (RecordCallTarget()) {
// If there is a call target cache, mark it megamorphic in the
// non-function case. MegamorphicSentinel is an immortal immovable
// object (undefined) so no write barrier is needed.
ASSERT_EQ(*TypeFeedbackCells::MegamorphicSentinel(masm->isolate()),
masm->isolate()->heap()->undefined_value());
__ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
__ str(ip, FieldMemOperand(r2, Cell::kValueOffset));
}
// Check for function proxy.
__ cmp(r3, Operand(JS_FUNCTION_PROXY_TYPE));
__ b(ne, &non_function);
__ push(r1); // put proxy as additional argument
__ mov(r0, Operand(argc_ + 1, RelocInfo::NONE32));
__ mov(r2, Operand::Zero());
__ GetBuiltinEntry(r3, Builtins::CALL_FUNCTION_PROXY);
__ SetCallKind(r5, CALL_AS_METHOD);
{
Handle<Code> adaptor =
masm->isolate()->builtins()->ArgumentsAdaptorTrampoline();
__ Jump(adaptor, RelocInfo::CODE_TARGET);
}
// CALL_NON_FUNCTION expects the non-function callee as receiver (instead
// of the original receiver from the call site).
__ bind(&non_function);
__ str(r1, MemOperand(sp, argc_ * kPointerSize));
__ mov(r0, Operand(argc_)); // Set up the number of arguments.
__ mov(r2, Operand::Zero());
__ GetBuiltinEntry(r3, Builtins::CALL_NON_FUNCTION);
__ SetCallKind(r5, CALL_AS_METHOD);
__ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
RelocInfo::CODE_TARGET);
}
void CallConstructStub::Generate(MacroAssembler* masm) {
// r0 : number of arguments
// r1 : the function to call
// r2 : cache cell for call target
Label slow, non_function_call;
// Check that the function is not a smi.
__ JumpIfSmi(r1, &non_function_call);
// Check that the function is a JSFunction.
__ CompareObjectType(r1, r3, r3, JS_FUNCTION_TYPE);
__ b(ne, &slow);
if (RecordCallTarget()) {
GenerateRecordCallTarget(masm);
}
// Jump to the function-specific construct stub.
Register jmp_reg = r3;
__ ldr(jmp_reg, FieldMemOperand(r1, JSFunction::kSharedFunctionInfoOffset));
__ ldr(jmp_reg, FieldMemOperand(jmp_reg,
SharedFunctionInfo::kConstructStubOffset));
__ add(pc, jmp_reg, Operand(Code::kHeaderSize - kHeapObjectTag));
// r0: number of arguments
// r1: called object
// r3: object type
Label do_call;
__ bind(&slow);
__ cmp(r3, Operand(JS_FUNCTION_PROXY_TYPE));
__ b(ne, &non_function_call);
__ GetBuiltinEntry(r3, Builtins::CALL_FUNCTION_PROXY_AS_CONSTRUCTOR);
__ jmp(&do_call);
__ bind(&non_function_call);
__ GetBuiltinEntry(r3, Builtins::CALL_NON_FUNCTION_AS_CONSTRUCTOR);
__ bind(&do_call);
// Set expected number of arguments to zero (not changing r0).
__ mov(r2, Operand::Zero());
__ SetCallKind(r5, CALL_AS_METHOD);
__ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
RelocInfo::CODE_TARGET);
}
// StringCharCodeAtGenerator
void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) {
Label flat_string;
Label ascii_string;
Label got_char_code;
Label sliced_string;
// If the receiver is a smi trigger the non-string case.
__ JumpIfSmi(object_, receiver_not_string_);
// Fetch the instance type of the receiver into result register.
__ ldr(result_, FieldMemOperand(object_, HeapObject::kMapOffset));
__ ldrb(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset));
// If the receiver is not a string trigger the non-string case.
__ tst(result_, Operand(kIsNotStringMask));
__ b(ne, 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.
__ ldr(ip, FieldMemOperand(object_, String::kLengthOffset));
__ cmp(ip, Operand(index_));
__ b(ls, index_out_of_range_);
__ SmiUntag(index_);
StringCharLoadGenerator::Generate(masm,
object_,
index_,
result_,
&call_runtime_);
__ SmiTag(result_);
__ bind(&exit_);
}
void StringCharCodeAtGenerator::GenerateSlow(
MacroAssembler* masm,
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);
__ push(object_);
__ push(index_); // Consumed by runtime conversion function.
if (index_flags_ == STRING_INDEX_IS_NUMBER) {
__ CallRuntime(Runtime::kNumberToIntegerMapMinusZero, 1);
} else {
ASSERT(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX);
// NumberToSmi discards numbers that are not exact integers.
__ CallRuntime(Runtime::kNumberToSmi, 1);
}
// Save the conversion result before the pop instructions below
// have a chance to overwrite it.
__ Move(index_, r0);
__ pop(object_);
// Reload the instance type.
__ ldr(result_, FieldMemOperand(object_, HeapObject::kMapOffset));
__ ldrb(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.
__ jmp(&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::kStringCharCodeAt, 2);
__ Move(result_, r0);
call_helper.AfterCall(masm);
__ jmp(&exit_);
__ Abort(kUnexpectedFallthroughFromCharCodeAtSlowCase);
}
// -------------------------------------------------------------------------
// StringCharFromCodeGenerator
void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) {
// Fast case of Heap::LookupSingleCharacterStringFromCode.
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiShiftSize == 0);
ASSERT(IsPowerOf2(String::kMaxOneByteCharCode + 1));
__ tst(code_,
Operand(kSmiTagMask |
((~String::kMaxOneByteCharCode) << kSmiTagSize)));
__ b(ne, &slow_case_);
__ LoadRoot(result_, Heap::kSingleCharacterStringCacheRootIndex);
// At this point code register contains smi tagged ASCII char code.
__ add(result_, result_, Operand::PointerOffsetFromSmiKey(code_));
__ ldr(result_, FieldMemOperand(result_, FixedArray::kHeaderSize));
__ CompareRoot(result_, Heap::kUndefinedValueRootIndex);
__ b(eq, &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::kCharFromCode, 1);
__ Move(result_, r0);
call_helper.AfterCall(masm);
__ jmp(&exit_);
__ Abort(kUnexpectedFallthroughFromCharFromCodeSlowCase);
}
void StringHelper::GenerateCopyCharacters(MacroAssembler* masm,
Register dest,
Register src,
Register count,
Register scratch,
bool ascii) {
Label loop;
Label done;
// This loop just copies one character at a time, as it is only used for very
// short strings.
if (!ascii) {
__ add(count, count, Operand(count), SetCC);
} else {
__ cmp(count, Operand::Zero());
}
__ b(eq, &done);
__ bind(&loop);
__ ldrb(scratch, MemOperand(src, 1, PostIndex));
// Perform sub between load and dependent store to get the load time to
// complete.
__ sub(count, count, Operand(1), SetCC);
__ strb(scratch, MemOperand(dest, 1, PostIndex));
// last iteration.
__ b(gt, &loop);
__ bind(&done);
}
enum CopyCharactersFlags {
COPY_ASCII = 1,
DEST_ALWAYS_ALIGNED = 2
};
void StringHelper::GenerateCopyCharactersLong(MacroAssembler* masm,
Register dest,
Register src,
Register count,
Register scratch1,
Register scratch2,
Register scratch3,
Register scratch4,
int flags) {
bool ascii = (flags & COPY_ASCII) != 0;
bool dest_always_aligned = (flags & DEST_ALWAYS_ALIGNED) != 0;
if (dest_always_aligned && FLAG_debug_code) {
// Check that destination is actually word aligned if the flag says
// that it is.
__ tst(dest, Operand(kPointerAlignmentMask));
__ Check(eq, kDestinationOfCopyNotAligned);
}
const int kReadAlignment = 4;
const int kReadAlignmentMask = kReadAlignment - 1;
// Ensure that reading an entire aligned word containing the last character
// of a string will not read outside the allocated area (because we pad up
// to kObjectAlignment).
STATIC_ASSERT(kObjectAlignment >= kReadAlignment);
// Assumes word reads and writes are little endian.
// Nothing to do for zero characters.
Label done;
if (!ascii) {
__ add(count, count, Operand(count), SetCC);
} else {
__ cmp(count, Operand::Zero());
}
__ b(eq, &done);
// Assume that you cannot read (or write) unaligned.
Label byte_loop;
// Must copy at least eight bytes, otherwise just do it one byte at a time.
__ cmp(count, Operand(8));
__ add(count, dest, Operand(count));
Register limit = count; // Read until src equals this.
__ b(lt, &byte_loop);
if (!dest_always_aligned) {
// Align dest by byte copying. Copies between zero and three bytes.
__ and_(scratch4, dest, Operand(kReadAlignmentMask), SetCC);
Label dest_aligned;
__ b(eq, &dest_aligned);
__ cmp(scratch4, Operand(2));
__ ldrb(scratch1, MemOperand(src, 1, PostIndex));
__ ldrb(scratch2, MemOperand(src, 1, PostIndex), le);
__ ldrb(scratch3, MemOperand(src, 1, PostIndex), lt);
__ strb(scratch1, MemOperand(dest, 1, PostIndex));
__ strb(scratch2, MemOperand(dest, 1, PostIndex), le);
__ strb(scratch3, MemOperand(dest, 1, PostIndex), lt);
__ bind(&dest_aligned);
}
Label simple_loop;
__ sub(scratch4, dest, Operand(src));
__ and_(scratch4, scratch4, Operand(0x03), SetCC);
__ b(eq, &simple_loop);
// Shift register is number of bits in a source word that
// must be combined with bits in the next source word in order
// to create a destination word.
// Complex loop for src/dst that are not aligned the same way.
{
Label loop;
__ mov(scratch4, Operand(scratch4, LSL, 3));
Register left_shift = scratch4;
__ and_(src, src, Operand(~3)); // Round down to load previous word.
__ ldr(scratch1, MemOperand(src, 4, PostIndex));
// Store the "shift" most significant bits of scratch in the least
// signficant bits (i.e., shift down by (32-shift)).
__ rsb(scratch2, left_shift, Operand(32));
Register right_shift = scratch2;
__ mov(scratch1, Operand(scratch1, LSR, right_shift));
__ bind(&loop);
__ ldr(scratch3, MemOperand(src, 4, PostIndex));
__ orr(scratch1, scratch1, Operand(scratch3, LSL, left_shift));
__ str(scratch1, MemOperand(dest, 4, PostIndex));
__ mov(scratch1, Operand(scratch3, LSR, right_shift));
// Loop if four or more bytes left to copy.
__ sub(scratch3, limit, Operand(dest));
__ sub(scratch3, scratch3, Operand(4), SetCC);
__ b(ge, &loop);
}
// There is now between zero and three bytes left to copy (negative that
// number is in scratch3), and between one and three bytes already read into
// scratch1 (eight times that number in scratch4). We may have read past
// the end of the string, but because objects are aligned, we have not read
// past the end of the object.
// Find the minimum of remaining characters to move and preloaded characters
// and write those as bytes.
__ add(scratch3, scratch3, Operand(4), SetCC);
__ b(eq, &done);
__ cmp(scratch4, Operand(scratch3, LSL, 3), ne);
// Move minimum of bytes read and bytes left to copy to scratch4.
__ mov(scratch3, Operand(scratch4, LSR, 3), LeaveCC, lt);
// Between one and three (value in scratch3) characters already read into
// scratch ready to write.
__ cmp(scratch3, Operand(2));
__ strb(scratch1, MemOperand(dest, 1, PostIndex));
__ mov(scratch1, Operand(scratch1, LSR, 8), LeaveCC, ge);
__ strb(scratch1, MemOperand(dest, 1, PostIndex), ge);
__ mov(scratch1, Operand(scratch1, LSR, 8), LeaveCC, gt);
__ strb(scratch1, MemOperand(dest, 1, PostIndex), gt);
// Copy any remaining bytes.
__ b(&byte_loop);
// Simple loop.
// Copy words from src to dst, until less than four bytes left.
// Both src and dest are word aligned.
__ bind(&simple_loop);
{
Label loop;
__ bind(&loop);
__ ldr(scratch1, MemOperand(src, 4, PostIndex));
__ sub(scratch3, limit, Operand(dest));
__ str(scratch1, MemOperand(dest, 4, PostIndex));
// Compare to 8, not 4, because we do the substraction before increasing
// dest.
__ cmp(scratch3, Operand(8));
__ b(ge, &loop);
}
// Copy bytes from src to dst until dst hits limit.
__ bind(&byte_loop);
__ cmp(dest, Operand(limit));
__ ldrb(scratch1, MemOperand(src, 1, PostIndex), lt);
__ b(ge, &done);
__ strb(scratch1, MemOperand(dest, 1, PostIndex));
__ b(&byte_loop);
__ bind(&done);
}
void StringHelper::GenerateTwoCharacterStringTableProbe(MacroAssembler* masm,
Register c1,
Register c2,
Register scratch1,
Register scratch2,
Register scratch3,
Register scratch4,
Register scratch5,
Label* not_found) {
// Register scratch3 is the general scratch register in this function.
Register scratch = scratch3;
// Make sure that both characters are not digits as such strings has a
// different hash algorithm. Don't try to look for these in the string table.
Label not_array_index;
__ sub(scratch, c1, Operand(static_cast<int>('0')));
__ cmp(scratch, Operand(static_cast<int>('9' - '0')));
__ b(hi, ¬_array_index);
__ sub(scratch, c2, Operand(static_cast<int>('0')));
__ cmp(scratch, Operand(static_cast<int>('9' - '0')));
// If check failed combine both characters into single halfword.
// This is required by the contract of the method: code at the
// not_found branch expects this combination in c1 register
__ orr(c1, c1, Operand(c2, LSL, kBitsPerByte), LeaveCC, ls);
__ b(ls, not_found);
__ bind(¬_array_index);
// Calculate the two character string hash.
Register hash = scratch1;
StringHelper::GenerateHashInit(masm, hash, c1);
StringHelper::GenerateHashAddCharacter(masm, hash, c2);
StringHelper::GenerateHashGetHash(masm, hash);
// Collect the two characters in a register.
Register chars = c1;
__ orr(chars, chars, Operand(c2, LSL, kBitsPerByte));
// chars: two character string, char 1 in byte 0 and char 2 in byte 1.
// hash: hash of two character string.
// Load string table
// Load address of first element of the string table.
Register string_table = c2;
__ LoadRoot(string_table, Heap::kStringTableRootIndex);
Register undefined = scratch4;
__ LoadRoot(undefined, Heap::kUndefinedValueRootIndex);
// Calculate capacity mask from the string table capacity.
Register mask = scratch2;
__ ldr(mask, FieldMemOperand(string_table, StringTable::kCapacityOffset));
__ mov(mask, Operand(mask, ASR, 1));
__ sub(mask, mask, Operand(1));
// Calculate untagged address of the first element of the string table.
Register first_string_table_element = string_table;
__ add(first_string_table_element, string_table,
Operand(StringTable::kElementsStartOffset - kHeapObjectTag));
// Registers
// chars: two character string, char 1 in byte 0 and char 2 in byte 1.
// hash: hash of two character string
// mask: capacity mask
// first_string_table_element: address of the first element of
// the string table
// undefined: the undefined object
// scratch: -
// Perform a number of probes in the string table.
const int kProbes = 4;
Label found_in_string_table;
Label next_probe[kProbes];
Register candidate = scratch5; // Scratch register contains candidate.
for (int i = 0; i < kProbes; i++) {
// Calculate entry in string table.
if (i > 0) {
__ add(candidate, hash, Operand(StringTable::GetProbeOffset(i)));
} else {
__ mov(candidate, hash);
}
__ and_(candidate, candidate, Operand(mask));
// Load the entry from the symble table.
STATIC_ASSERT(StringTable::kEntrySize == 1);
__ ldr(candidate,
MemOperand(first_string_table_element,
candidate,
LSL,
kPointerSizeLog2));
// If entry is undefined no string with this hash can be found.
Label is_string;
__ CompareObjectType(candidate, scratch, scratch, ODDBALL_TYPE);
__ b(ne, &is_string);
__ cmp(undefined, candidate);
__ b(eq, not_found);
// Must be the hole (deleted entry).
if (FLAG_debug_code) {
__ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
__ cmp(ip, candidate);
__ Assert(eq, kOddballInStringTableIsNotUndefinedOrTheHole);
}
__ jmp(&next_probe[i]);
__ bind(&is_string);
// Check that the candidate is a non-external ASCII string. The instance
// type is still in the scratch register from the CompareObjectType
// operation.
__ JumpIfInstanceTypeIsNotSequentialAscii(scratch, scratch, &next_probe[i]);
// If length is not 2 the string is not a candidate.
__ ldr(scratch, FieldMemOperand(candidate, String::kLengthOffset));
__ cmp(scratch, Operand(Smi::FromInt(2)));
__ b(ne, &next_probe[i]);
// Check if the two characters match.
// Assumes that word load is little endian.
__ ldrh(scratch, FieldMemOperand(candidate, SeqOneByteString::kHeaderSize));
__ cmp(chars, scratch);
__ b(eq, &found_in_string_table);
__ bind(&next_probe[i]);
}
// No matching 2 character string found by probing.
__ jmp(not_found);
// Scratch register contains result when we fall through to here.
Register result = candidate;
__ bind(&found_in_string_table);
__ Move(r0, result);
}
void StringHelper::GenerateHashInit(MacroAssembler* masm,
Register hash,
Register character) {
// hash = character + (character << 10);
__ LoadRoot(hash, Heap::kHashSeedRootIndex);
// Untag smi seed and add the character.
__ add(hash, character, Operand(hash, LSR, kSmiTagSize));
// hash += hash << 10;
__ add(hash, hash, Operand(hash, LSL, 10));
// hash ^= hash >> 6;
__ eor(hash, hash, Operand(hash, LSR, 6));
}
void StringHelper::GenerateHashAddCharacter(MacroAssembler* masm,
Register hash,
Register character) {
// hash += character;
__ add(hash, hash, Operand(character));
// hash += hash << 10;
__ add(hash, hash, Operand(hash, LSL, 10));
// hash ^= hash >> 6;
__ eor(hash, hash, Operand(hash, LSR, 6));
}
void StringHelper::GenerateHashGetHash(MacroAssembler* masm,
Register hash) {
// hash += hash << 3;
__ add(hash, hash, Operand(hash, LSL, 3));
// hash ^= hash >> 11;
__ eor(hash, hash, Operand(hash, LSR, 11));
// hash += hash << 15;
__ add(hash, hash, Operand(hash, LSL, 15));
__ and_(hash, hash, Operand(String::kHashBitMask), SetCC);
// if (hash == 0) hash = 27;
__ mov(hash, Operand(StringHasher::kZeroHash), LeaveCC, eq);
}
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;
__ Ldrd(r2, r3, MemOperand(sp, kToOffset));
STATIC_ASSERT(kFromOffset == kToOffset + 4);
STATIC_ASSERT(kSmiTag == 0);
STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
// Arithmetic shift right by one un-smi-tags. In this case we rotate right
// instead because we bail out on non-smi values: ROR and ASR are equivalent
// for smis but they set the flags in a way that's easier to optimize.
__ mov(r2, Operand(r2, ROR, 1), SetCC);
__ mov(r3, Operand(r3, ROR, 1), SetCC, cc);
// If either to or from had the smi tag bit set, then C is set now, and N
// has the same value: we rotated by 1, so the bottom bit is now the top bit.
// We want to bailout to runtime here if From is negative. In that case, the
// next instruction is not executed and we fall through to bailing out to
// runtime.
// Executed if both r2 and r3 are untagged integers.
__ sub(r2, r2, Operand(r3), SetCC, cc);
// One of the above un-smis or the above SUB could have set N==1.
__ b(mi, &runtime); // Either "from" or "to" is not an smi, or from > to.
// Make sure first argument is a string.
__ ldr(r0, MemOperand(sp, kStringOffset));
// Do a JumpIfSmi, but fold its jump into the subsequent string test.
__ SmiTst(r0);
Condition is_string = masm->IsObjectStringType(r0, r1, ne);
ASSERT(is_string == eq);
__ b(NegateCondition(is_string), &runtime);
Label single_char;
__ cmp(r2, Operand(1));
__ b(eq, &single_char);
// Short-cut for the case of trivial substring.
Label return_r0;
// r0: original string
// r2: result string length
__ ldr(r4, FieldMemOperand(r0, String::kLengthOffset));
__ cmp(r2, Operand(r4, ASR, 1));
// Return original string.
__ b(eq, &return_r0);
// Longer than original string's length or negative: unsafe arguments.
__ b(hi, &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 r5.
// r0: original string
// r1: instance type
// r2: length
// r3: 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);
__ tst(r1, Operand(kIsIndirectStringMask));
__ b(eq, &seq_or_external_string);
__ tst(r1, Operand(kSlicedNotConsMask));
__ b(ne, &sliced_string);
// Cons string. Check whether it is flat, then fetch first part.
__ ldr(r5, FieldMemOperand(r0, ConsString::kSecondOffset));
__ CompareRoot(r5, Heap::kempty_stringRootIndex);
__ b(ne, &runtime);
__ ldr(r5, FieldMemOperand(r0, ConsString::kFirstOffset));
// Update instance type.
__ ldr(r1, FieldMemOperand(r5, HeapObject::kMapOffset));
__ ldrb(r1, FieldMemOperand(r1, Map::kInstanceTypeOffset));
__ jmp(&underlying_unpacked);
__ bind(&sliced_string);
// Sliced string. Fetch parent and correct start index by offset.
__ ldr(r5, FieldMemOperand(r0, SlicedString::kParentOffset));
__ ldr(r4, FieldMemOperand(r0, SlicedString::kOffsetOffset));
__ add(r3, r3, Operand(r4, ASR, 1)); // Add offset to index.
// Update instance type.
__ ldr(r1, FieldMemOperand(r5, HeapObject::kMapOffset));
__ ldrb(r1, FieldMemOperand(r1, Map::kInstanceTypeOffset));
__ jmp(&underlying_unpacked);
__ bind(&seq_or_external_string);
// Sequential or external string. Just move string to the expected register.
__ mov(r5, r0);
__ bind(&underlying_unpacked);
if (FLAG_string_slices) {
Label copy_routine;
// r5: underlying subject string
// r1: instance type of underlying subject string
// r2: length
// r3: adjusted start index (untagged)
__ cmp(r2, Operand(SlicedString::kMinLength));
// Short slice. Copy instead of slicing.
__ b(lt, ©_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);
__ tst(r1, Operand(kStringEncodingMask));
__ b(eq, &two_byte_slice);
__ AllocateAsciiSlicedString(r0, r2, r6, r4, &runtime);
__ jmp(&set_slice_header);
__ bind(&two_byte_slice);
__ AllocateTwoByteSlicedString(r0, r2, r6, r4, &runtime);
__ bind(&set_slice_header);
__ mov(r3, Operand(r3, LSL, 1));
__ str(r5, FieldMemOperand(r0, SlicedString::kParentOffset));
__ str(r3, FieldMemOperand(r0, SlicedString::kOffsetOffset));
__ jmp(&return_r0);
__ bind(©_routine);
}
// r5: underlying subject string
// r1: instance type of underlying subject string
// r2: length
// r3: adjusted start index (untagged)
Label two_byte_sequential, sequential_string, allocate_result;
STATIC_ASSERT(kExternalStringTag != 0);
STATIC_ASSERT(kSeqStringTag == 0);
__ tst(r1, Operand(kExternalStringTag));
__ b(eq, &sequential_string);
// Handle external string.
// Rule out short external strings.
STATIC_CHECK(kShortExternalStringTag != 0);
__ tst(r1, Operand(kShortExternalStringTag));
__ b(ne, &runtime);
__ ldr(r5, FieldMemOperand(r5, ExternalString::kResourceDataOffset));
// r5 already points to the first character of underlying string.
__ jmp(&allocate_result);
__ bind(&sequential_string);
// Locate first character of underlying subject string.
STATIC_ASSERT(SeqTwoByteString::kHeaderSize == SeqOneByteString::kHeaderSize);
__ add(r5, r5, Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
__ bind(&allocate_result);
// Sequential acii string. Allocate the result.
STATIC_ASSERT((kOneByteStringTag & kStringEncodingMask) != 0);
__ tst(r1, Operand(kStringEncodingMask));
__ b(eq, &two_byte_sequential);
// Allocate and copy the resulting ASCII string.
__ AllocateAsciiString(r0, r2, r4, r6, r1, &runtime);
// Locate first character of substring to copy.
__ add(r5, r5, r3);
// Locate first character of result.
__ add(r1, r0, Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
// r0: result string
// r1: first character of result string
// r2: result string length
// r5: first character of substring to copy
STATIC_ASSERT((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
StringHelper::GenerateCopyCharactersLong(masm, r1, r5, r2, r3, r4, r6, r9,
COPY_ASCII | DEST_ALWAYS_ALIGNED);
__ jmp(&return_r0);
// Allocate and copy the resulting two-byte string.
__ bind(&two_byte_sequential);
__ AllocateTwoByteString(r0, r2, r4, r6, r1, &runtime);
// Locate first character of substring to copy.
STATIC_ASSERT(kSmiTagSize == 1 && kSmiTag == 0);
__ add(r5, r5, Operand(r3, LSL, 1));
// Locate first character of result.
__ add(r1, r0, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
// r0: result string.
// r1: first character of result.
// r2: result length.
// r5: first character of substring to copy.
STATIC_ASSERT((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
StringHelper::GenerateCopyCharactersLong(
masm, r1, r5, r2, r3, r4, r6, r9, DEST_ALWAYS_ALIGNED);
__ bind(&return_r0);
Counters* counters = masm->isolate()->counters();
__ IncrementCounter(counters->sub_string_native(), 1, r3, r4);
__ Drop(3);
__ Ret();
// Just jump to runtime to create the sub string.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kSubString, 3, 1);
__ bind(&single_char);
// r0: original string
// r1: instance type
// r2: length
// r3: from index (untagged)
__ SmiTag(r3, r3);
StringCharAtGenerator generator(
r0, r3, r2, r0, &runtime, &runtime, &runtime, STRING_INDEX_IS_NUMBER);
generator.GenerateFast(masm);
__ Drop(3);
__ Ret();
generator.SkipSlow(masm, &runtime);
}
void StringCompareStub::GenerateFlatAsciiStringEquals(MacroAssembler* masm,
Register left,
Register right,
Register scratch1,
Register scratch2,
Register scratch3) {
Register length = scratch1;
// Compare lengths.
Label strings_not_equal, check_zero_length;
__ ldr(length, FieldMemOperand(left, String::kLengthOffset));
__ ldr(scratch2, FieldMemOperand(right, String::kLengthOffset));
__ cmp(length, scratch2);
__ b(eq, &check_zero_length);
__ bind(&strings_not_equal);
__ mov(r0, Operand(Smi::FromInt(NOT_EQUAL)));
__ Ret();
// Check if the length is zero.
Label compare_chars;
__ bind(&check_zero_length);
STATIC_ASSERT(kSmiTag == 0);
__ cmp(length, Operand::Zero());
__ b(ne, &compare_chars);
__ mov(r0, Operand(Smi::FromInt(EQUAL)));
__ Ret();
// Compare characters.
__ bind(&compare_chars);
GenerateAsciiCharsCompareLoop(masm,
left, right, length, scratch2, scratch3,
&strings_not_equal);
// Characters are equal.
__ mov(r0, Operand(Smi::FromInt(EQUAL)));
__ Ret();
}
void StringCompareStub::GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
Register left,
Register right,
Register scratch1,
Register scratch2,
Register scratch3,
Register scratch4) {
Label result_not_equal, compare_lengths;
// Find minimum length and length difference.
__ ldr(scratch1, FieldMemOperand(left, String::kLengthOffset));
__ ldr(scratch2, FieldMemOperand(right, String::kLengthOffset));
__ sub(scratch3, scratch1, Operand(scratch2), SetCC);
Register length_delta = scratch3;
__ mov(scratch1, scratch2, LeaveCC, gt);
Register min_length = scratch1;
STATIC_ASSERT(kSmiTag == 0);
__ cmp(min_length, Operand::Zero());
__ b(eq, &compare_lengths);
// Compare loop.
GenerateAsciiCharsCompareLoop(masm,
left, right, min_length, scratch2, scratch4,
&result_not_equal);
// Compare lengths - strings up to min-length are equal.
__ bind(&compare_lengths);
ASSERT(Smi::FromInt(EQUAL) == static_cast<Smi*>(0));
// Use length_delta as result if it's zero.
__ mov(r0, Operand(length_delta), SetCC);
__ bind(&result_not_equal);
// Conditionally update the result based either on length_delta or
// the last comparion performed in the loop above.
__ mov(r0, Operand(Smi::FromInt(GREATER)), LeaveCC, gt);
__ mov(r0, Operand(Smi::FromInt(LESS)), LeaveCC, lt);
__ Ret();
}
void StringCompareStub::GenerateAsciiCharsCompareLoop(
MacroAssembler* masm,
Register left,
Register right,
Register length,
Register scratch1,
Register scratch2,
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);
__ add(scratch1, length,
Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
__ add(left, left, Operand(scratch1));
__ add(right, right, Operand(scratch1));
__ rsb(length, length, Operand::Zero());
Register index = length; // index = -length;
// Compare loop.
Label loop;
__ bind(&loop);
__ ldrb(scratch1, MemOperand(left, index));
__ ldrb(scratch2, MemOperand(right, index));
__ cmp(scratch1, scratch2);
__ b(ne, chars_not_equal);
__ add(index, index, Operand(1), SetCC);
__ b(ne, &loop);
}
void StringCompareStub::Generate(MacroAssembler* masm) {
Label runtime;
Counters* counters = masm->isolate()->counters();
// Stack frame on entry.
// sp[0]: right string
// sp[4]: left string
__ Ldrd(r0 , r1, MemOperand(sp)); // Load right in r0, left in r1.
Label not_same;
__ cmp(r0, r1);
__ b(ne, ¬_same);
STATIC_ASSERT(EQUAL == 0);
STATIC_ASSERT(kSmiTag == 0);
__ mov(r0, Operand(Smi::FromInt(EQUAL)));
__ IncrementCounter(counters->string_compare_native(), 1, r1, r2);
__ add(sp, sp, Operand(2 * kPointerSize));
__ Ret();
__ bind(¬_same);
// Check that both objects are sequential ASCII strings.
__ JumpIfNotBothSequentialAsciiStrings(r1, r0, r2, r3, &runtime);
// Compare flat ASCII strings natively. Remove arguments from stack first.
__ IncrementCounter(counters->string_compare_native(), 1, r2, r3);
__ add(sp, sp, Operand(2 * kPointerSize));
GenerateCompareFlatAsciiStrings(masm, r1, r0, r2, r3, r4, r5);
// Call the runtime; it returns -1 (less), 0 (equal), or 1 (greater)
// tagged as a small integer.
__ bind(&runtime);
__ TailCallRuntime(Runtime::kStringCompare, 2, 1);
}
void StringAddStub::Generate(MacroAssembler* masm) {
Label call_runtime, call_builtin;
Builtins::JavaScript builtin_id = Builtins::ADD;
Counters* counters = masm->isolate()->counters();
// Stack on entry:
// sp[0]: second argument (right).
// sp[4]: first argument (left).
// Load the two arguments.
__ ldr(r0, MemOperand(sp, 1 * kPointerSize)); // First argument.
__ ldr(r1, MemOperand(sp, 0 * kPointerSize)); // Second argument.
// Make sure that both arguments are strings if not known in advance.
// Otherwise, at least one of the arguments is definitely a string,
// and we convert the one that is not known to be a string.
if ((flags_ & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_BOTH) {
ASSERT((flags_ & STRING_ADD_CHECK_LEFT) == STRING_ADD_CHECK_LEFT);
ASSERT((flags_ & STRING_ADD_CHECK_RIGHT) == STRING_ADD_CHECK_RIGHT);
__ JumpIfEitherSmi(r0, r1, &call_runtime);
// Load instance types.
__ ldr(r4, FieldMemOperand(r0, HeapObject::kMapOffset));
__ ldr(r5, FieldMemOperand(r1, HeapObject::kMapOffset));
__ ldrb(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
__ ldrb(r5, FieldMemOperand(r5, Map::kInstanceTypeOffset));
STATIC_ASSERT(kStringTag == 0);
// If either is not a string, go to runtime.
__ tst(r4, Operand(kIsNotStringMask));
__ tst(r5, Operand(kIsNotStringMask), eq);
__ b(ne, &call_runtime);
} else if ((flags_ & STRING_ADD_CHECK_LEFT) == STRING_ADD_CHECK_LEFT) {
ASSERT((flags_ & STRING_ADD_CHECK_RIGHT) == 0);
GenerateConvertArgument(
masm, 1 * kPointerSize, r0, r2, r3, r4, r5, &call_builtin);
builtin_id = Builtins::STRING_ADD_RIGHT;
} else if ((flags_ & STRING_ADD_CHECK_RIGHT) == STRING_ADD_CHECK_RIGHT) {
ASSERT((flags_ & STRING_ADD_CHECK_LEFT) == 0);
GenerateConvertArgument(
masm, 0 * kPointerSize, r1, r2, r3, r4, r5, &call_builtin);
builtin_id = Builtins::STRING_ADD_LEFT;
}
// Both arguments are strings.
// r0: first string
// r1: second string
// r4: first string instance type (if flags_ == NO_STRING_ADD_FLAGS)
// r5: second string instance type (if flags_ == NO_STRING_ADD_FLAGS)
{
Label strings_not_empty;
// Check if either of the strings are empty. In that case return the other.
__ ldr(r2, FieldMemOperand(r0, String::kLengthOffset));
__ ldr(r3, FieldMemOperand(r1, String::kLengthOffset));
STATIC_ASSERT(kSmiTag == 0);
__ cmp(r2, Operand(Smi::FromInt(0))); // Test if first string is empty.
__ mov(r0, Operand(r1), LeaveCC, eq); // If first is empty, return second.
STATIC_ASSERT(kSmiTag == 0);
// Else test if second string is empty.
__ cmp(r3, Operand(Smi::FromInt(0)), ne);
__ b(ne, &strings_not_empty); // If either string was empty, return r0.
__ IncrementCounter(counters->string_add_native(), 1, r2, r3);
__ add(sp, sp, Operand(2 * kPointerSize));
__ Ret();
__ bind(&strings_not_empty);
}
__ SmiUntag(r2);
__ SmiUntag(r3);
// Both strings are non-empty.
// r0: first string
// r1: second string
// r2: length of first string
// r3: length of second string
// r4: first string instance type (if flags_ == NO_STRING_ADD_FLAGS)
// r5: second string instance type (if flags_ == NO_STRING_ADD_FLAGS)
// Look at the length of the result of adding the two strings.
Label string_add_flat_result, longer_than_two;
// Adding two lengths can't overflow.
STATIC_ASSERT(String::kMaxLength < String::kMaxLength * 2);
__ add(r6, r2, Operand(r3));
// Use the string table when adding two one character strings, as it
// helps later optimizations to return a string here.
__ cmp(r6, Operand(2));
__ b(ne, &longer_than_two);
// Check that both strings are non-external ASCII strings.
if ((flags_ & STRING_ADD_CHECK_BOTH) != STRING_ADD_CHECK_BOTH) {
__ ldr(r4, FieldMemOperand(r0, HeapObject::kMapOffset));
__ ldr(r5, FieldMemOperand(r1, HeapObject::kMapOffset));
__ ldrb(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
__ ldrb(r5, FieldMemOperand(r5, Map::kInstanceTypeOffset));
}
__ JumpIfBothInstanceTypesAreNotSequentialAscii(r4, r5, r6, r3,
&call_runtime);
// Get the two characters forming the sub string.
__ ldrb(r2, FieldMemOperand(r0, SeqOneByteString::kHeaderSize));
__ ldrb(r3, FieldMemOperand(r1, SeqOneByteString::kHeaderSize));
// Try to lookup two character string in string table. If it is not found
// just allocate a new one.
Label make_two_character_string;
StringHelper::GenerateTwoCharacterStringTableProbe(
masm, r2, r3, r6, r0, r4, r5, r9, &make_two_character_string);
__ IncrementCounter(counters->string_add_native(), 1, r2, r3);
__ add(sp, sp, Operand(2 * kPointerSize));
__ Ret();
__ bind(&make_two_character_string);
// Resulting string has length 2 and first chars of two strings
// are combined into single halfword in r2 register.
// So we can fill resulting string without two loops by a single
// halfword store instruction (which assumes that processor is
// in a little endian mode)
__ mov(r6, Operand(2));
__ AllocateAsciiString(r0, r6, r4, r5, r9, &call_runtime);
__ strh(r2, FieldMemOperand(r0, SeqOneByteString::kHeaderSize));
__ IncrementCounter(counters->string_add_native(), 1, r2, r3);
__ add(sp, sp, Operand(2 * kPointerSize));
__ Ret();
__ bind(&longer_than_two);
// Check if resulting string will be flat.
__ cmp(r6, Operand(ConsString::kMinLength));
__ b(lt, &string_add_flat_result);
// Handle exceptionally long strings in the runtime system.
STATIC_ASSERT((String::kMaxLength & 0x80000000) == 0);
ASSERT(IsPowerOf2(String::kMaxLength + 1));
// kMaxLength + 1 is representable as shifted literal, kMaxLength is not.
__ cmp(r6, Operand(String::kMaxLength + 1));
__ b(hs, &call_runtime);
// If result is not supposed to be flat, allocate a cons string object.
// If both strings are ASCII the result is an ASCII cons string.
if ((flags_ & STRING_ADD_CHECK_BOTH) != STRING_ADD_CHECK_BOTH) {
__ ldr(r4, FieldMemOperand(r0, HeapObject::kMapOffset));
__ ldr(r5, FieldMemOperand(r1, HeapObject::kMapOffset));
__ ldrb(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
__ ldrb(r5, FieldMemOperand(r5, Map::kInstanceTypeOffset));
}
Label non_ascii, allocated, ascii_data;
STATIC_ASSERT(kTwoByteStringTag == 0);
__ tst(r4, Operand(kStringEncodingMask));
__ tst(r5, Operand(kStringEncodingMask), ne);
__ b(eq, &non_ascii);
// Allocate an ASCII cons string.
__ bind(&ascii_data);
__ AllocateAsciiConsString(r3, r6, r4, r5, &call_runtime);
__ bind(&allocated);
// Fill the fields of the cons string.
Label skip_write_barrier, after_writing;
ExternalReference high_promotion_mode = ExternalReference::
new_space_high_promotion_mode_active_address(masm->isolate());
__ mov(r4, Operand(high_promotion_mode));
__ ldr(r4, MemOperand(r4, 0));
__ cmp(r4, Operand::Zero());
__ b(eq, &skip_write_barrier);
__ str(r0, FieldMemOperand(r3, ConsString::kFirstOffset));
__ RecordWriteField(r3,
ConsString::kFirstOffset,
r0,
r4,
kLRHasNotBeenSaved,
kDontSaveFPRegs);
__ str(r1, FieldMemOperand(r3, ConsString::kSecondOffset));
__ RecordWriteField(r3,
ConsString::kSecondOffset,
r1,
r4,
kLRHasNotBeenSaved,
kDontSaveFPRegs);
__ jmp(&after_writing);
__ bind(&skip_write_barrier);
__ str(r0, FieldMemOperand(r3, ConsString::kFirstOffset));
__ str(r1, FieldMemOperand(r3, ConsString::kSecondOffset));
__ bind(&after_writing);
__ mov(r0, Operand(r3));
__ IncrementCounter(counters->string_add_native(), 1, r2, r3);
__ add(sp, sp, Operand(2 * kPointerSize));
__ Ret();
__ bind(&non_ascii);
// At least one of the strings is two-byte. Check whether it happens
// to contain only one byte characters.
// r4: first instance type.
// r5: second instance type.
__ tst(r4, Operand(kOneByteDataHintMask));
__ tst(r5, Operand(kOneByteDataHintMask), ne);
__ b(ne, &ascii_data);
__ eor(r4, r4, Operand(r5));
STATIC_ASSERT(kOneByteStringTag != 0 && kOneByteDataHintTag != 0);
__ and_(r4, r4, Operand(kOneByteStringTag | kOneByteDataHintTag));
__ cmp(r4, Operand(kOneByteStringTag | kOneByteDataHintTag));
__ b(eq, &ascii_data);
// Allocate a two byte cons string.
__ AllocateTwoByteConsString(r3, r6, r4, r5, &call_runtime);
__ jmp(&allocated);
// We cannot encounter sliced strings or cons strings here since:
STATIC_ASSERT(SlicedString::kMinLength >= ConsString::kMinLength);
// Handle creating a flat result from either external or sequential strings.
// Locate the first characters' locations.
// r0: first string
// r1: second string
// r2: length of first string
// r3: length of second string
// r4: first string instance type (if flags_ == NO_STRING_ADD_FLAGS)
// r5: second string instance type (if flags_ == NO_STRING_ADD_FLAGS)
// r6: sum of lengths.
Label first_prepared, second_prepared;
__ bind(&string_add_flat_result);
if ((flags_ & STRING_ADD_CHECK_BOTH) != STRING_ADD_CHECK_BOTH) {
__ ldr(r4, FieldMemOperand(r0, HeapObject::kMapOffset));
__ ldr(r5, FieldMemOperand(r1, HeapObject::kMapOffset));
__ ldrb(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
__ ldrb(r5, FieldMemOperand(r5, Map::kInstanceTypeOffset));
}
// Check whether both strings have same encoding
__ eor(ip, r4, Operand(r5));
ASSERT(__ ImmediateFitsAddrMode1Instruction(kStringEncodingMask));
__ tst(ip, Operand(kStringEncodingMask));
__ b(ne, &call_runtime);
STATIC_ASSERT(kSeqStringTag == 0);
__ tst(r4, Operand(kStringRepresentationMask));
STATIC_ASSERT(SeqOneByteString::kHeaderSize == SeqTwoByteString::kHeaderSize);
__ add(r6,
r0,
Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag),
LeaveCC,
eq);
__ b(eq, &first_prepared);
// External string: rule out short external string and load string resource.
STATIC_ASSERT(kShortExternalStringTag != 0);
__ tst(r4, Operand(kShortExternalStringMask));
__ b(ne, &call_runtime);
__ ldr(r6, FieldMemOperand(r0, ExternalString::kResourceDataOffset));
__ bind(&first_prepared);
STATIC_ASSERT(kSeqStringTag == 0);
__ tst(r5, Operand(kStringRepresentationMask));
STATIC_ASSERT(SeqOneByteString::kHeaderSize == SeqTwoByteString::kHeaderSize);
__ add(r1,
r1,
Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag),
LeaveCC,
eq);
__ b(eq, &second_prepared);
// External string: rule out short external string and load string resource.
STATIC_ASSERT(kShortExternalStringTag != 0);
__ tst(r5, Operand(kShortExternalStringMask));
__ b(ne, &call_runtime);
__ ldr(r1, FieldMemOperand(r1, ExternalString::kResourceDataOffset));
__ bind(&second_prepared);
Label non_ascii_string_add_flat_result;
// r6: first character of first string
// r1: first character of second string
// r2: length of first string.
// r3: length of second string.
// Both strings have the same encoding.
STATIC_ASSERT(kTwoByteStringTag == 0);
__ tst(r5, Operand(kStringEncodingMask));
__ b(eq, &non_ascii_string_add_flat_result);
__ add(r2, r2, Operand(r3));
__ AllocateAsciiString(r0, r2, r4, r5, r9, &call_runtime);
__ sub(r2, r2, Operand(r3));
__ add(r5, r0, Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
// r0: result string.
// r6: first character of first string.
// r1: first character of second string.
// r2: length of first string.
// r3: length of second string.
// r5: first character of result.
StringHelper::GenerateCopyCharacters(masm, r5, r6, r2, r4, true);
// r5: next character of result.
StringHelper::GenerateCopyCharacters(masm, r5, r1, r3, r4, true);
__ IncrementCounter(counters->string_add_native(), 1, r2, r3);
__ add(sp, sp, Operand(2 * kPointerSize));
__ Ret();
__ bind(&non_ascii_string_add_flat_result);
__ add(r2, r2, Operand(r3));
__ AllocateTwoByteString(r0, r2, r4, r5, r9, &call_runtime);
__ sub(r2, r2, Operand(r3));
__ add(r5, r0, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
// r0: result string.
// r6: first character of first string.
// r1: first character of second string.
// r2: length of first string.
// r3: length of second string.
// r5: first character of result.
StringHelper::GenerateCopyCharacters(masm, r5, r6, r2, r4, false);
// r5: next character of result.
StringHelper::GenerateCopyCharacters(masm, r5, r1, r3, r4, false);
__ IncrementCounter(counters->string_add_native(), 1, r2, r3);
__ add(sp, sp, Operand(2 * kPointerSize));
__ Ret();
// Just jump to runtime to add the two strings.
__ bind(&call_runtime);
__ TailCallRuntime(Runtime::kStringAdd, 2, 1);
if (call_builtin.is_linked()) {
__ bind(&call_builtin);
__ InvokeBuiltin(builtin_id, JUMP_FUNCTION);
}
}
void StringAddStub::GenerateRegisterArgsPush(MacroAssembler* masm) {
__ push(r0);
__ push(r1);
}
void StringAddStub::GenerateRegisterArgsPop(MacroAssembler* masm) {
__ pop(r1);
__ pop(r0);
}
void StringAddStub::GenerateConvertArgument(MacroAssembler* masm,
int stack_offset,
Register arg,
Register scratch1,
Register scratch2,
Register scratch3,
Register scratch4,
Label* slow) {
// First check if the argument is already a string.
Label not_string, done;
__ JumpIfSmi(arg, ¬_string);
__ CompareObjectType(arg, scratch1, scratch1, FIRST_NONSTRING_TYPE);
__ b(lt, &done);
// Check the number to string cache.
__ bind(¬_string);
// Puts the cached result into scratch1.
__ LookupNumberStringCache(arg, scratch1, scratch2, scratch3, scratch4, slow);
__ mov(arg, scratch1);
__ str(arg, MemOperand(sp, stack_offset));
__ bind(&done);
}
void ICCompareStub::GenerateSmis(MacroAssembler* masm) {
ASSERT(state_ == CompareIC::SMI);
Label miss;
__ orr(r2, r1, r0);
__ JumpIfNotSmi(r2, &miss);
if (GetCondition() == eq) {
// For equality we do not care about the sign of the result.
__ sub(r0, r0, r1, SetCC);
} else {
// Untag before subtracting to avoid handling overflow.
__ SmiUntag(r1);
__ sub(r0, r1, Operand::SmiUntag(r0));
}
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void ICCompareStub::GenerateNumbers(MacroAssembler* masm) {
ASSERT(state_ == CompareIC::NUMBER);
Label generic_stub;
Label unordered, maybe_undefined1, maybe_undefined2;
Label miss;
if (left_ == CompareIC::SMI) {
__ JumpIfNotSmi(r1, &miss);
}
if (right_ == CompareIC::SMI) {
__ JumpIfNotSmi(r0, &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(r0, &right_smi);
__ CheckMap(r0, r2, Heap::kHeapNumberMapRootIndex, &maybe_undefined1,
DONT_DO_SMI_CHECK);
__ sub(r2, r0, Operand(kHeapObjectTag));
__ vldr(d1, r2, HeapNumber::kValueOffset);
__ b(&left);
__ bind(&right_smi);
__ SmiToDouble(d1, r0);
__ bind(&left);
__ JumpIfSmi(r1, &left_smi);
__ CheckMap(r1, r2, Heap::kHeapNumberMapRootIndex, &maybe_undefined2,
DONT_DO_SMI_CHECK);
__ sub(r2, r1, Operand(kHeapObjectTag));
__ vldr(d0, r2, HeapNumber::kValueOffset);
__ b(&done);
__ bind(&left_smi);
__ SmiToDouble(d0, r1);
__ bind(&done);
// Compare operands.
__ VFPCompareAndSetFlags(d0, d1);
// Don't base result on status bits when a NaN is involved.
__ b(vs, &unordered);
// Return a result of -1, 0, or 1, based on status bits.
__ mov(r0, Operand(EQUAL), LeaveCC, eq);
__ mov(r0, Operand(LESS), LeaveCC, lt);
__ mov(r0, Operand(GREATER), LeaveCC, gt);
__ Ret();
__ bind(&unordered);
__ bind(&generic_stub);
ICCompareStub stub(op_, CompareIC::GENERIC, CompareIC::GENERIC,
CompareIC::GENERIC);
__ Jump(stub.GetCode(masm->isolate()), RelocInfo::CODE_TARGET);
__ bind(&maybe_undefined1);
if (Token::IsOrderedRelationalCompareOp(op_)) {
__ CompareRoot(r0, Heap::kUndefinedValueRootIndex);
__ b(ne, &miss);
__ JumpIfSmi(r1, &unordered);
__ CompareObjectType(r1, r2, r2, HEAP_NUMBER_TYPE);
__ b(ne, &maybe_undefined2);
__ jmp(&unordered);
}
__ bind(&maybe_undefined2);
if (Token::IsOrderedRelationalCompareOp(op_)) {
__ CompareRoot(r1, Heap::kUndefinedValueRootIndex);
__ b(eq, &unordered);
}
__ bind(&miss);
GenerateMiss(masm);
}
void ICCompareStub::GenerateInternalizedStrings(MacroAssembler* masm) {
ASSERT(state_ == CompareIC::INTERNALIZED_STRING);
Label miss;
// Registers containing left and right operands respectively.
Register left = r1;
Register right = r0;
Register tmp1 = r2;
Register tmp2 = r3;
// Check that both operands are heap objects.
__ JumpIfEitherSmi(left, right, &miss);
// Check that both operands are internalized strings.
__ ldr(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
__ ldr(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
__ ldrb(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
__ ldrb(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
__ orr(tmp1, tmp1, Operand(tmp2));
__ tst(tmp1, Operand(kIsNotStringMask | kIsNotInternalizedMask));
__ b(ne, &miss);
// Internalized strings are compared by identity.
__ cmp(left, right);
// Make sure r0 is non-zero. At this point input operands are
// guaranteed to be non-zero.
ASSERT(right.is(r0));
STATIC_ASSERT(EQUAL == 0);
STATIC_ASSERT(kSmiTag == 0);
__ mov(r0, Operand(Smi::FromInt(EQUAL)), LeaveCC, eq);
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void ICCompareStub::GenerateUniqueNames(MacroAssembler* masm) {
ASSERT(state_ == CompareIC::UNIQUE_NAME);
ASSERT(GetCondition() == eq);
Label miss;
// Registers containing left and right operands respectively.
Register left = r1;
Register right = r0;
Register tmp1 = r2;
Register tmp2 = r3;
// 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.
__ ldr(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
__ ldr(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
__ ldrb(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
__ ldrb(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
__ JumpIfNotUniqueName(tmp1, &miss);
__ JumpIfNotUniqueName(tmp2, &miss);
// Unique names are compared by identity.
__ cmp(left, right);
// Make sure r0 is non-zero. At this point input operands are
// guaranteed to be non-zero.
ASSERT(right.is(r0));
STATIC_ASSERT(EQUAL == 0);
STATIC_ASSERT(kSmiTag == 0);
__ mov(r0, Operand(Smi::FromInt(EQUAL)), LeaveCC, eq);
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void ICCompareStub::GenerateStrings(MacroAssembler* masm) {
ASSERT(state_ == CompareIC::STRING);
Label miss;
bool equality = Token::IsEqualityOp(op_);
// Registers containing left and right operands respectively.
Register left = r1;
Register right = r0;
Register tmp1 = r2;
Register tmp2 = r3;
Register tmp3 = r4;
Register tmp4 = r5;
// 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.
__ ldr(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
__ ldr(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
__ ldrb(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
__ ldrb(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
STATIC_ASSERT(kNotStringTag != 0);
__ orr(tmp3, tmp1, tmp2);
__ tst(tmp3, Operand(kIsNotStringMask));
__ b(ne, &miss);
// Fast check for identical strings.
__ cmp(left, right);
STATIC_ASSERT(EQUAL == 0);
STATIC_ASSERT(kSmiTag == 0);
__ mov(r0, Operand(Smi::FromInt(EQUAL)), LeaveCC, eq);
__ Ret(eq);
// 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) {
ASSERT(GetCondition() == eq);
STATIC_ASSERT(kInternalizedTag == 0);
__ orr(tmp3, tmp1, Operand(tmp2));
__ tst(tmp3, Operand(kIsNotInternalizedMask));
// Make sure r0 is non-zero. At this point input operands are
// guaranteed to be non-zero.
ASSERT(right.is(r0));
__ Ret(eq);
}
// Check that both strings are sequential ASCII.
Label runtime;
__ JumpIfBothInstanceTypesAreNotSequentialAscii(
tmp1, tmp2, tmp3, tmp4, &runtime);
// Compare flat ASCII strings. Returns when done.
if (equality) {
StringCompareStub::GenerateFlatAsciiStringEquals(
masm, left, right, tmp1, tmp2, tmp3);
} else {
StringCompareStub::GenerateCompareFlatAsciiStrings(
masm, left, right, tmp1, tmp2, tmp3, tmp4);
}
// Handle more complex cases in runtime.
__ bind(&runtime);
__ Push(left, right);
if (equality) {
__ TailCallRuntime(Runtime::kStringEquals, 2, 1);
} else {
__ TailCallRuntime(Runtime::kStringCompare, 2, 1);
}
__ bind(&miss);
GenerateMiss(masm);
}
void ICCompareStub::GenerateObjects(MacroAssembler* masm) {
ASSERT(state_ == CompareIC::OBJECT);
Label miss;
__ and_(r2, r1, Operand(r0));
__ JumpIfSmi(r2, &miss);
__ CompareObjectType(r0, r2, r2, JS_OBJECT_TYPE);
__ b(ne, &miss);
__ CompareObjectType(r1, r2, r2, JS_OBJECT_TYPE);
__ b(ne, &miss);
ASSERT(GetCondition() == eq);
__ sub(r0, r0, Operand(r1));
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void ICCompareStub::GenerateKnownObjects(MacroAssembler* masm) {
Label miss;
__ and_(r2, r1, Operand(r0));
__ JumpIfSmi(r2, &miss);
__ ldr(r2, FieldMemOperand(r0, HeapObject::kMapOffset));
__ ldr(r3, FieldMemOperand(r1, HeapObject::kMapOffset));
__ cmp(r2, Operand(known_map_));
__ b(ne, &miss);
__ cmp(r3, Operand(known_map_));
__ b(ne, &miss);
__ sub(r0, r0, Operand(r1));
__ Ret();
__ bind(&miss);
GenerateMiss(masm);
}
void ICCompareStub::GenerateMiss(MacroAssembler* masm) {
{
// Call the runtime system in a fresh internal frame.
ExternalReference miss =
ExternalReference(IC_Utility(IC::kCompareIC_Miss), masm->isolate());
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(r1, r0);
__ Push(lr, r1, r0);
__ mov(ip, Operand(Smi::FromInt(op_)));
__ push(ip);
__ CallExternalReference(miss, 3);
// Compute the entry point of the rewritten stub.
__ add(r2, r0, Operand(Code::kHeaderSize - kHeapObjectTag));
// Restore registers.
__ pop(lr);
__ Pop(r1, r0);
}
__ Jump(r2);
}
void DirectCEntryStub::Generate(MacroAssembler* masm) {
// Place the return address on the stack, making the call
// GC safe. The RegExp backend also relies on this.
__ str(lr, MemOperand(sp, 0));
__ blx(ip); // Call the C++ function.
__ VFPEnsureFPSCRState(r2);
__ ldr(pc, MemOperand(sp, 0));
}
void DirectCEntryStub::GenerateCall(MacroAssembler* masm,
Register target) {
intptr_t code =
reinterpret_cast<intptr_t>(GetCode(masm->isolate()).location());
__ Move(ip, target);
__ mov(lr, Operand(code, RelocInfo::CODE_TARGET));
__ blx(lr); // Call the stub.
}
void NameDictionaryLookupStub::GenerateNegativeLookup(MacroAssembler* masm,
Label* miss,
Label* done,
Register receiver,
Register properties,
Handle<Name> name,
Register scratch0) {
ASSERT(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.
__ ldr(index, FieldMemOperand(properties, kCapacityOffset));
__ sub(index, index, Operand(1));
__ and_(index, index, Operand(
Smi::FromInt(name->Hash() + NameDictionary::GetProbeOffset(i))));
// Scale the index by multiplying by the entry size.
ASSERT(NameDictionary::kEntrySize == 3);
__ add(index, index, Operand(index, LSL, 1)); // index *= 3.
Register entity_name = scratch0;
// Having undefined at this place means the name is not contained.
ASSERT_EQ(kSmiTagSize, 1);
Register tmp = properties;
__ add(tmp, properties, Operand(index, LSL, 1));
__ ldr(entity_name, FieldMemOperand(tmp, kElementsStartOffset));
ASSERT(!tmp.is(entity_name));
__ LoadRoot(tmp, Heap::kUndefinedValueRootIndex);
__ cmp(entity_name, tmp);
__ b(eq, done);
// Load the hole ready for use below:
__ LoadRoot(tmp, Heap::kTheHoleValueRootIndex);
// Stop if found the property.
__ cmp(entity_name, Operand(Handle<Name>(name)));
__ b(eq, miss);
Label good;
__ cmp(entity_name, tmp);
__ b(eq, &good);
// Check if the entry name is not a unique name.
__ ldr(entity_name, FieldMemOperand(entity_name, HeapObject::kMapOffset));
__ ldrb(entity_name,
FieldMemOperand(entity_name, Map::kInstanceTypeOffset));
__ JumpIfNotUniqueName(entity_name, miss);
__ bind(&good);
// Restore the properties.
__ ldr(properties,
FieldMemOperand(receiver, JSObject::kPropertiesOffset));
}
const int spill_mask =
(lr.bit() | r6.bit() | r5.bit() | r4.bit() | r3.bit() |
r2.bit() | r1.bit() | r0.bit());
__ stm(db_w, sp, spill_mask);
__ ldr(r0, FieldMemOperand(receiver, JSObject::kPropertiesOffset));
__ mov(r1, Operand(Handle<Name>(name)));
NameDictionaryLookupStub stub(NEGATIVE_LOOKUP);
__ CallStub(&stub);
__ cmp(r0, Operand::Zero());
__ ldm(ia_w, sp, spill_mask);
__ b(eq, done);
__ b(ne, 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) {
ASSERT(!elements.is(scratch1));
ASSERT(!elements.is(scratch2));
ASSERT(!name.is(scratch1));
ASSERT(!name.is(scratch2));
__ AssertName(name);
// Compute the capacity mask.
__ ldr(scratch1, FieldMemOperand(elements, kCapacityOffset));
__ SmiUntag(scratch1);
__ sub(scratch1, 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.
__ ldr(scratch2, FieldMemOperand(name, Name::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.
ASSERT(NameDictionary::GetProbeOffset(i) <
1 << (32 - Name::kHashFieldOffset));
__ add(scratch2, scratch2, Operand(
NameDictionary::GetProbeOffset(i) << Name::kHashShift));
}
__ and_(scratch2, scratch1, Operand(scratch2, LSR, Name::kHashShift));
// Scale the index by multiplying by the element size.
ASSERT(NameDictionary::kEntrySize == 3);
// scratch2 = scratch2 * 3.
__ add(scratch2, scratch2, Operand(scratch2, LSL, 1));
// Check if the key is identical to the name.
__ add(scratch2, elements, Operand(scratch2, LSL, 2));
__ ldr(ip, FieldMemOperand(scratch2, kElementsStartOffset));
__ cmp(name, Operand(ip));
__ b(eq, done);
}
const int spill_mask =
(lr.bit() | r6.bit() | r5.bit() | r4.bit() |
r3.bit() | r2.bit() | r1.bit() | r0.bit()) &
~(scratch1.bit() | scratch2.bit());
__ stm(db_w, sp, spill_mask);
if (name.is(r0)) {
ASSERT(!elements.is(r1));
__ Move(r1, name);
__ Move(r0, elements);
} else {
__ Move(r0, elements);
__ Move(r1, name);
}
NameDictionaryLookupStub stub(POSITIVE_LOOKUP);
__ CallStub(&stub);
__ cmp(r0, Operand::Zero());
__ mov(scratch2, Operand(r2));
__ ldm(ia_w, sp, spill_mask);
__ b(ne, done);
__ b(eq, 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
// r1: 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 = r0;
Register dictionary = r0;
Register key = r1;
Register index = r2;
Register mask = r3;
Register hash = r4;
Register undefined = r5;
Register entry_key = r6;
Label in_dictionary, maybe_in_dictionary, not_in_dictionary;
__ ldr(mask, FieldMemOperand(dictionary, kCapacityOffset));
__ SmiUntag(mask);
__ sub(mask, mask, Operand(1));
__ ldr(hash, FieldMemOperand(key, Name::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.
ASSERT(NameDictionary::GetProbeOffset(i) <
1 << (32 - Name::kHashFieldOffset));
__ add(index, hash, Operand(
NameDictionary::GetProbeOffset(i) << Name::kHashShift));
} else {
__ mov(index, Operand(hash));
}
__ and_(index, mask, Operand(index, LSR, Name::kHashShift));
// Scale the index by multiplying by the entry size.
ASSERT(NameDictionary::kEntrySize == 3);
__ add(index, index, Operand(index, LSL, 1)); // index *= 3.
ASSERT_EQ(kSmiTagSize, 1);
__ add(index, dictionary, Operand(index, LSL, 2));
__ ldr(entry_key, FieldMemOperand(index, kElementsStartOffset));
// Having undefined at this place means the name is not contained.
__ cmp(entry_key, Operand(undefined));
__ b(eq, ¬_in_dictionary);
// Stop if found the property.
__ cmp(entry_key, Operand(key));
__ b(eq, &in_dictionary);
if (i != kTotalProbes - 1 && mode_ == NEGATIVE_LOOKUP) {
// Check if the entry name is not a unique name.
__ ldr(entry_key, FieldMemOperand(entry_key, HeapObject::kMapOffset));
__ ldrb(entry_key,
FieldMemOperand(entry_key, Map::kInstanceTypeOffset));
__ JumpIfNotUniqueName(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) {
__ mov(result, Operand::Zero());
__ Ret();
}
__ bind(&in_dictionary);
__ mov(result, Operand(1));
__ Ret();
__ bind(¬_in_dictionary);
__ mov(result, Operand::Zero());
__ Ret();
}
void StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(
Isolate* isolate) {
StoreBufferOverflowStub stub1(kDontSaveFPRegs);
stub1.GetCode(isolate);
// Hydrogen code stubs need stub2 at snapshot time.
StoreBufferOverflowStub stub2(kSaveFPRegs);
stub2.GetCode(isolate);
}
bool CodeStub::CanUseFPRegisters() {
return true; // VFP2 is a base requirement for V8
}
// 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 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 a compare instructions (a nop in this position) and the
// real branch when we start and stop incremental heap marking.
// See RecordWriteStub::Patch for details.
{
// Block literal pool emission, as the position of these two instructions
// is assumed by the patching code.
Assembler::BlockConstPoolScope block_const_pool(masm);
__ b(&skip_to_incremental_noncompacting);
__ b(&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.
ASSERT(Assembler::GetBranchOffset(masm->instr_at(0)) < (1 << 12));
ASSERT(Assembler::GetBranchOffset(masm->instr_at(4)) < (1 << 12));
PatchBranchIntoNop(masm, 0);
PatchBranchIntoNop(masm, Assembler::kInstrSize);
}
void RecordWriteStub::GenerateIncremental(MacroAssembler* masm, Mode mode) {
regs_.Save(masm);
if (remembered_set_action_ == EMIT_REMEMBERED_SET) {
Label dont_need_remembered_set;
__ ldr(regs_.scratch0(), MemOperand(regs_.address(), 0));
__ JumpIfNotInNewSpace(regs_.scratch0(), // Value.
regs_.scratch0(),
&dont_need_remembered_set);
__ CheckPageFlag(regs_.object(),
regs_.scratch0(),
1 << MemoryChunk::SCAN_ON_SCAVENGE,
ne,
&dont_need_remembered_set);
// First notify the incremental marker if necessary, then update the
// remembered set.
CheckNeedsToInformIncrementalMarker(
masm, kUpdateRememberedSetOnNoNeedToInformIncrementalMarker, mode);
InformIncrementalMarker(masm, mode);
regs_.Restore(masm);
__ RememberedSetHelper(object_,
address_,
value_,
save_fp_regs_mode_,
MacroAssembler::kReturnAtEnd);
__ bind(&dont_need_remembered_set);
}
CheckNeedsToInformIncrementalMarker(
masm, kReturnOnNoNeedToInformIncrementalMarker, mode);
InformIncrementalMarker(masm, mode);
regs_.Restore(masm);
__ Ret();
}
void RecordWriteStub::InformIncrementalMarker(MacroAssembler* masm, Mode mode) {
regs_.SaveCallerSaveRegisters(masm, save_fp_regs_mode_);
int argument_count = 3;
__ PrepareCallCFunction(argument_count, regs_.scratch0());
Register address =
r0.is(regs_.address()) ? regs_.scratch0() : regs_.address();
ASSERT(!address.is(regs_.object()));
ASSERT(!address.is(r0));
__ Move(address, regs_.address());
__ Move(r0, regs_.object());
__ Move(r1, address);
__ mov(r2, Operand(ExternalReference::isolate_address(masm->isolate())));
AllowExternalCallThatCantCauseGC scope(masm);
if (mode == INCREMENTAL_COMPACTION) {
__ CallCFunction(
ExternalReference::incremental_evacuation_record_write_function(
masm->isolate()),
argument_count);
} else {
ASSERT(mode == INCREMENTAL);
__ CallCFunction(
ExternalReference::incremental_marking_record_write_function(
masm->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;
__ and_(regs_.scratch0(), regs_.object(), Operand(~Page::kPageAlignmentMask));
__ ldr(regs_.scratch1(),
MemOperand(regs_.scratch0(),
MemoryChunk::kWriteBarrierCounterOffset));
__ sub(regs_.scratch1(), regs_.scratch1(), Operand(1), SetCC);
__ str(regs_.scratch1(),
MemOperand(regs_.scratch0(),
MemoryChunk::kWriteBarrierCounterOffset));
__ b(mi, &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.
__ ldr(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());
__ EnsureNotWhite(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 StoreArrayLiteralElementStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r0 : element value to store
// -- r3 : element index as smi
// -- sp[0] : array literal index in function as smi
// -- sp[4] : array literal
// clobbers r1, r2, r4
// -----------------------------------
Label element_done;
Label double_elements;
Label smi_element;
Label slow_elements;
Label fast_elements;
// Get array literal index, array literal and its map.
__ ldr(r4, MemOperand(sp, 0 * kPointerSize));
__ ldr(r1, MemOperand(sp, 1 * kPointerSize));
__ ldr(r2, FieldMemOperand(r1, JSObject::kMapOffset));
__ CheckFastElements(r2, r5, &double_elements);
// FAST_*_SMI_ELEMENTS or FAST_*_ELEMENTS
__ JumpIfSmi(r0, &smi_element);
__ CheckFastSmiElements(r2, r5, &fast_elements);
// Store into the array literal requires a elements transition. Call into
// the runtime.
__ bind(&slow_elements);
// call.
__ Push(r1, r3, r0);
__ ldr(r5, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
__ ldr(r5, FieldMemOperand(r5, JSFunction::kLiteralsOffset));
__ Push(r5, r4);
__ TailCallRuntime(Runtime::kStoreArrayLiteralElement, 5, 1);
// Array literal has ElementsKind of FAST_*_ELEMENTS and value is an object.
__ bind(&fast_elements);
__ ldr(r5, FieldMemOperand(r1, JSObject::kElementsOffset));
__ add(r6, r5, Operand::PointerOffsetFromSmiKey(r3));
__ add(r6, r6, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
__ str(r0, MemOperand(r6, 0));
// Update the write barrier for the array store.
__ RecordWrite(r5, r6, r0, kLRHasNotBeenSaved, kDontSaveFPRegs,
EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
__ Ret();
// Array literal has ElementsKind of FAST_*_SMI_ELEMENTS or FAST_*_ELEMENTS,
// and value is Smi.
__ bind(&smi_element);
__ ldr(r5, FieldMemOperand(r1, JSObject::kElementsOffset));
__ add(r6, r5, Operand::PointerOffsetFromSmiKey(r3));
__ str(r0, FieldMemOperand(r6, FixedArray::kHeaderSize));
__ Ret();
// Array literal has ElementsKind of FAST_DOUBLE_ELEMENTS.
__ bind(&double_elements);
__ ldr(r5, FieldMemOperand(r1, JSObject::kElementsOffset));
__ StoreNumberToDoubleElements(r0, r3, r5, r6, d0, &slow_elements);
__ Ret();
}
void StubFailureTrampolineStub::Generate(MacroAssembler* masm) {
CEntryStub ces(1, fp_registers_ ? kSaveFPRegs : kDontSaveFPRegs);
__ Call(ces.GetCode(masm->isolate()), RelocInfo::CODE_TARGET);
int parameter_count_offset =
StubFailureTrampolineFrame::kCallerStackParameterCountFrameOffset;
__ ldr(r1, MemOperand(fp, parameter_count_offset));
if (function_mode_ == JS_FUNCTION_STUB_MODE) {
__ add(r1, r1, Operand(1));
}
masm->LeaveFrame(StackFrame::STUB_FAILURE_TRAMPOLINE);
__ mov(r1, Operand(r1, LSL, kPointerSizeLog2));
__ add(sp, sp, r1);
__ Ret();
}
void StubFailureTailCallTrampolineStub::Generate(MacroAssembler* masm) {
CEntryStub ces(1, fp_registers_ ? kSaveFPRegs : kDontSaveFPRegs);
__ Call(ces.GetCode(masm->isolate()), RelocInfo::CODE_TARGET);
__ mov(r1, r0);
int parameter_count_offset =
StubFailureTrampolineFrame::kCallerStackParameterCountFrameOffset;
__ ldr(r0, MemOperand(fp, parameter_count_offset));
// The parameter count above includes the receiver for the arguments passed to
// the deoptimization handler. Subtract the receiver for the parameter count
// for the call.
__ sub(r0, r0, Operand(1));
masm->LeaveFrame(StackFrame::STUB_FAILURE_TRAMPOLINE);
ParameterCount argument_count(r0);
__ InvokeFunction(
r1, argument_count, JUMP_FUNCTION, NullCallWrapper(), CALL_AS_METHOD);
}
void ProfileEntryHookStub::MaybeCallEntryHook(MacroAssembler* masm) {
if (masm->isolate()->function_entry_hook() != NULL) {
PredictableCodeSizeScope predictable(masm, 4 * Assembler::kInstrSize);
ProfileEntryHookStub stub;
__ push(lr);
__ CallStub(&stub);
__ pop(lr);
}
}
void ProfileEntryHookStub::Generate(MacroAssembler* masm) {
// The entry hook is a "push lr" instruction, followed by a call.
const int32_t kReturnAddressDistanceFromFunctionStart =
3 * Assembler::kInstrSize;
// This should contain all kCallerSaved registers.
const RegList kSavedRegs =
1 << 0 | // r0
1 << 1 | // r1
1 << 2 | // r2
1 << 3 | // r3
1 << 5 | // r5
1 << 9; // r9
// We also save lr, so the count here is one higher than the mask indicates.
const int32_t kNumSavedRegs = 7;
ASSERT((kCallerSaved & kSavedRegs) == kCallerSaved);
// Save all caller-save registers as this may be called from anywhere.
__ stm(db_w, sp, kSavedRegs | lr.bit());
// Compute the function's address for the first argument.
__ sub(r0, lr, Operand(kReturnAddressDistanceFromFunctionStart));
// The caller's return address is above the saved temporaries.
// Grab that for the second argument to the hook.
__ add(r1, sp, Operand(kNumSavedRegs * kPointerSize));
// Align the stack if necessary.
int frame_alignment = masm->ActivationFrameAlignment();
if (frame_alignment > kPointerSize) {
__ mov(r5, sp);
ASSERT(IsPowerOf2(frame_alignment));
__ and_(sp, sp, Operand(-frame_alignment));
}
#if V8_HOST_ARCH_ARM
int32_t entry_hook =
reinterpret_cast<int32_t>(masm->isolate()->function_entry_hook());
__ mov(ip, Operand(entry_hook));
#else
// 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(r2, Operand(ExternalReference::isolate_address(masm->isolate())));
ApiFunction dispatcher(FUNCTION_ADDR(EntryHookTrampoline));
__ mov(ip, Operand(ExternalReference(&dispatcher,
ExternalReference::BUILTIN_CALL,
masm->isolate())));
#endif
__ Call(ip);
// Restore the stack pointer if needed.
if (frame_alignment > kPointerSize) {
__ mov(sp, r5);
}
// Also pop pc to get Ret(0).
__ ldm(ia_w, sp, kSavedRegs | pc.bit());
}
template<class T>
static void CreateArrayDispatch(MacroAssembler* masm,
AllocationSiteOverrideMode mode) {
if (mode == DISABLE_ALLOCATION_SITES) {
T stub(GetInitialFastElementsKind(),
CONTEXT_CHECK_REQUIRED,
mode);
__ TailCallStub(&stub);
} else if (mode == DONT_OVERRIDE) {
int last_index = GetSequenceIndexFromFastElementsKind(
TERMINAL_FAST_ELEMENTS_KIND);
for (int i = 0; i <= last_index; ++i) {
Label next;
ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
__ cmp(r3, Operand(kind));
__ b(ne, &next);
T stub(kind);
__ TailCallStub(&stub);
__ bind(&next);
}
// If we reached this point there is a problem.
__ Abort(kUnexpectedElementsKindInArrayConstructor);
} else {
UNREACHABLE();
}
}
static void CreateArrayDispatchOneArgument(MacroAssembler* masm,
AllocationSiteOverrideMode mode) {
// r2 - type info cell (if mode != DISABLE_ALLOCATION_SITES)
// r3 - kind (if mode != DISABLE_ALLOCATION_SITES)
// r0 - number of arguments
// r1 - constructor?
// sp[0] - last argument
Label normal_sequence;
if (mode == DONT_OVERRIDE) {
ASSERT(FAST_SMI_ELEMENTS == 0);
ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
ASSERT(FAST_ELEMENTS == 2);
ASSERT(FAST_HOLEY_ELEMENTS == 3);
ASSERT(FAST_DOUBLE_ELEMENTS == 4);
ASSERT(FAST_HOLEY_DOUBLE_ELEMENTS == 5);
// is the low bit set? If so, we are holey and that is good.
__ tst(r3, Operand(1));
__ b(ne, &normal_sequence);
}
// look at the first argument
__ ldr(r5, MemOperand(sp, 0));
__ cmp(r5, Operand::Zero());
__ b(eq, &normal_sequence);
if (mode == DISABLE_ALLOCATION_SITES) {
ElementsKind initial = GetInitialFastElementsKind();
ElementsKind holey_initial = GetHoleyElementsKind(initial);
ArraySingleArgumentConstructorStub stub_holey(holey_initial,
CONTEXT_CHECK_REQUIRED,
DISABLE_ALLOCATION_SITES);
__ TailCallStub(&stub_holey);
__ bind(&normal_sequence);
ArraySingleArgumentConstructorStub stub(initial,
CONTEXT_CHECK_REQUIRED,
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 cell).
__ add(r3, r3, Operand(1));
__ ldr(r5, FieldMemOperand(r2, Cell::kValueOffset));
if (FLAG_debug_code) {
__ ldr(r5, FieldMemOperand(r5, 0));
__ CompareRoot(r5, Heap::kAllocationSiteMapRootIndex);
__ Assert(eq, kExpectedAllocationSiteInCell);
__ ldr(r5, FieldMemOperand(r2, Cell::kValueOffset));
}
// Save the resulting elements kind in type info. We can't just store r3
// 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);
__ ldr(r4, FieldMemOperand(r5, AllocationSite::kTransitionInfoOffset));
__ add(r4, r4, Operand(Smi::FromInt(kFastElementsKindPackedToHoley)));
__ str(r4, FieldMemOperand(r5, AllocationSite::kTransitionInfoOffset));
__ bind(&normal_sequence);
int last_index = GetSequenceIndexFromFastElementsKind(
TERMINAL_FAST_ELEMENTS_KIND);
for (int i = 0; i <= last_index; ++i) {
Label next;
ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
__ cmp(r3, Operand(kind));
__ b(ne, &next);
ArraySingleArgumentConstructorStub stub(kind);
__ TailCallStub(&stub);
__ bind(&next);
}
// If we reached this point there is a problem.
__ Abort(kUnexpectedElementsKindInArrayConstructor);
} else {
UNREACHABLE();
}
}
template<class T>
static void ArrayConstructorStubAheadOfTimeHelper(Isolate* isolate) {
ElementsKind initial_kind = GetInitialFastElementsKind();
ElementsKind initial_holey_kind = GetHoleyElementsKind(initial_kind);
int to_index = GetSequenceIndexFromFastElementsKind(
TERMINAL_FAST_ELEMENTS_KIND);
for (int i = 0; i <= to_index; ++i) {
ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
T stub(kind);
stub.GetCode(isolate);
if (AllocationSite::GetMode(kind) != DONT_TRACK_ALLOCATION_SITE ||
(!FLAG_track_allocation_sites &&
(kind == initial_kind || kind == initial_holey_kind))) {
T stub1(kind, CONTEXT_CHECK_REQUIRED, DISABLE_ALLOCATION_SITES);
stub1.GetCode(isolate);
}
}
}
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(kinds[i]);
stubh1.GetCode(isolate);
InternalArraySingleArgumentConstructorStub stubh2(kinds[i]);
stubh2.GetCode(isolate);
InternalArrayNArgumentsConstructorStub stubh3(kinds[i]);
stubh3.GetCode(isolate);
}
}
void ArrayConstructorStub::GenerateDispatchToArrayStub(
MacroAssembler* masm,
AllocationSiteOverrideMode mode) {
if (argument_count_ == ANY) {
Label not_zero_case, not_one_case;
__ tst(r0, r0);
__ b(ne, ¬_zero_case);
CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode);
__ bind(¬_zero_case);
__ cmp(r0, Operand(1));
__ b(gt, ¬_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 -------------
// -- r0 : argc (only if argument_count_ == ANY)
// -- r1 : constructor
// -- r2 : type info cell
// -- 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.
__ ldr(r3, FieldMemOperand(r1, JSFunction::kPrototypeOrInitialMapOffset));
// Will both indicate a NULL and a Smi.
__ tst(r3, Operand(kSmiTagMask));
__ Assert(ne, kUnexpectedInitialMapForArrayFunction);
__ CompareObjectType(r3, r3, r4, MAP_TYPE);
__ Assert(eq, kUnexpectedInitialMapForArrayFunction);
// We should either have undefined in ebx or a valid cell
Label okay_here;
Handle<Map> cell_map = masm->isolate()->factory()->cell_map();
__ CompareRoot(r2, Heap::kUndefinedValueRootIndex);
__ b(eq, &okay_here);
__ ldr(r3, FieldMemOperand(r2, 0));
__ cmp(r3, Operand(cell_map));
__ Assert(eq, kExpectedPropertyCellInRegisterEbx);
__ bind(&okay_here);
}
Label no_info;
// Get the elements kind and case on that.
__ CompareRoot(r2, Heap::kUndefinedValueRootIndex);
__ b(eq, &no_info);
__ ldr(r3, FieldMemOperand(r2, Cell::kValueOffset));
// If the type cell is undefined, or contains anything other than an
// AllocationSite, call an array constructor that doesn't use AllocationSites.
__ ldr(r4, FieldMemOperand(r3, 0));
__ CompareRoot(r4, Heap::kAllocationSiteMapRootIndex);
__ b(ne, &no_info);
__ ldr(r3, FieldMemOperand(r3, AllocationSite::kTransitionInfoOffset));
__ SmiUntag(r3);
STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0);
__ and_(r3, r3, Operand(AllocationSite::ElementsKindBits::kMask));
GenerateDispatchToArrayStub(masm, DONT_OVERRIDE);
__ bind(&no_info);
GenerateDispatchToArrayStub(masm, DISABLE_ALLOCATION_SITES);
}
void InternalArrayConstructorStub::GenerateCase(
MacroAssembler* masm, ElementsKind kind) {
Label not_zero_case, not_one_case;
Label normal_sequence;
__ tst(r0, r0);
__ b(ne, ¬_zero_case);
InternalArrayNoArgumentConstructorStub stub0(kind);
__ TailCallStub(&stub0);
__ bind(¬_zero_case);
__ cmp(r0, Operand(1));
__ b(gt, ¬_one_case);
if (IsFastPackedElementsKind(kind)) {
// We might need to create a holey array
// look at the first argument
__ ldr(r3, MemOperand(sp, 0));
__ cmp(r3, Operand::Zero());
__ b(eq, &normal_sequence);
InternalArraySingleArgumentConstructorStub
stub1_holey(GetHoleyElementsKind(kind));
__ TailCallStub(&stub1_holey);
}
__ bind(&normal_sequence);
InternalArraySingleArgumentConstructorStub stub1(kind);
__ TailCallStub(&stub1);
__ bind(¬_one_case);
InternalArrayNArgumentsConstructorStub stubN(kind);
__ TailCallStub(&stubN);
}
void InternalArrayConstructorStub::Generate(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- r0 : argc
// -- r1 : 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.
__ ldr(r3, FieldMemOperand(r1, JSFunction::kPrototypeOrInitialMapOffset));
// Will both indicate a NULL and a Smi.
__ tst(r3, Operand(kSmiTagMask));
__ Assert(ne, kUnexpectedInitialMapForArrayFunction);
__ CompareObjectType(r3, r3, r4, MAP_TYPE);
__ Assert(eq, kUnexpectedInitialMapForArrayFunction);
}
// Figure out the right elements kind
__ ldr(r3, FieldMemOperand(r1, JSFunction::kPrototypeOrInitialMapOffset));
// Load the map's "bit field 2" into |result|. We only need the first byte,
// but the following bit field extraction takes care of that anyway.
__ ldr(r3, FieldMemOperand(r3, Map::kBitField2Offset));
// Retrieve elements_kind from bit field 2.
__ Ubfx(r3, r3, Map::kElementsKindShift, Map::kElementsKindBitCount);
if (FLAG_debug_code) {
Label done;
__ cmp(r3, Operand(FAST_ELEMENTS));
__ b(eq, &done);
__ cmp(r3, Operand(FAST_HOLEY_ELEMENTS));
__ Assert(eq,
kInvalidElementsKindForInternalArrayOrInternalPackedArray);
__ bind(&done);
}
Label fast_elements_case;
__ cmp(r3, Operand(FAST_ELEMENTS));
__ b(eq, &fast_elements_case);
GenerateCase(masm, FAST_HOLEY_ELEMENTS);
__ bind(&fast_elements_case);
GenerateCase(masm, FAST_ELEMENTS);
}
#undef __
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_ARM
| [
"h0x91b@gmail.com"
] | h0x91b@gmail.com |
08a8d5715ce04c218b57c309256c5b9eb1745262 | ff9bc40f14868b4f73593115c17c73cf23e34b0d | /Homework/hw11/hw11.ino | 84e22f392b622259918dd0882bceaecbbc39a02c | [] | no_license | ihansam/Semester7_CapstoneDesign_HW | 256b60db494897a8a3b0b4257420c5dfc10e4902 | eea5b0491e35681b586ee22104f0097dfdeb7fb2 | refs/heads/master | 2022-09-04T06:43:11.120201 | 2020-05-26T14:27:54 | 2020-05-26T14:27:54 | 264,071,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | ino | // 블루투스 모듈
#include <SoftwareSerial.h>
int blueTx=11; //Tx (보내는핀 설정)
int blueRx=10; //Rx (받는핀 설정)
SoftwareSerial mySerial(blueTx, blueRx);
// 서보 모터
#include <Servo.h>
Servo servo;
int pos = 90; // 초기 각도
String myString=""; // 받는 문자열
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
mySerial.write("Enter the up or down\n"); // 초기 스마트폰 출력
mySerial.write("up = angle + 15\n");
mySerial.write("down = angle - 15");
servo.attach(24, 600, 2400);
servo.write(pos);
delay(1000);
servo.detach();
}
void loop() {
while(mySerial.available()) // 스마트폰에 문자가 입력되면
{
char myChar = (char)mySerial.read();
myString+=myChar; // 한 글자씩 myString에 저장
delay(5); //수신 문자열 끊김 방지
}
if(!myString.equals("")) // myString에 문자열이 생겼을 때
{
if(myString=="up" && pos<180) // 문자열이 up이고 각도가 180도 미만일 때
{
servo.attach(24, 600, 2400); // 서보모터 각도롤 15도 키움
for (int i = pos+1; i<=pos+15; ++i){
servo.write(i);
delay(15);
}
servo.detach();
pos += 15;
mySerial.write("+15 "); // 스마트폰에 +15 현재각도 출력
mySerial.print(pos);
}
else if(myString=="down" && pos>0) // 문자열이 down이고 각도가 0도 초과일 때
{
servo.attach(24, 600, 2400); // 서보모터 각도를 15도 줄임
for (int i = pos-1; i>=pos-15; --i){
servo.write(i);
delay(15);
}
servo.detach();
pos -= 15;
mySerial.write("-15 "); // 스마트폰에 -15 현재각도 출력
mySerial.print(pos);
}
else // 입력 문자열이 up 또는 down이 아니면 출력
{
mySerial.write("wrong operation!!");
}
myString=""; //myString 변수값 초기화
}
}
| [
"ihansam@skku.edu"
] | ihansam@skku.edu |
8cfe8ed4ea8ea406c687849f0d84c91040db7547 | 43cb929bc7a4dd7b8c98a679d22fd60509ce9ed0 | /handlesettings.h | 7fc5842cd0e5f81dbbc6594eba1131d2b5aaf54f | [] | no_license | GiteZz/FolderFilter | 5de176fd1790b71d2a8107db1fe107f282c52044 | cd3548e675cb716968f80c6fa8d6e2beb661ecef | refs/heads/master | 2020-06-14T05:30:32.837817 | 2018-03-13T12:34:38 | 2018-03-13T12:34:38 | 75,227,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 333 | h | #ifndef HANDLESETTINGS_H
#define HANDLESETTINGS_H
#include <QString>
#include<vector>
class handleSettings
{
public:
handleSettings();
static std::vector<QString> getInfoFromTag(QString settingsFileLocation,QString tag);
static struct nameStruct readFile(std::vector<QString> location);
};
#endif // HANDLESETTINGS_H
| [
"gi.ba@live.be"
] | gi.ba@live.be |
aca8e159b4000ceee44be7384401509b954ef091 | 1d42d1076ddaa08e5871326b63b8a370faacae42 | /system/controlDict~ | d8cdf378918f428156ff3c58b27bb047f43ab84f | [] | no_license | dhanvi97/OpenFOAM-Project | 6aba1036f9f867d1e6780d603f40ddab3d08559e | abf7e87a02270a3c8530e1af986ed7d6453b9cca | refs/heads/master | 2020-03-29T08:47:24.297791 | 2017-06-18T06:00:26 | 2017-06-18T06:00:26 | 94,668,278 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,253 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system";
object controlDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
application simpleFoam;
startFrom startTime;
startTime 0;
stopAt endTime;
endTime 500;
deltaT 1;
writeControl timeStep;
writeInterval 50;
purgeWrite 0;
writeFormat ascii;
writePrecision 6;
writeCompression off;
timeFormat general;
timePrecision 6;
runTimeModifiable true;
functions
{
#include "forceCoeffs"
}
// ************************************************************************* //
| [
"anantjoshi67iitb@gmail.com"
] | anantjoshi67iitb@gmail.com | |
25dfb8a716759147fffedd4e2354321463676ffc | 084006eb442b60b82b3d85d61a3b53d21c5c8855 | /shared/Arduboy/ArduboyPlaytune.cpp | 0152b6d27b1ee724a43ae7011b7889aef9ef436d | [
"XFree86-1.1",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | SethRobinson/proton | 7aadcb38bc676c136dce01b8f6773fd75fa33d55 | 6b1474e75a2acf48d848c70fcb043ce8223001a9 | refs/heads/master | 2023-08-31T11:04:21.575522 | 2023-08-29T07:44:50 | 2023-08-29T07:44:50 | 142,253,855 | 81 | 31 | NOASSERTION | 2023-08-07T22:02:41 | 2018-07-25T05:55:38 | C++ | UTF-8 | C++ | false | false | 9,147 | cpp | #include "ArduboyPlaytune.h"
#include <avr/power.h>
#include "audio/audio.h"
const byte PROGMEM tune_pin_to_timer_PGM[] = { 3, 1 };
volatile byte *_tunes_timer1_pin_port;
volatile byte _tunes_timer1_pin_mask;
volatile int32_t timer1_toggle_count;
volatile byte *_tunes_timer3_pin_port;
volatile byte _tunes_timer3_pin_mask;
byte _tune_pins[AVAILABLE_TIMERS];
byte _tune_num_chans = 0;
volatile boolean tune_playing = false; // is the score still playing?
volatile unsigned wait_timer_frequency2; /* its current frequency */
volatile boolean wait_timer_playing = false; /* is it currently playing a note? */
volatile boolean tonePlaying = false;
volatile unsigned long wait_toggle_count; /* countdown score waits */
#define F_CPU 800000 //random crap set by seth
// pointers to your musical score and your position in said score
volatile const byte *score_start = 0;
volatile const byte *score_cursor = 0;
// Table of midi note frequencies * 2
// They are times 2 for greater accuracy, yet still fits in a word.
// Generated from Excel by =ROUND(2*440/32*(2^((x-9)/12)),0) for 0<x<128
// The lowest notes might not work, depending on the Arduino clock frequency
// Ref: http://www.phy.mtu.edu/~suits/notefreqs.html
const uint8_t PROGMEM _midi_byte_note_frequencies[48] = {
16,17,18,19,21,22,23,24,26,28,29,31,33,35,37,39,41,44,46,49,52,55,58,62,65,
69,73,78,82,87,92,98,104,110,117,123,131,139,147,156,165,175,185,196,208,220,
233,247
};
const unsigned int PROGMEM _midi_word_note_frequencies[80] = {
262,277,294,311,330,349,370,392,415,440,466,494,523,554,587,622,659,
698,740,784,831,880,932,988,1047,1109,1175,1245,1319,1397,1480,1568,1661,1760,
1865,1976,2093,2217,2349,2489,2637,2794,2960,3136,3322,3520,3729,3951,4186,
4435,4699,4978,5274,5588,5920,6272,6645,7040,7459,7902,8372,8870,9397,9956,
10548,11175,11840,12544,13290,14080,14917,15804,16744,17740,18795,19912,21096,
22351,23680,25088 };
void ArduboyPlaytune::initChannel(byte pin)
{
/*
byte timer_num;
// we are all out of timers
if (_tune_num_chans == AVAILABLE_TIMERS)
return;
timer_num = pgm_read_byte(tune_pin_to_timer_PGM + _tune_num_chans);
_tune_pins[_tune_num_chans] = pin;
_tune_num_chans++;
pinMode(pin, OUTPUT);
switch (timer_num) {
case 1: // 16 bit timer
power_timer1_enable();
TCCR1A = 0;
TCCR1B = 0;
bitWrite(TCCR1B, WGM12, 1);
bitWrite(TCCR1B, CS10, 1);
_tunes_timer1_pin_port = portOutputRegister(digitalPinToPort(pin));
_tunes_timer1_pin_mask = digitalPinToBitMask(pin);
break;
case 3: // 16 bit timer
power_timer3_enable();
TCCR3A = 0;
TCCR3B = 0;
bitWrite(TCCR3B, WGM32, 1);
bitWrite(TCCR3B, CS30, 1);
_tunes_timer3_pin_port = portOutputRegister(digitalPinToPort(pin));
_tunes_timer3_pin_mask = digitalPinToBitMask(pin);
playNote(0, 60);
stopNote(0);
break;
}
*/
}
void ArduboyPlaytune::playNote(byte chan, byte note)
{
/*
byte timer_num;
byte prescalar_bits;
unsigned int frequency2;
unsigned long ocr;
// we can't plan on a channel that does not exist
if (chan >= _tune_num_chans)
return;
// we only have frequencies for 128 notes
if (note > 127) {
return;
}
timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan);
if (note < 48) {
frequency2 = pgm_read_byte(_midi_byte_note_frequencies + note);
} else {
frequency2 = pgm_read_word(_midi_word_note_frequencies + note - 48);
}
// ****** 16-bit timer *********
// two choices for the 16 bit timers: ck/1 or ck/64
ocr = F_CPU / frequency2 - 1;
prescalar_bits = 0b001;
if (ocr > 0xffff) {
ocr = F_CPU / frequency2 / 64 - 1;
prescalar_bits = 0b011;
}
// Set the OCR for the given timer, then turn on the interrupts
switch (timer_num) {
case 1:
TCCR1B = (TCCR1B & 0b11111000) | prescalar_bits;
OCR1A = ocr;
bitWrite(TIMSK1, OCIE1A, 1);
break;
case 3:
TCCR3B = (TCCR3B & 0b11111000) | prescalar_bits;
OCR3A = ocr;
wait_timer_frequency2 = frequency2; // for "tune_delay" function
wait_timer_playing = true;
bitWrite(TIMSK3, OCIE3A, 1);
break;
}
*/
}
void ArduboyPlaytune::stopNote(byte chan)
{
byte timer_num;
timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan);
switch (timer_num) {
case 1:
TIMSK1 &= ~(1 << OCIE1A); // disable the interrupt
*_tunes_timer1_pin_port &= ~(_tunes_timer1_pin_mask); // keep pin low after stop
break;
case 3:
wait_timer_playing = false;
*_tunes_timer3_pin_port &= ~(_tunes_timer3_pin_mask); // keep pin low after stop
break;
}
}
void ArduboyPlaytune::playScore(const byte *score)
{
if (!ArduboyAudio::audio_enabled) return;
score_start = score;
score_cursor = score_start;
step(); /* execute initial commands */
tune_playing = true; /* release the interrupt routine */
}
void ArduboyPlaytune::stopScore (void)
{
for (uint8_t i = 0; i < _tune_num_chans; i++)
stopNote(i);
tune_playing = false;
}
bool ArduboyPlaytune::playing()
{
return tune_playing;
}
/* Do score commands until a "wait" is found, or the score is stopped.
This is called initially from tune_playcore, but then is called
from the interrupt routine when waits expire.
*/
/* if CMD < 0x80, then the other 7 bits and the next byte are a 15-bit big-endian number of msec to wait */
void ArduboyPlaytune::step()
{
byte command, opcode, chan;
unsigned duration;
while (1) {
command = pgm_read_byte(score_cursor++);
opcode = command & 0xf0;
chan = command & 0x0f;
if (opcode == TUNE_OP_STOPNOTE) { /* stop note */
stopNote(chan);
}
else if (opcode == TUNE_OP_PLAYNOTE) { /* play note */
playNote(chan, pgm_read_byte(score_cursor++));
}
else if (opcode == TUNE_OP_RESTART) { /* restart score */
score_cursor = score_start;
}
else if (opcode == TUNE_OP_STOP) { /* stop score */
tune_playing = false;
break;
}
else if (opcode < 0x80) { /* wait count in msec. */
duration = ((unsigned)command << 8) | (pgm_read_byte(score_cursor++));
wait_toggle_count = ((unsigned long) wait_timer_frequency2 * duration + 500) / 1000;
if (wait_toggle_count == 0) wait_toggle_count = 1;
break;
}
}
}
void ArduboyPlaytune::closeChannels(void)
{
/*
byte timer_num;
for (uint8_t chan=0; chan < _tune_num_chans; chan++) {
timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan);
switch (timer_num) {
case 1:
TIMSK1 &= ~(1 << OCIE1A);
break;
case 3:
TIMSK3 &= ~(1 << OCIE3A);
break;
}
digitalWrite(_tune_pins[chan], 0);
}
_tune_num_chans = 0;
*/
tune_playing = false;
}
void ArduboyPlaytune::soundOutput()
{
if (wait_timer_playing) { // toggle the pin if we're sounding a note
*_tunes_timer3_pin_port ^= _tunes_timer3_pin_mask;
}
if (tune_playing && wait_toggle_count && --wait_toggle_count == 0) {
// end of a score wait, so execute more score commands
ArduboyPlaytune::step(); // execute commands
}
}
void ArduboyPlaytune::tone(unsigned int frequency, unsigned long duration)
{
if (!ArduboyAudio::audio_enabled) return;
tonePlaying = true;
uint8_t prescalarbits = 0x0b001;
int32_t toggle_count = 0;
uint32_t ocr = 0;
//LogMsg("Playing freq: %d", frequency);
//world's worst audio simulation
if (frequency > 1000)
{
GetAudioManager()->Play("audio/tone_high.wav");
} else if (frequency > 180)
{
GetAudioManager()->Play("audio/tone_quick.wav");
} else
{
GetAudioManager()->Play("audio/tone_low.wav");
}
return;
// two choices for the 16 bit timers: ck/1 or ck/64
ocr = F_CPU / frequency / 2 - 1;
prescalarbits = 0x0b001;
if (ocr > 0xffff) {
ocr = F_CPU / frequency / 2 / 64 - 1;
prescalarbits = 0x0b011;
}
//TCCR1B = (TCCR1B & 0x0b11111000) | prescalarbits;
// Calculate the toggle count
if (duration > 0) {
toggle_count = 2 * frequency * duration / 1000;
}
else {
toggle_count = -1;
}
// Set the OCR for the given timer,
// set the toggle count,
// then turn on the interrupts
OCR1A = ocr;
timer1_toggle_count = toggle_count;
bitWrite(TIMSK1, OCIE1A, 1);
}
// TIMER 1
void ISR(TIMER1_COMPA_vect)
{
/*
if (tonePlaying) {
if (timer1_toggle_count != 0) {
// toggle the pin
*_tunes_timer1_pin_port ^= _tunes_timer1_pin_mask;
if (timer1_toggle_count > 0) timer1_toggle_count--;
}
else {
tonePlaying = false;
TIMSK1 &= ~(1 << OCIE1A); // disable the interrupt
*_tunes_timer1_pin_port &= ~(_tunes_timer1_pin_mask); // keep pin low after stop
}
}
else {
*_tunes_timer1_pin_port ^= _tunes_timer1_pin_mask; // toggle the pin
}
*/
}
| [
"seth@rtsoft.com"
] | seth@rtsoft.com |
8f18feb210b239f29fca6a3f328360c5eaed1b70 | 7d0f76a3b69b1841d74dda54cd34e459c7da5aaf | /src/utils/BamTools/src/api/internal/io/TcpSocketEngine_p.h | 9218278b6342de7675528a4fdab0ddc773af9c03 | [
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | arq5x/lumpy-sv | aa313dd1dc24c5966a4347445180c9bb0fafc24a | f24085f5d7865579e390add664ebbd9383fa0536 | refs/heads/master | 2022-06-23T14:04:51.403033 | 2022-06-07T21:10:43 | 2022-06-07T21:10:43 | 6,121,988 | 285 | 127 | MIT | 2022-06-07T21:10:44 | 2012-10-08T09:09:26 | C | UTF-8 | C++ | false | false | 3,230 | h | // ***************************************************************************
// TcpSocketEngine_p.h (c) 2011 Derek Barnett
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 8 December 2011 (DB)
// ---------------------------------------------------------------------------
// Provides low-level implementation of TCP I/O
// ***************************************************************************
#ifndef TCPSOCKETENGINE_P_H
#define TCPSOCKETENGINE_P_H
// -------------
// W A R N I N G
// -------------
//
// This file is not part of the BamTools API. It exists purely as an
// implementation detail. This header file may change from version to version
// without notice, or even be removed.
//
// We mean it.
#include "api/internal/io/HostAddress_p.h"
#include "api/internal/io/TcpSocket_p.h"
#ifdef _WIN32
# include "api/internal/io/NetWin_p.h"
#endif
namespace BamTools {
namespace Internal {
struct TcpSocketEngine {
// ctors & dtor
public:
TcpSocketEngine(void);
TcpSocketEngine(const TcpSocketEngine& other);
~TcpSocketEngine(void);
// TcpSocketEngine interface
public:
// connection-related methods
void Close(void);
bool Connect(const HostAddress& address, const uint16_t port);
bool Initialize(HostAddress::NetworkProtocol protocol);
bool IsValid(void) const;
// IO-related methods
int64_t NumBytesAvailable(void) const;
int64_t Read(char* dest, size_t max);
int64_t Write(const char* data, size_t length);
bool WaitForRead(int msec, bool* timedOut);
bool WaitForWrite(int msec, bool* timedOut);
// query connection state
// HostAddress GetLocalAddress(void) const;
// uint16_t GetLocalPort(void) const;
HostAddress GetRemoteAddress(void) const;
uint16_t GetRemotePort(void) const;
int GetSocketDescriptor(void) const;
TcpSocket::SocketError GetSocketError(void);
TcpSocket::SocketState GetSocketState(void);
std::string GetErrorString(void) const;
// platform-dependent internal methods
// provided in the corresponding TcpSocketEngine_<OS>_p.cpp
private:
void nativeClose(void);
bool nativeConnect(const HostAddress& address, const uint16_t port);
bool nativeCreateSocket(HostAddress::NetworkProtocol protocol);
void nativeDisconnect(void);
int64_t nativeNumBytesAvailable(void) const;
int64_t nativeRead(char* dest, size_t max);
int nativeSelect(int msecs, bool isRead) const;
int64_t nativeWrite(const char* data, size_t length);
// data members
private:
int m_socketDescriptor;
// HostAddress m_localAddress;
HostAddress m_remoteAddress;
// uint16_t m_localPort;
uint16_t m_remotePort;
TcpSocket::SocketError m_socketError;
TcpSocket::SocketState m_socketState;
std::string m_errorString;
#ifdef _WIN32
WindowsSockInit m_win;
#endif
};
} // namespace Internal
} // namespace BamTools
#endif // TCPSOCKETENGINE_P_H
| [
"arq5x@virginia.edu"
] | arq5x@virginia.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.