repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
null | fantasia3d.unofficial-main/render/renderutils/c_src/mesh.h | /*
* Copyright (c) 2020-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
#include "common.h"
struct XfmKernelParams
{
bool isPoints;
Tensor points;
Tensor matrix;
Tensor out;
dim3 gridSize;
};
| 696 | 28.041667 | 80 | h |
null | fantasia3d.unofficial-main/render/renderutils/c_src/normal.h | /*
* Copyright (c) 2020-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
#include "common.h"
struct PrepareShadingNormalKernelParams
{
Tensor pos;
Tensor view_pos;
Tensor perturbed_nrm;
Tensor smooth_nrm;
Tensor smooth_tng;
Tensor geom_nrm;
Tensor out;
dim3 gridSize;
bool two_sided_shading, opengl;
};
| 786 | 27.107143 | 80 | h |
null | fantasia3d.unofficial-main/render/renderutils/c_src/vec3f.h | /*
* Copyright (c) 2020-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
struct vec3f
{
float x, y, z;
#ifdef __CUDACC__
__device__ vec3f() { }
__device__ vec3f(float v) { x = v; y = v; z = v; }
__device__ vec3f(float _x, float _y, float _z) { x = _x; y = _y; z = _z; }
__device__ vec3f(float3 v) { x = v.x; y = v.y; z = v.z; }
__device__ inline vec3f& operator+=(const vec3f& b) { x += b.x; y += b.y; z += b.z; return *this; }
__device__ inline vec3f& operator-=(const vec3f& b) { x -= b.x; y -= b.y; z -= b.z; return *this; }
__device__ inline vec3f& operator*=(const vec3f& b) { x *= b.x; y *= b.y; z *= b.z; return *this; }
__device__ inline vec3f& operator/=(const vec3f& b) { x /= b.x; y /= b.y; z /= b.z; return *this; }
#endif
};
#ifdef __CUDACC__
__device__ static inline vec3f operator+(const vec3f& a, const vec3f& b) { return vec3f(a.x + b.x, a.y + b.y, a.z + b.z); }
__device__ static inline vec3f operator-(const vec3f& a, const vec3f& b) { return vec3f(a.x - b.x, a.y - b.y, a.z - b.z); }
__device__ static inline vec3f operator*(const vec3f& a, const vec3f& b) { return vec3f(a.x * b.x, a.y * b.y, a.z * b.z); }
__device__ static inline vec3f operator/(const vec3f& a, const vec3f& b) { return vec3f(a.x / b.x, a.y / b.y, a.z / b.z); }
__device__ static inline vec3f operator-(const vec3f& a) { return vec3f(-a.x, -a.y, -a.z); }
__device__ static inline float sum(vec3f a)
{
return a.x + a.y + a.z;
}
__device__ static inline vec3f cross(vec3f a, vec3f b)
{
vec3f out;
out.x = a.y * b.z - a.z * b.y;
out.y = a.z * b.x - a.x * b.z;
out.z = a.x * b.y - a.y * b.x;
return out;
}
__device__ static inline void bwdCross(vec3f a, vec3f b, vec3f &d_a, vec3f &d_b, vec3f d_out)
{
d_a.x += d_out.z * b.y - d_out.y * b.z;
d_a.y += d_out.x * b.z - d_out.z * b.x;
d_a.z += d_out.y * b.x - d_out.x * b.y;
d_b.x += d_out.y * a.z - d_out.z * a.y;
d_b.y += d_out.z * a.x - d_out.x * a.z;
d_b.z += d_out.x * a.y - d_out.y * a.x;
}
__device__ static inline float dot(vec3f a, vec3f b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
__device__ static inline void bwdDot(vec3f a, vec3f b, vec3f& d_a, vec3f& d_b, float d_out)
{
d_a.x += d_out * b.x; d_a.y += d_out * b.y; d_a.z += d_out * b.z;
d_b.x += d_out * a.x; d_b.y += d_out * a.y; d_b.z += d_out * a.z;
}
__device__ static inline vec3f reflect(vec3f x, vec3f n)
{
return n * 2.0f * dot(n, x) - x;
}
__device__ static inline void bwdReflect(vec3f x, vec3f n, vec3f& d_x, vec3f& d_n, const vec3f d_out)
{
d_x.x += d_out.x * (2 * n.x * n.x - 1) + d_out.y * (2 * n.x * n.y) + d_out.z * (2 * n.x * n.z);
d_x.y += d_out.x * (2 * n.x * n.y) + d_out.y * (2 * n.y * n.y - 1) + d_out.z * (2 * n.y * n.z);
d_x.z += d_out.x * (2 * n.x * n.z) + d_out.y * (2 * n.y * n.z) + d_out.z * (2 * n.z * n.z - 1);
d_n.x += d_out.x * (2 * (2 * n.x * x.x + n.y * x.y + n.z * x.z)) + d_out.y * (2 * n.y * x.x) + d_out.z * (2 * n.z * x.x);
d_n.y += d_out.x * (2 * n.x * x.y) + d_out.y * (2 * (n.x * x.x + 2 * n.y * x.y + n.z * x.z)) + d_out.z * (2 * n.z * x.y);
d_n.z += d_out.x * (2 * n.x * x.z) + d_out.y * (2 * n.y * x.z) + d_out.z * (2 * (n.x * x.x + n.y * x.y + 2 * n.z * x.z));
}
__device__ static inline vec3f safeNormalize(vec3f v)
{
float l = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);
return l > 0.0f ? (v / l) : vec3f(0.0f);
}
__device__ static inline void bwdSafeNormalize(const vec3f v, vec3f& d_v, const vec3f d_out)
{
float l = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);
if (l > 0.0f)
{
float fac = 1.0 / powf(v.x * v.x + v.y * v.y + v.z * v.z, 1.5f);
d_v.x += (d_out.x * (v.y * v.y + v.z * v.z) - d_out.y * (v.x * v.y) - d_out.z * (v.x * v.z)) * fac;
d_v.y += (d_out.y * (v.x * v.x + v.z * v.z) - d_out.x * (v.y * v.x) - d_out.z * (v.y * v.z)) * fac;
d_v.z += (d_out.z * (v.x * v.x + v.y * v.y) - d_out.x * (v.z * v.x) - d_out.y * (v.z * v.y)) * fac;
}
}
#endif | 4,430 | 39.651376 | 125 | h |
null | fantasia3d.unofficial-main/render/renderutils/c_src/vec4f.h | /*
* Copyright (c) 2020-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
struct vec4f
{
float x, y, z, w;
#ifdef __CUDACC__
__device__ vec4f() { }
__device__ vec4f(float v) { x = v; y = v; z = v; w = v; }
__device__ vec4f(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; }
__device__ vec4f(float4 v) { x = v.x; y = v.y; z = v.z; w = v.w; }
#endif
};
| 831 | 31 | 96 | h |
null | SymbolicPCC-main/src/core/buffer.h | /*****************************************************************************
Copyright (c) 2001 - 2009, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 05/05/2009
*****************************************************************************/
#ifndef __UDT_BUFFER_H__
#define __UDT_BUFFER_H__
#include "udt.h"
#include "list.h"
#include "queue.h"
#include <fstream>
#include <queue>
class LessThan {
public:
int operator() (const int32_t& a, const int32_t& b) {
return b < a;
}
};
class CSndBuffer
{
public:
CSndBuffer(const int& size = 64, const int& mss = 1500);
~CSndBuffer();
// Functionality:
// Insert a user buffer into the sending list.
// Parameters:
// 0) [in] data: pointer to the user data block.
// 1) [in] len: size of the block.
// 2) [in] ttl: time to live in milliseconds
// 3) [in] order: if the block should be delivered in order, for DGRAM only
// Returned value:
// None.
void addBuffer(const char* data, const int& len, const int& ttl = -1, const bool& order = false);
// Functionality:
// Read a block of data from file and insert it into the sending list.
// Parameters:
// 0) [in] ifs: input file stream.
// 1) [in] len: size of the block.
// Returned value:
// actual size of data added from the file.
int addBufferFromFile(std::fstream& ifs, const int& len);
// Functionality:
// Find data position to pack a DATA packet from the furthest reading point.
// Parameters:
// 0) [out] data: the pointer to the data position.
// 1) [out] msgno: message number of the packet.
// Returned value:
// Actual length of data read.
int readData(char** data, int32_t& msgno);
// Functionality:
// Find data position to pack a DATA packet for a retransmission.
// Parameters:
// 0) [out] data: the pointer to the data position.
// 1) [in] offset: offset from the last ACK point.
// 2) [out] msgno: message number of the packet.
// 3) [out] msglen: length of the message
// Returned value:
// Actual length of data read.
int readData(char** data, const int offset, int32_t& msgno, int& msglen);
// Functionality:
// Update the ACK point and may release/unmap/return the user data according to the flag.
// Parameters:
// 0) [in] offset: number of packets acknowledged.
// Returned value:
// None.
void ackData(const int& offset);
// Functionality:
// Read size of data still in the sending list.
// Parameters:
// None.
// Returned value:
// Current size of the data in the sending list.
int getCurrBufSize() const;
void resizeMSS(int size);
private:
void increase();
private:
pthread_mutex_t m_BufLock; // used to synchronize buffer operation
struct Block
{
char* m_pcData; // pointer to the data block
int m_iLength; // length of the block
int32_t m_iMsgNo; // message number
int32_t m_iBufferNo;
uint64_t m_OriginTime; // original request time
int m_iTTL; // time to live (milliseconds)
Block* m_pNext; // next block
} *m_pBlock, *m_pFirstBlock, *m_pCurrBlock, *m_pLastBlock, *blockEnder;
// m_pBlock: The head pointer
// m_pFirstBlock: The first block
// m_pCurrBlock: The current block
// m_pLastBlock: The last block (if first == last, buffer is empty)
int FirstBlock;
struct Buffer
{
Block* first_block;
char* m_pcData; // buffer
int m_iSize; // size
Buffer* m_pNext; // next buffer
} *m_pBuffer, *FirstBuffer, *bufferEnder; // physical buffer
int32_t m_iNextMsgNo; // next message number
int m_iSize; // buffer size (number of packets)
int m_iMSS; // maximum seqment/packet size
int m_iCount; // number of used blocks
int m_iBlockSize;
private:
CSndBuffer(const CSndBuffer&);
CSndBuffer& operator=(const CSndBuffer&);
//Block* findBlock(int offset);
};
////////////////////////////////////////////////////////////////////////////////
class CRcvBuffer
{
public:
CRcvBuffer(CUnitQueue* queue, int32_t first_seq_no, const int& bufsize = 65536);
~CRcvBuffer();
// Functionality:
// Write data into the buffer.
// Parameters:
// 0) [in] unit: pointer to a data unit containing new packet
// 1) [in] offset: offset from last ACK point.
// Returned value:
// 0 is success, -1 if data is repeated.
int addData(CUnit* unit, int offset);
// Functionality:
// Read data into a user buffer.
// Parameters:
// 0) [in] data: pointer to user buffer.
// 1) [in] len: length of user buffer.
// Returned value:
// size of data read.
int readBuffer(char* data, const int& len);
// Functionality:
// Read data directly into file.
// Parameters:
// 0) [in] file: C++ file stream.
// 1) [in] len: expected length of data to write into the file.
// Returned value:
// size of data read.
int readBufferToFile(std::fstream& ofs, const int& len);
// Functionality:
// Update the ACK point of the buffer.
// Parameters:
// 0) [in] len: size of data to be acknowledged.
// Returned value:
// 1 if a user buffer is fulfilled, otherwise 0.
void AckData(int32_t seq_no);
// Functionality:
// Query how many buffer space left for data receiving.
// Parameters:
// None.
// Returned value:
// size of available buffer space (including user buffer) for data receiving.
int getAvailBufSize() const;
// Functionality:
// Query how many data has been continuously received (for reading).
// Parameters:
// None.
// Returned value:
// size of valid (continous) data for reading.
int getRcvDataSize() const;
// Functionality:
// mark the message to be dropped from the message list.
// Parameters:
// 0) [in] msgno: message nuumer.
// Returned value:
// None.
void dropMsg(const int32_t& msgno);
// Functionality:
// read a message.
// Parameters:
// 0) [out] data: buffer to write the message into.
// 1) [in] len: size of the buffer.
// Returned value:
// actuall size of data read.
int readMsg(char* data, const int& len);
// Functionality:
// Query how many messages are available now.
// Parameters:
// None.
// Returned value:
// number of messages available for recvmsg.
int getRcvMsgNum();
private:
bool scanMsg(int& start, int& end, bool& passack);
private:
CUnit** m_pUnit; // pointer to the protocol buffer
int m_iSize; // size of the protocol buffer
CUnitQueue* m_pUnitQueue; // the shared unit queue
int m_iStartPos; // the head position for I/O (inclusive)
int m_iLastAckPos; // the last ACKed position (exclusive)
// EMPTY: m_iStartPos = m_iLastAckPos FULL: m_iStartPos = m_iLastAckPos + 1
int m_iMaxPos; // the furthest data position
int m_iNotch; // the starting read point of the first unit
std::priority_queue<int32_t, std::vector<int32_t>, LessThan> ack_queue_;
int32_t seq_offset_;
private:
CRcvBuffer();
CRcvBuffer(const CRcvBuffer&);
CRcvBuffer& operator=(const CRcvBuffer&);
};
#endif
| 9,537 | 31.006711 | 100 | h |
null | SymbolicPCC-main/src/core/cache.h | /*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 01/27/2011
*****************************************************************************/
#ifndef __UDT_CACHE_H__
#define __UDT_CACHE_H__
#include <list>
#include <vector>
#include "common.h"
#include "udt.h"
class CCacheItem
{
public:
virtual ~CCacheItem() {}
public:
virtual CCacheItem& operator=(const CCacheItem&) = 0;
// The "==" operator SHOULD only compare key values.
virtual bool operator==(const CCacheItem&) = 0;
// Functionality:
// get a deep copy clone of the current item
// Parameters:
// None.
// Returned value:
// Pointer to the new item, or NULL if failed.
virtual CCacheItem* clone() = 0;
// Functionality:
// get a random key value between 0 and MAX_INT to be used for the hash in cache
// Parameters:
// None.
// Returned value:
// A random hash key.
virtual int getKey() = 0;
// If there is any shared resources between the cache item and its clone,
// the shared resource should be released by this function.
virtual void release() {}
};
template<typename T> class CCache
{
public:
CCache(const int& size = 1024):
m_iMaxSize(size),
m_iHashSize(size * 3),
m_iCurrSize(0)
{
m_vHashPtr.resize(m_iHashSize);
CGuard::createMutex(m_Lock);
}
~CCache()
{
clear();
CGuard::releaseMutex(m_Lock);
}
public:
// Functionality:
// find the matching item in the cache.
// Parameters:
// 0) [in/out] data: storage for the retrieved item; initially it must carry the key information
// Returned value:
// 0 if found a match, otherwise -1.
int lookup(T* data)
{
CGuard cacheguard(m_Lock);
int key = data->getKey();
if (key < 0)
return -1;
if (key >= m_iMaxSize)
key %= m_iHashSize;
const ItemPtrList& item_list = m_vHashPtr[key];
for (typename ItemPtrList::const_iterator i = item_list.begin(); i != item_list.end(); ++ i)
{
if (*data == ***i)
{
// copy the cached info
*data = ***i;
return 0;
}
}
return -1;
}
// Functionality:
// update an item in the cache, or insert one if it doesn't exist; oldest item may be removed
// Parameters:
// 0) [in] data: the new item to updated/inserted to the cache
// Returned value:
// 0 if success, otherwise -1.
int update(T* data)
{
CGuard cacheguard(m_Lock);
int key = data->getKey();
if (key < 0)
return -1;
if (key >= m_iMaxSize)
key %= m_iHashSize;
T* curr = NULL;
ItemPtrList& item_list = m_vHashPtr[key];
for (typename ItemPtrList::iterator i = item_list.begin(); i != item_list.end(); ++ i)
{
if (*data == ***i)
{
// update the existing entry with the new value
***i = *data;
curr = **i;
// remove the current entry
m_StorageList.erase(*i);
item_list.erase(i);
// re-insert to the front
m_StorageList.push_front(curr);
item_list.push_front(m_StorageList.begin());
return 0;
}
}
// create new entry and insert to front
curr = data->clone();
m_StorageList.push_front(curr);
item_list.push_front(m_StorageList.begin());
++ m_iCurrSize;
if (m_iCurrSize >= m_iMaxSize)
{
// Cache overflow, remove oldest entry.
T* last_data = m_StorageList.back();
int last_key = last_data->getKey() % m_iHashSize;
item_list = m_vHashPtr[last_key];
for (typename ItemPtrList::iterator i = item_list.begin(); i != item_list.end(); ++ i)
{
if (*last_data == ***i)
{
item_list.erase(i);
break;
}
}
last_data->release();
delete last_data;
m_StorageList.pop_back();
-- m_iCurrSize;
}
return 0;
}
// Functionality:
// Specify the cache size (i.e., max number of items).
// Parameters:
// 0) [in] size: max cache size.
// Returned value:
// None.
void setSizeLimit(const int& size)
{
m_iMaxSize = size;
m_iHashSize = size * 3;
m_vHashPtr.resize(m_iHashSize);
}
// Functionality:
// Clear all entries in the cache, restore to initialization state.
// Parameters:
// None.
// Returned value:
// None.
void clear()
{
for (typename std::list<T*>::iterator i = m_StorageList.begin(); i != m_StorageList.end(); ++ i)
{
(*i)->release();
delete *i;
}
m_StorageList.clear();
for (typename std::vector<ItemPtrList>::iterator i = m_vHashPtr.begin(); i != m_vHashPtr.end(); ++ i)
i->clear();
m_iCurrSize = 0;
}
private:
std::list<T*> m_StorageList;
typedef typename std::list<T*>::iterator ItemPtr;
typedef std::list<ItemPtr> ItemPtrList;
std::vector<ItemPtrList> m_vHashPtr;
int m_iMaxSize;
int m_iHashSize;
int m_iCurrSize;
pthread_mutex_t m_Lock;
private:
CCache(const CCache&);
CCache& operator=(const CCache&);
};
class CInfoBlock
{
public:
uint32_t m_piIP[4]; // IP address, machine read only, not human readable format
int m_iIPversion; // IP version
uint64_t m_ullTimeStamp; // last update time
int m_iRTT; // RTT
int m_iBandwidth; // estimated bandwidth
int m_iLossRate; // average loss rate
int m_iReorderDistance; // packet reordering distance
double m_dInterval; // inter-packet time, congestion control
double m_dCWnd; // congestion window size, congestion control
public:
virtual ~CInfoBlock() {}
virtual CInfoBlock& operator=(const CInfoBlock& obj);
virtual bool operator==(const CInfoBlock& obj);
virtual CInfoBlock* clone();
virtual int getKey();
virtual void release() {}
public:
// Functionality:
// convert sockaddr structure to an integer array
// Parameters:
// 0) [in] addr: network address
// 1) [in] ver: IP version
// 2) [out] ip: the result machine readable IP address in integer array
// Returned value:
// None.
static void convert(const sockaddr* addr, const int& ver, uint32_t ip[]);
};
#endif
| 8,297 | 27.22449 | 107 | h |
null | SymbolicPCC-main/src/core/channel.h | /*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 01/27/2011
*****************************************************************************/
#ifndef __UDT_CHANNEL_H__
#define __UDT_CHANNEL_H__
#include "udt.h"
#include "packet.h"
class CChannel
{
public:
CChannel();
CChannel(const int& version);
~CChannel();
// Functionality:
// Opne a UDP channel.
// Parameters:
// 0) [in] addr: The local address that UDP will use.
// Returned value:
// None.
void open(const sockaddr* addr = NULL);
// Functionality:
// Opne a UDP channel based on an existing UDP socket.
// Parameters:
// 0) [in] udpsock: UDP socket descriptor.
// Returned value:
// None.
void open(UDPSOCKET udpsock);
// Functionality:
// Disconnect and close the UDP entity.
// Parameters:
// None.
// Returned value:
// None.
void close() const;
// Functionality:
// Get the UDP sending buffer size.
// Parameters:
// None.
// Returned value:
// Current UDP sending buffer size.
int getSndBufSize();
// Functionality:
// Get the UDP receiving buffer size.
// Parameters:
// None.
// Returned value:
// Current UDP receiving buffer size.
int getRcvBufSize();
// Functionality:
// Set the UDP sending buffer size.
// Parameters:
// 0) [in] size: expected UDP sending buffer size.
// Returned value:
// None.
void setSndBufSize(const int& size);
// Functionality:
// Set the UDP receiving buffer size.
// Parameters:
// 0) [in] size: expected UDP receiving buffer size.
// Returned value:
// None.
void setRcvBufSize(const int& size);
// Functionality:
// Query the socket address that the channel is using.
// Parameters:
// 0) [out] addr: pointer to store the returned socket address.
// Returned value:
// None.
void getSockAddr(sockaddr* addr) const;
// Functionality:
// Query the peer side socket address that the channel is connect to.
// Parameters:
// 0) [out] addr: pointer to store the returned socket address.
// Returned value:
// None.
void getPeerAddr(sockaddr* addr) const;
// Functionality:
// Send a packet to the given address.
// Parameters:
// 0) [in] addr: pointer to the destination address.
// 1) [in] packet: reference to a CPacket entity.
// Returned value:
// Actual size of data sent.
int sendto(const sockaddr* addr, CPacket& packet) const;
// Functionality:
// Receive a packet from the channel and record the source address.
// Parameters:
// 0) [in] addr: pointer to the source address.
// 1) [in] packet: reference to a CPacket entity.
// Returned value:
// Actual size of data received.
int recvfrom(sockaddr* addr, CPacket& packet) const;
private:
void setUDPSockOpt();
private:
int m_iIPversion; // IP version
int m_iSockAddrSize; // socket address structure size (pre-defined to avoid run-time test)
UDPSOCKET m_iSocket; // socket descriptor
int m_iSndBufSize; // UDP sending buffer size
int m_iRcvBufSize; // UDP receiving buffer size
};
#endif
| 5,308 | 29.866279 | 109 | h |
null | SymbolicPCC-main/src/core/common.h | /*****************************************************************************
Copyright (c) 2001 - 2009, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 08/01/2009
*****************************************************************************/
#ifndef __UDT_COMMON_H__
#define __UDT_COMMON_H__
#ifndef WIN32
#include <sys/time.h>
#include <sys/uio.h>
#include <pthread.h>
#else
#include <windows.h>
#endif
#include <cstdlib>
#include "udt.h"
#ifdef WIN32
// Windows compability
typedef HANDLE pthread_t;
typedef HANDLE pthread_mutex_t;
typedef HANDLE pthread_cond_t;
typedef DWORD pthread_key_t;
#endif
////////////////////////////////////////////////////////////////////////////////
class CTimer
{
public:
CTimer();
~CTimer();
public:
// Functionality:
// Sleep for "interval" CCs.
// Parameters:
// 0) [in] interval: CCs to sleep.
// Returned value:
// None.
void sleep(const uint64_t& interval);
// Functionality:
// Seelp until CC "nexttime".
// Parameters:
// 0) [in] nexttime: next time the caller is waken up.
// Returned value:
// None.
void sleepto(const uint64_t& nexttime);
// Functionality:
// Stop the sleep() or sleepto() methods.
// Parameters:
// None.
// Returned value:
// None.
void interrupt();
// Functionality:
// trigger the clock for a tick, for better granuality in no_busy_waiting timer.
// Parameters:
// None.
// Returned value:
// None.
void tick();
public:
// Functionality:
// Read the CPU clock cycle into x.
// Parameters:
// 0) [out] x: to record cpu clock cycles.
// Returned value:
// None.
static void rdtsc(uint64_t &x);
// Functionality:
// return the CPU frequency.
// Parameters:
// None.
// Returned value:
// CPU frequency.
static uint64_t getCPUFrequency();
// Functionality:
// check the current time, 64bit, in microseconds.
// Parameters:
// None.
// Returned value:
// current time in microseconds.
static uint64_t getTime();
// Functionality:
// trigger an event such as new connection, close, new data, etc. for "select" call.
// Parameters:
// None.
// Returned value:
// None.
static void triggerEvent();
// Functionality:
// wait for an event to br triggered by "triggerEvent".
// Parameters:
// None.
// Returned value:
// None.
static void waitForEvent();
// Functionality:
// sleep for a short interval. exact sleep time does not matter
// Parameters:
// None.
// Returned value:
// None.
static void sleep();
private:
uint64_t m_ullSchedTime; // next schedulled time
pthread_cond_t m_TickCond;
pthread_mutex_t m_TickLock;
static pthread_cond_t m_EventCond;
static pthread_mutex_t m_EventLock;
private:
static uint64_t s_ullCPUFrequency; // CPU frequency : clock cycles per microsecond
static uint64_t readCPUFrequency();
};
////////////////////////////////////////////////////////////////////////////////
class CGuard
{
public:
CGuard(pthread_mutex_t& lock);
~CGuard();
public:
static void enterCS(pthread_mutex_t& lock);
static void leaveCS(pthread_mutex_t& lock);
static void createMutex(pthread_mutex_t& lock);
static void releaseMutex(pthread_mutex_t& lock);
static void createCond(pthread_cond_t& cond);
static void releaseCond(pthread_cond_t& cond);
private:
pthread_mutex_t& m_Mutex; // Alias name of the mutex to be protected
int m_iLocked; // Locking status
CGuard& operator=(const CGuard&);
};
////////////////////////////////////////////////////////////////////////////////
// UDT Sequence Number 0 - (2^31 - 1)
// seqcmp: compare two seq#, considering the wraping
// seqlen: length from the 1st to the 2nd seq#, including both
// seqoff: offset from the 2nd to the 1st seq#
// incseq: increase the seq# by 1
// decseq: decrease the seq# by 1
// incseq: increase the seq# by a given offset
class CSeqNo
{
public:
inline static int seqcmp(const int32_t& seq1, const int32_t& seq2)
{return (abs(seq1 - seq2) < m_iSeqNoTH) ? (seq1 - seq2) : (seq2 - seq1);}
inline static int seqlen(const int32_t& seq1, const int32_t& seq2)
{return (seq1 <= seq2) ? (seq2 - seq1 + 1) : (seq2 - seq1 + m_iMaxSeqNo + 2);}
inline static int seqoff(const int32_t& seq1, const int32_t& seq2)
{
if (abs(seq1 - seq2) < m_iSeqNoTH)
return seq2 - seq1;
if (seq1 < seq2)
return seq2 - seq1 - m_iMaxSeqNo - 1;
return seq2 - seq1 + m_iMaxSeqNo + 1;
}
inline static int32_t incseq(const int32_t seq)
{return (seq == m_iMaxSeqNo) ? 0 : seq + 1;}
inline static int32_t decseq(const int32_t& seq)
{return (seq == 0) ? m_iMaxSeqNo : seq - 1;}
inline static int32_t incseq(const int32_t& seq, const int32_t& inc)
{return (m_iMaxSeqNo - seq >= inc) ? seq + inc : seq - m_iMaxSeqNo + inc - 1;}
public:
static const int32_t m_iSeqNoTH; // threshold for comparing seq. no.
static const int32_t m_iMaxSeqNo; // maximum sequence number used in UDT
};
////////////////////////////////////////////////////////////////////////////////
// UDT ACK Sub-sequence Number: 0 - (2^31 - 1)
class CAckNo
{
public:
inline static int32_t incack(const int32_t& ackno)
{return (ackno == m_iMaxAckSeqNo) ? 0 : ackno + 1;}
public:
static const int32_t m_iMaxAckSeqNo; // maximum ACK sub-sequence number used in UDT
};
////////////////////////////////////////////////////////////////////////////////
// UDT Message Number: 0 - (2^29 - 1)
class CMsgNo
{
public:
inline static int msgcmp(const int32_t& msgno1, const int32_t& msgno2)
{return (abs(msgno1 - msgno2) < m_iMsgNoTH) ? (msgno1 - msgno2) : (msgno2 - msgno1);}
inline static int msglen(const int32_t& msgno1, const int32_t& msgno2)
{return (msgno1 <= msgno2) ? (msgno2 - msgno1 + 1) : (msgno2 - msgno1 + m_iMaxMsgNo + 2);}
inline static int msgoff(const int32_t& msgno1, const int32_t& msgno2)
{
if (abs(msgno1 - msgno2) < m_iMsgNoTH)
return msgno2 - msgno1;
if (msgno1 < msgno2)
return msgno2 - msgno1 - m_iMaxMsgNo - 1;
return msgno2 - msgno1 + m_iMaxMsgNo + 1;
}
inline static int32_t incmsg(const int32_t& msgno)
{return (msgno == m_iMaxMsgNo) ? 0 : msgno + 1;}
public:
static const int32_t m_iMsgNoTH; // threshold for comparing msg. no.
static const int32_t m_iMaxMsgNo; // maximum message number used in UDT
};
////////////////////////////////////////////////////////////////////////////////
struct CIPAddress
{
static bool ipcmp(const sockaddr* addr1, const sockaddr* addr2, const int& ver = AF_INET);
static void ntop(const sockaddr* addr, uint32_t ip[4], const int& ver = AF_INET);
static void pton(sockaddr* addr, const uint32_t ip[4], const int& ver = AF_INET);
};
////////////////////////////////////////////////////////////////////////////////
struct CMD5
{
static void compute(const char* input, unsigned char result[16]);
};
#endif
| 9,092 | 27.684543 | 94 | h |
null | SymbolicPCC-main/src/core/list.h | /*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 01/22/2011
*****************************************************************************/
#ifndef __UDT_LIST_H__
#define __UDT_LIST_H__
#include "udt.h"
#include "common.h"
#include <iostream>
using namespace std;
class CSndLossList
{
public:
CSndLossList(const int& size = 500000);
~CSndLossList();
// Functionality:
// Insert a seq. no. into the sender loss list.
// Parameters:
// 0) [in] seqno1: sequence number starts.
// 1) [in] seqno2: sequence number ends.
// Returned value:
// number of packets that are not in the list previously.
int insert(const int32_t& seqno1, const int32_t& seqno2);
// Functionality:
// Remove ALL the seq. no. that are not greater than the parameter.
// Parameters:
// 0) [in] seqno: sequence number.
// Returned value:
// None.
void remove(const int32_t& seqno);
// Functionality:
// Read the loss length.
// Parameters:
// None.
// Returned value:
// The length of the list.
int getLossLength();
// Functionality:
// Read the first (smallest) loss seq. no. in the list and remove it.
// Parameters:
// None.
// Returned value:
// The seq. no. or -1 if the list is empty.
int32_t getLostSeq();
public:
int32_t* m_piData1; // sequence number starts
int32_t* m_piData2; // seqnence number ends
int* m_piNext; // next node in the list
int m_iHead; // first node
int m_iLength; // loss length
int m_iSize; // size of the static array
int m_iLastInsertPos; // position of last insert node
pthread_mutex_t m_ListLock; // used to synchronize list operation
private:
CSndLossList(const CSndLossList&);
CSndLossList& operator=(const CSndLossList&);
};
////////////////////////////////////////////////////////////////////////////////
class CRcvLossList
{
public:
CRcvLossList(const int& size = 500000);
~CRcvLossList();
// Functionality:
// Insert a series of loss seq. no. between "seqno1" and "seqno2" into the receiver's loss list.
// Parameters:
// 0) [in] seqno1: sequence number starts.
// 1) [in] seqno2: seqeunce number ends.
// Returned value:
// None.
void insert(const int32_t& seqno1, const int32_t& seqno2);
// Functionality:
// Remove a loss seq. no. from the receiver's loss list.
// Parameters:
// 0) [in] seqno: sequence number.
// Returned value:
// if the packet is removed (true) or no such lost packet is found (false).
int remove(const int32_t& seqno);
// Functionality:
// Remove all packets between seqno1 and seqno2.
// Parameters:
// 0) [in] seqno1: start sequence number.
// 1) [in] seqno2: end sequence number.
// Returned value:
// if the packet is removed (true) or no such lost packet is found (false).
int remove(const int32_t& seqno1, const int32_t& seqno2);
// Functionality:
// Find if there is any lost packets whose sequence number falling seqno1 and seqno2.
// Parameters:
// 0) [in] seqno1: start sequence number.
// 1) [in] seqno2: end sequence number.
// Returned value:
// True if found; otherwise false.
bool find(const int32_t& seqno1, const int32_t& seqno2) const;
// Functionality:
// Read the loss length.
// Parameters:
// None.
// Returned value:
// the length of the list.
int getLossLength() const;
// Functionality:
// Read the first (smallest) seq. no. in the list.
// Parameters:
// None.
// Returned value:
// the sequence number or -1 if the list is empty.
int getFirstLostSeq() const;
// Functionality:
// Get a encoded loss array for NAK report.
// Parameters:
// 0) [out] array: the result list of seq. no. to be included in NAK.
// 1) [out] physical length of the result array.
// 2) [in] limit: maximum length of the array.
// Returned value:
// None.
void getLossArray(int32_t* array, int& len, int limit, int & offset);
public:
int32_t* m_piData1; // sequence number starts
int32_t* m_piData2; // sequence number ends
int* m_piNext; // next node in the list
int* m_piPrior; // prior node in the list;
int m_iHead; // first node in the list
int m_iTail; // last node in the list;
int m_iLength; // loss length
int m_iSize; // size of the static array
private:
CRcvLossList(const CRcvLossList&);
CRcvLossList& operator=(const CRcvLossList&);
};
#endif
| 6,876 | 32.876847 | 105 | h |
null | SymbolicPCC-main/src/core/md5.h | /*
Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
[email protected]
*/
/* $Id: md5.h,v 1.2 2007/12/24 05:58:37 lilyco Exp $ */
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.h is L. Peter Deutsch
<[email protected]>. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Removed support for non-ANSI compilers; removed
references to Ghostscript; clarified derivation from RFC 1321;
now handles byte order either statically or dynamically.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
added conditionalization for C++ compilation from Martin
Purschke <[email protected]>.
1999-05-03 lpd Original version.
*/
#ifndef md5_INCLUDED
# define md5_INCLUDED
/*
* This package supports both compile-time and run-time determination of CPU
* byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be
* compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is
* defined as non-zero, the code will be compiled to run only on big-endian
* CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to
* run on either big- or little-endian CPUs, but will run slightly less
* efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined.
*/
typedef unsigned char md5_byte_t; /* 8-bit byte */
typedef unsigned int md5_word_t; /* 32-bit word */
/* Define the state of the MD5 Algorithm. */
typedef struct md5_state_s {
md5_word_t count[2]; /* message length in bits, lsw first */
md5_word_t abcd[4]; /* digest buffer */
md5_byte_t buf[64]; /* accumulate block */
} md5_state_t;
#ifdef __cplusplus
extern "C"
{
#endif
/* Initialize the algorithm. */
void md5_init(md5_state_t *pms);
/* Append a string to the message. */
void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes);
/* Finish the message and return the digest. */
void md5_finish(md5_state_t *pms, md5_byte_t digest[16]);
#ifdef __cplusplus
} /* end extern "C" */
#endif
#endif /* md5_INCLUDED */
| 3,395 | 35.913043 | 76 | h |
null | SymbolicPCC-main/src/core/options.h |
/*
* See fleece/COPYRIGHT for copyright information.
*
* This file is a part of Fleece.
*
* Fleece is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3.0 of the License, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, see www.gnu.org/licenses
*/
#ifndef _OPTIONS_H_
#define _OPTIONS_H_
#include <assert.h>
#include <iostream>
#include <string.h>
namespace Options {
/**
* Make global copies of argc and argv for use
* by get().
*/
void Parse(int argc, char** argv);
/**
* Get the argument that starts with str. Returns
* the argument on success, NULL on failure.
*/
const char* Get(const char* str);
/**
* Deallocates memory allocated by parse().
*/
void Destroy();
extern int argc;
extern char** argv;
}
#endif
| 1,300 | 24.509804 | 80 | h |
null | SymbolicPCC-main/src/core/queue.h | /*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 01/12/2011
*****************************************************************************/
#ifndef __UDT_QUEUE_H__
#define __UDT_QUEUE_H__
#include "channel.h"
#include "common.h"
#include "packet.h"
#include <list>
#include <map>
#include <queue>
#include <vector>
class CUDT;
struct CUnit
{
CPacket m_Packet; // packet
int m_iFlag; // 0: free, 1: occupied, 2: msg read but not freed (out-of-order), 3: msg dropped
};
class CUnitQueue
{
friend class CRcvQueue;
friend class CRcvBuffer;
public:
CUnitQueue();
~CUnitQueue();
public:
// Functionality:
// Initialize the unit queue.
// Parameters:
// 1) [in] size: queue size
// 2) [in] mss: maximum segament size
// 3) [in] version: IP version
// Returned value:
// 0: success, -1: failure.
int init(const int& size, const int& mss, const int& version);
// Functionality:
// Increase (double) the unit queue size.
// Parameters:
// None.
// Returned value:
// 0: success, -1: failure.
int increase();
// Functionality:
// Decrease (halve) the unit queue size.
// Parameters:
// None.
// Returned value:
// 0: success, -1: failure.
int shrink();
// Functionality:
// find an available unit for incoming packet.
// Parameters:
// None.
// Returned value:
// Pointer to the available unit, NULL if not found.
CUnit* getNextAvailUnit();
private:
struct CQEntry
{
CUnit* m_pUnit; // unit queue
char* m_pBuffer; // data buffer
int m_iSize; // size of each queue
CQEntry* m_pNext;
}
*m_pQEntry, // pointer to the first unit queue
*m_pCurrQueue, // pointer to the current available queue
*m_pLastQueue; // pointer to the last unit queue
CUnit* m_pAvailUnit; // recent available unit
int m_iSize; // total size of the unit queue, in number of packets
int m_iCount; // total number of valid packets in the queue
int m_iMSS; // unit buffer size
int m_iIPversion; // IP version
private:
CUnitQueue(const CUnitQueue&);
CUnitQueue& operator=(const CUnitQueue&);
};
struct CSNode
{
CUDT* m_pUDT; // Pointer to the instance of CUDT socket
uint64_t m_llTimeStamp; // Time Stamp
int m_iHeapLoc; // location on the heap, -1 means not on the heap
};
class CSndUList
{
friend class CSndQueue;
public:
CSndUList();
~CSndUList();
public:
// Functionality:
// Insert a new UDT instance into the list.
// Parameters:
// 1) [in] ts: time stamp: next processing time
// 2) [in] u: pointer to the UDT instance
// Returned value:
// None.
void insert(const int64_t& ts, const CUDT* u);
// Functionality:
// Update the timestamp of the UDT instance on the list.
// Parameters:
// 1) [in] u: pointer to the UDT instance
// 2) [in] resechedule: if the timestampe shoudl be rescheduled
// Returned value:
// None.
void update(const CUDT* u, const bool& reschedule = true);
// Functionality:
// Retrieve the next packet and peer address from the first entry, and reschedule it in the queue.
// Parameters:
// 0) [out] addr: destination address of the next packet
// 1) [out] pkt: the next packet to be sent
// Returned value:
// 1 if successfully retrieved, -1 if no packet found.
int pop(sockaddr*& addr, CPacket& pkt);
// Functionality:
// Remove UDT instance from the list.
// Parameters:
// 1) [in] u: pointer to the UDT instance
// Returned value:
// None.
void remove(const CUDT* u);
// Functionality:
// Retrieve the next scheduled processing time.
// Parameters:
// None.
// Returned value:
// Scheduled processing time of the first UDT socket in the list.
uint64_t getNextProcTime();
private:
void insert_(const int64_t& ts, const CUDT* u);
void remove_(const CUDT* u);
private:
CSNode** m_pHeap; // The heap array
int m_iArrayLength; // physical length of the array
int m_iLastEntry; // position of last entry on the heap array
pthread_mutex_t m_ListLock;
pthread_mutex_t* m_pWindowLock;
pthread_cond_t* m_pWindowCond;
CTimer* m_pTimer;
private:
CSndUList(const CSndUList&);
CSndUList& operator=(const CSndUList&);
};
struct CRNode
{
CUDT* m_pUDT; // Pointer to the instance of CUDT socket
uint64_t m_llTimeStamp; // Time Stamp
CRNode* m_pPrev; // previous link
CRNode* m_pNext; // next link
bool m_bOnList; // if the node is already on the list
};
class CRcvUList
{
public:
CRcvUList();
~CRcvUList();
public:
// Functionality:
// Insert a new UDT instance to the list.
// Parameters:
// 1) [in] u: pointer to the UDT instance
// Returned value:
// None.
void insert(const CUDT* u);
// Functionality:
// Remove the UDT instance from the list.
// Parameters:
// 1) [in] u: pointer to the UDT instance
// Returned value:
// None.
void remove(const CUDT* u);
// Functionality:
// Move the UDT instance to the end of the list, if it already exists; otherwise, do nothing.
// Parameters:
// 1) [in] u: pointer to the UDT instance
// Returned value:
// None.
void update(const CUDT* u);
public:
CRNode* m_pUList; // the head node
private:
CRNode* m_pLast; // the last node
private:
CRcvUList(const CRcvUList&);
CRcvUList& operator=(const CRcvUList&);
};
class CHash
{
public:
CHash();
~CHash();
public:
// Functionality:
// Initialize the hash table.
// Parameters:
// 1) [in] size: hash table size
// Returned value:
// None.
void init(const int& size);
// Functionality:
// Look for a UDT instance from the hash table.
// Parameters:
// 1) [in] id: socket ID
// Returned value:
// Pointer to a UDT instance, or NULL if not found.
CUDT* lookup(const int32_t& id);
// Functionality:
// Insert an entry to the hash table.
// Parameters:
// 1) [in] id: socket ID
// 2) [in] u: pointer to the UDT instance
// Returned value:
// None.
void insert(const int32_t& id, const CUDT* u);
// Functionality:
// Remove an entry from the hash table.
// Parameters:
// 1) [in] id: socket ID
// Returned value:
// None.
void remove(const int32_t& id);
private:
struct CBucket
{
int32_t m_iID; // Socket ID
CUDT* m_pUDT; // Socket instance
CBucket* m_pNext; // next bucket
} **m_pBucket; // list of buckets (the hash table)
int m_iHashSize; // size of hash table
private:
CHash(const CHash&);
CHash& operator=(const CHash&);
};
class CRendezvousQueue
{
public:
CRendezvousQueue();
~CRendezvousQueue();
public:
void insert(const UDTSOCKET& id, CUDT* u, const int& ipv, const sockaddr* addr, const uint64_t& ttl);
void remove(const UDTSOCKET& id);
CUDT* retrieve(const sockaddr* addr, UDTSOCKET& id);
void updateConnStatus();
private:
struct CRL
{
UDTSOCKET m_iID; // UDT socket ID (self)
CUDT* m_pUDT; // UDT instance
int m_iIPversion; // IP version
sockaddr* m_pPeerAddr; // UDT sonnection peer address
uint64_t m_ullTTL; // the time that this request expires
};
std::list<CRL> m_lRendezvousID; // The sockets currently in rendezvous mode
pthread_mutex_t m_RIDVectorLock;
};
class CSndQueue
{
friend class CUDT;
friend class CUDTUnited;
public:
CSndQueue();
~CSndQueue();
public:
// Functionality:
// Initialize the sending queue.
// Parameters:
// 1) [in] c: UDP channel to be associated to the queue
// 2) [in] t: Timer
// Returned value:
// None.
void init(const CChannel* c, const CTimer* t);
// Functionality:
// Send out a packet to a given address.
// Parameters:
// 1) [in] addr: destination address
// 2) [in] packet: packet to be sent out
// Returned value:
// Size of data sent out.
int sendto(const sockaddr* addr, CPacket& packet);
private:
#ifndef WIN32
static void* worker(void* param);
#else
static DWORD WINAPI worker(LPVOID param);
#endif
pthread_t m_WorkerThread;
private:
CSndUList* m_pSndUList; // List of UDT instances for data sending
CChannel* m_pChannel; // The UDP channel for data sending
CTimer* m_pTimer; // Timing facility
pthread_mutex_t m_WindowLock;
pthread_cond_t m_WindowCond;
volatile bool m_bClosing; // closing the worker
pthread_cond_t m_ExitCond;
private:
CSndQueue(const CSndQueue&);
CSndQueue& operator=(const CSndQueue&);
};
class CRcvQueue
{
friend class CUDT;
friend class CUDTUnited;
public:
CRcvQueue();
~CRcvQueue();
public:
// Functionality:
// Initialize the receiving queue.
// Parameters:
// 1) [in] size: queue size
// 2) [in] mss: maximum packet size
// 3) [in] version: IP version
// 4) [in] hsize: hash table size
// 5) [in] c: UDP channel to be associated to the queue
// 6) [in] t: timer
// Returned value:
// None.
void init(const int& size, const int& payload, const int& version, const int& hsize, const CChannel* c, const CTimer* t);
// Functionality:
// Read a packet for a specific UDT socket id.
// Parameters:
// 1) [in] id: Socket ID
// 2) [out] packet: received packet
// Returned value:
// Data size of the packet
int recvfrom(const int32_t& id, CPacket& packet);
private:
#ifndef WIN32
static void* worker(void* param);
#else
static DWORD WINAPI worker(LPVOID param);
#endif
pthread_t m_WorkerThread;
private:
CUnitQueue m_UnitQueue; // The received packet queue
CRcvUList* m_pRcvUList; // List of UDT instances that will read packets from the queue
CHash* m_pHash; // Hash table for UDT socket looking up
CChannel* m_pChannel; // UDP channel for receving packets
CTimer* m_pTimer; // shared timer with the snd queue
int m_iPayloadSize; // packet payload size
volatile bool m_bClosing; // closing the workder
pthread_cond_t m_ExitCond;
private:
int setListener(const CUDT* u);
void removeListener(const CUDT* u);
void registerConnector(const UDTSOCKET& id, CUDT* u, const int& ipv, const sockaddr* addr, const uint64_t& ttl);
void removeConnector(const UDTSOCKET& id);
void setNewEntry(CUDT* u);
bool ifNewEntry();
CUDT* getNewEntry();
void storePkt(const int32_t& id, CPacket* pkt);
private:
pthread_mutex_t m_LSLock;
volatile CUDT* m_pListener; // pointer to the (unique, if any) listening UDT entity
CRendezvousQueue* m_pRendezvousQueue; // The list of sockets in rendezvous mode
std::vector<CUDT*> m_vNewEntry; // newly added entries, to be inserted
pthread_mutex_t m_IDLock;
std::map<int32_t, std::queue<CPacket*> > m_mBuffer; // temporary buffer for rendezvous connection request
pthread_mutex_t m_PassLock;
pthread_cond_t m_PassCond;
private:
CRcvQueue(const CRcvQueue&);
CRcvQueue& operator=(const CRcvQueue&);
};
struct CMultiplexer
{
CSndQueue* m_pSndQueue; // The sending queue
CRcvQueue* m_pRcvQueue; // The receiving queue
CChannel* m_pChannel; // The UDP channel for sending and receiving
CTimer* m_pTimer; // The timer
int m_iPort; // The UDP port number of this multiplexer
int m_iIPversion; // IP version
int m_iMSS; // Maximum Segment Size
int m_iRefCount; // number of UDT instances that are associated with this multiplexer
bool m_bReusable; // if this one can be shared with others
int m_iID; // multiplexer ID
};
#endif
| 14,117 | 25.738636 | 124 | h |
null | SymbolicPCC-main/src/core/window.h | /*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 01/22/2011
*****************************************************************************/
#ifndef __UDT_WINDOW_H__
#define __UDT_WINDOW_H__
#ifndef WIN32
#include <sys/time.h>
#include <time.h>
#endif
#include "udt.h"
class CACKWindow
{
public:
CACKWindow(const int& size = 1024);
~CACKWindow();
// Functionality:
// Write an ACK record into the window.
// Parameters:
// 0) [in] seq: ACK seq. no.
// 1) [in] ack: DATA ACK no.
// Returned value:
// None.
void store(const int32_t& seq, const int32_t& ack);
// Functionality:
// Search the ACK-2 "seq" in the window, find out the DATA "ack" and caluclate RTT .
// Parameters:
// 0) [in] seq: ACK-2 seq. no.
// 1) [out] ack: the DATA ACK no. that matches the ACK-2 no.
// Returned value:
// RTT.
int acknowledge(const int32_t& seq, int32_t& ack);
private:
int32_t* m_piACKSeqNo; // Seq. No. for the ACK packet
int32_t* m_piACK; // Data Seq. No. carried by the ACK packet
uint64_t* m_pTimeStamp; // The timestamp when the ACK was sent
int m_iSize; // Size of the ACK history window
int m_iHead; // Pointer to the lastest ACK record
int m_iTail; // Pointer to the oldest ACK record
private:
CACKWindow(const CACKWindow&);
CACKWindow& operator=(const CACKWindow&);
};
////////////////////////////////////////////////////////////////////////////////
class CPktTimeWindow
{
public:
CPktTimeWindow(const int& asize = 16, const int& psize = 16);
~CPktTimeWindow();
// Functionality:
// read the minimum packet sending interval.
// Parameters:
// None.
// Returned value:
// minimum packet sending interval (microseconds).
int getMinPktSndInt() const;
// Functionality:
// Calculate the packes arrival speed.
// Parameters:
// None.
// Returned value:
// Packet arrival speed (packets per second).
int getPktRcvSpeed() const;
// Functionality:
// Estimate the bandwidth.
// Parameters:
// None.
// Returned value:
// Estimated bandwidth (packets per second).
int getBandwidth() const;
// Functionality:
// Record time information of a packet sending.
// Parameters:
// 0) currtime: timestamp of the packet sending.
// Returned value:
// None.
void onPktSent(const int& currtime);
// Functionality:
// Record time information of an arrived packet.
// Parameters:
// None.
// Returned value:
// None.
void onPktArrival();
// Functionality:
// Record the arrival time of the first probing packet.
// Parameters:
// None.
// Returned value:
// None.
void probe1Arrival();
// Functionality:
// Record the arrival time of the second probing packet and the interval between packet pairs.
// Parameters:
// None.
// Returned value:
// None.
void probe2Arrival();
private:
int m_iAWSize; // size of the packet arrival history window
int* m_piPktWindow; // packet information window
int* m_piPktReplica;
int m_iPktWindowPtr; // position pointer of the packet info. window.
int m_iPWSize; // size of probe history window size
int* m_piProbeWindow; // record inter-packet time for probing packet pairs
int* m_piProbeReplica;
int m_iProbeWindowPtr; // position pointer to the probing window
int m_iLastSentTime; // last packet sending time
int m_iMinPktSndInt; // Minimum packet sending interval
uint64_t m_LastArrTime; // last packet arrival time
uint64_t m_CurrArrTime; // current packet arrival time
uint64_t m_ProbeTime; // arrival time of the first probing packet
private:
CPktTimeWindow(const CPktTimeWindow&);
CPktTimeWindow &operator=(const CPktTimeWindow&);
};
#endif
| 5,962 | 30.718085 | 103 | h |
null | SymbolicPCC-main/src/pcc/pcc_logger.h | // PCC (Performance Oriented Congestion Control) algorithm
#ifndef NET_QUIC_CORE_CONGESTION_CONTROL_PCC_EVENT_LOGGER_H_
#define NET_QUIC_CORE_CONGESTION_CONTROL_PCC_EVENT_LOGGER_H_
#include <vector>
#include <map>
#include "../core/common.h"
#include "../core/options.h"
#include <iostream>
#include <fstream>
#include <mutex>
#include <sstream>
#define QUIC_EXPORT_PRIVATE
struct PccLoggableEventValue {
std::string value_name;
std::string value;
};
class QUIC_EXPORT_PRIVATE PccLoggableEvent {
public:
PccLoggableEvent(const std::string& event_name, const std::string& flag);
~PccLoggableEvent();
bool IsActive() const { return active; }
template <typename ValueType>
void AddValue(const std::string& flag, const ValueType& value);
std::string name;
std::vector<PccLoggableEventValue> values;
private:
bool active;
static bool CheckFlag(const std::string& flag);
static std::map<std::string, bool> flag_map;
};
class QUIC_EXPORT_PRIVATE PccEventLogger {
public:
PccEventLogger(const std::string& filename);
~PccEventLogger();
void LogEvent(const PccLoggableEvent&);
private:
std::ofstream output_file_;
bool first_line;
uint64_t start_time;
std::mutex log_lock;
};
template <typename ValueType>
void PccLoggableEvent::AddValue(const std::string& flag, const ValueType& value) {
if (!active) {
return;
}
PccLoggableEventValue event_val;
event_val.value_name = flag;
std::ostringstream sstream;
sstream << value;
event_val.value = sstream.str();
values.push_back(event_val);
}
#endif
| 1,573 | 24.387097 | 82 | h |
null | SymbolicPCC-main/src/pcc/pcc_sender.h | // PCC (Performance Oriented Congestion Control) algorithm
#ifndef NET_QUIC_CORE_CONGESTION_CONTROL_PCC_SENDER_H_
#define NET_QUIC_CORE_CONGESTION_CONTROL_PCC_SENDER_H_
#include <vector>
#include <queue>
#include <mutex>
#ifdef QUIC_PORT
#include "base/macros.h"
#ifdef QUIC_PORT_LOCAL
#include "net/quic/core/congestion_control/pcc_monitor_interval_queue.h"
#include "net/quic/core/congestion_control/send_algorithm_interface.h"
#include "net/quic/core/quic_bandwidth.h"
#include "net/quic/core/quic_connection_stats.h"
#include "net/quic/core/quic_time.h"
#include "net/quic/core/quic_types.h"
#else
#include "third_party/pcc_quic/pcc_monitor_interval_queue.h"
#include "gfe/quic/core/congestion_control/send_algorithm_interface.h"
#include "gfe/quic/core/quic_bandwidth.h"
#include "gfe/quic/core/quic_connection_stats.h"
#include "gfe/quic/core/quic_time.h"
#include "gfe/quic/core/quic_types.h"
#endif
#else
#include "../core/options.h"
#include "rate_control/pcc_rc.h"
#include "rate_control/pcc_rc_factory.h"
#include "utility/pcc_ucalc.h"
#include "utility/pcc_ucalc_factory.h"
#include "monitor_interval/pcc_mi_analysis_group.h"
#include "monitor_interval/pcc_mi_queue.h"
#include "pcc_logger.h"
#include <iostream>
#define QUIC_EXPORT_PRIVATE
typedef bool HasRetransmittableData;
#endif
#ifdef QUIC_PORT
#ifdef QUIC_PORT_LOCAL
namespace net {
#else
namespace gfe_quic {
#endif
namespace test {
class PccSenderPeer;
} // namespace test
#endif
// PccSender implements the PCC congestion control algorithm. PccSender
// evaluates the benefits of different sending rates by comparing their
// utilities, and adjusts the sending rate towards the direction of
// higher utility.
class QUIC_EXPORT_PRIVATE PccSender
#ifdef QUIC_PORT
: public SendAlgorithmInterface {
#else
{
#endif
public:
#ifdef QUIC_PORT
PccSender(const RttStats* rtt_stats,
QuicPacketCount initial_congestion_window,
QuicPacketCount max_congestion_window, QuicRandom* random);
#else
PccSender(QuicTime initial_rtt_us,
QuicPacketCount initial_congestion_window,
QuicPacketCount max_congestion_window);
#endif
PccSender(const PccSender&) = delete;
PccSender& operator=(const PccSender&) = delete;
PccSender(PccSender&&) = delete;
PccSender& operator=(PccSender&&) = delete;
#ifdef QUIC_PORT_LOCAL
~PccSender() override;
#else
~PccSender();
#endif
#ifdef QUIC_PORT
// Start implementation of SendAlgorithmInterface.
bool InSlowStart() const override;
bool InRecovery() const override;
bool IsProbingForMoreBandwidth() const override;
void SetFromConfig(const QuicConfig& config,
Perspective perspective) override {}
void AdjustNetworkParameters(QuicBandwidth bandwidth,
QuicTime::Delta rtt) override {}
void SetNumEmulatedConnections(int num_connections) override {}
#endif
void OnCongestionEvent(bool rtt_updated,
QuicByteCount bytes_in_flight,
QuicTime event_time,
#ifndef QUIC_PORT
QuicTime rtt,
#endif
const AckedPacketVector& acked_packets,
#ifdef QUIC_PORT
const LostPacketVector& lost_packets) override;
#else
const LostPacketVector& lost_packets);
#endif
void OnPacketSent(QuicTime sent_time,
QuicByteCount bytes_in_flight,
QuicPacketNumber packet_number,
QuicByteCount bytes,
#ifdef QUIC_PORT
HasRetransmittableData is_retransmittable) override;
void OnRetransmissionTimeout(bool packets_retransmitted) override {}
void OnConnectionMigration() override {}
bool CanSend(QuicByteCount bytes_in_flight) override;
#else
HasRetransmittableData is_retransmittable);
#endif
#ifdef QUIC_PORT
QuicBandwidth PacingRate(QuicByteCount bytes_in_flight) const override;
#else
QuicBandwidth PacingRate(QuicByteCount bytes_in_flight) const;
#endif
#ifdef QUIC_PORT
QuicBandwidth BandwidthEstimate() const override;
QuicByteCount GetCongestionWindow() const override;
QuicByteCount GetSlowStartThreshold() const override;
CongestionControlType GetCongestionControlType() const override;
#if defined(QUIC_PORT) && defined(QUIC_PORT_LOCAL)
std::string GetDebugState() const override;
#else
string GetDebugState() const override;
#endif
void OnApplicationLimited(QuicByteCount bytes_in_flight) override {}
// End implementation of SendAlgorithmInterface.
QuicTime::Delta ComputeMonitorDuration(
QuicBandwidth sending_rate,
QuicTime::Delta rtt);
#else
QuicTime ComputeMonitorDuration(
QuicBandwidth sending_rate,
QuicTime rtt);
#endif
#ifndef QUIC_PORT
PccEventLogger* log;
void Reset();
#endif
QuicTime GetCurrentRttEstimate(QuicTime cur_time);
private:
#ifdef QUIC_PORT
friend class test::PccSenderPeer;
#endif
void UpdateCurrentRttEstimate(QuicTime rtt);
bool ShouldCreateNewMonitorInterval(QuicTime cur_time);
QuicBandwidth UpdateSendingRate(QuicTime cur_time);
// Sending rate in Mbit/s for the next monitor intervals.
QuicBandwidth sending_rate_;
// Queue of monitor intervals with pending utilities.
PccMonitorIntervalQueue interval_queue_;
// Group of previously measured monitor intervals.
PccMonitorIntervalAnalysisGroup interval_analysis_group_;
#ifdef QUIC_PORT
const RttStats* rtt_stats_;
QuicRandom* random_;
#else
QuicTime avg_rtt_;
#endif
PccUtilityCalculator* utility_calculator_;
PccRateController* rate_controller_;
std::mutex* rate_control_lock_;
};
#ifdef QUIC_PORT
} // namespace gfe_quic
#endif
#endif
| 5,773 | 28.762887 | 73 | h |
null | SymbolicPCC-main/src/pcc/monitor_interval/pcc_mi.h | #ifndef THIRD_PARTY_PCC_QUIC_PCC_MONITOR_INTERVAL_H_
#define THIRD_PARTY_PCC_QUIC_PCC_MONITOR_INTERVAL_H_
#include <utility>
#include <vector>
#include <iostream>
#ifdef QUIC_PORT
#ifdef QUIC_PORT_LOCAL
#include "net/quic/core/congestion_control/send_algorithm_interface.h"
#include "net/quic/core/quic_time.h"
#include "net/quic/core/quic_types.h"
#else
#include "gfe/quic/core/congestion_control/send_algorithm_interface.h"
#include "gfe/quic/core/quic_time.h"
#include "gfe/quic/core/quic_types.h"
#endif
#else
#include <cstdint>
#include <cstdlib>
#include <cmath>
#endif
#ifndef QUIC_PORT
typedef int32_t QuicPacketCount;
typedef int32_t QuicPacketNumber;
typedef int64_t QuicByteCount;
typedef int64_t QuicTime;
typedef double QuicBandwidth;
#endif
#ifdef QUIC_PORT
#ifdef QUIC_PORT_LOCAL
namespace net {
namespace {
bool FLAGS_use_utility_version_2 = true;
}
#else
namespace gfe_quic {
DECLARE_bool(use_utility_version_2);
#endif
using namespace net;
#endif
// PacketRttSample, stores the packet number and its corresponding RTT
struct PacketRttSample {
PacketRttSample();
#ifdef QUIC_PORT
PacketRttSample(QuicPacketNumber packet_number, QuicTime::Delta rtt);
#else
PacketRttSample(QuicPacketNumber packet_number, QuicTime rtt);
#endif
~PacketRttSample() {}
// Packet number of the sampled packet.
QuicPacketNumber packet_number;
// RTT corresponding to the sampled packet.
#ifdef QUIC_PORT
QuicTime::Delta rtt;
#else
QuicTime rtt;
#endif
};
// MonitorInterval, as the queue's entry struct, stores the information
// of a PCC monitor interval (MonitorInterval) that can be used to
// - pinpoint a acked/lost packet to the corresponding MonitorInterval,
// - calculate the MonitorInterval's utility value.
struct MonitorInterval {
//friend class MonitorIntervalMetric;
//public:
MonitorInterval(QuicBandwidth sending_rate, QuicTime end_time);
#if defined(QUIC_PORT) && defined(QUIC_PORT_LOCAL)
explicit MonitorInterval(const MonitorInterval&);
#endif
#ifdef QUIC_PORT_LOCAL
~MonitorInterval();
#else
~MonitorInterval() {}
#endif
void OnPacketSent(QuicTime cur_time, QuicPacketNumber packet_num, QuicByteCount packet_size);
void OnPacketAcked(QuicTime cur_time, QuicPacketNumber packet_num, QuicByteCount packet_size, QuicTime rtt);
void OnPacketLost(QuicTime cur_time, QuicPacketNumber packet_num, QuicByteCount packet_size);
bool AllPacketsSent(QuicTime cur_time) const;
bool AllPacketsAccountedFor(QuicTime cur_time);
QuicBandwidth GetTargetSendingRate() const;
QuicTime GetStartTime() const;
void SetUtility(float utility);
QuicBandwidth GetObsThroughput() const;
QuicBandwidth GetObsSendingRate() const;
float GetObsSendDur() const;
float GetObsRecvDur() const;
float GetObsRtt() const;
float GetObsRttInflation() const;
float GetObsLossRate() const;
float GetObsUtility() const;
int GetId() const { return id; }
int GetBytesSent() const { return bytes_sent; }
int GetBytesAcked() const { return bytes_acked; }
int GetBytesLost() const { return bytes_lost; }
uint64_t GetSendStartTime() const { return first_packet_sent_time; }
uint64_t GetSendEndTime() const { return last_packet_sent_time; }
uint64_t GetRecvStartTime() const { return first_packet_ack_time; }
uint64_t GetRecvEndTime() const { return last_packet_ack_time; }
uint64_t GetFirstAckLatency() const;
uint64_t GetLastAckLatency() const;
int GetAveragePacketSize() const { return bytes_sent / n_packets_sent; }
double GetUtility() const { return utility; }
private:
static int next_id;
bool ContainsPacket(QuicPacketNumber packet_num);
int id;
// Sending rate.
QuicBandwidth target_sending_rate;
// The end time for this monitor interval in microseconds.
QuicTime end_time;
// Sent time of the first packet.
QuicTime first_packet_sent_time;
// Sent time of the last packet.
QuicTime last_packet_sent_time;
// Sent time of the first packet.
QuicTime first_packet_ack_time;
// Sent time of the last packet.
QuicTime last_packet_ack_time;
// PacketNumber of the first sent packet.
QuicPacketNumber first_packet_number;
// PacketNumber of the last sent packet.
QuicPacketNumber last_packet_number;
// PacketNumber of the last packet whose status is known (acked/lost).
QuicPacketNumber last_packet_number_accounted_for;
// Number of bytes which are sent in total.
QuicByteCount bytes_sent;
// Number of bytes which have been acked.
QuicByteCount bytes_acked;
// Number of bytes which are considered as lost.
QuicByteCount bytes_lost;
// Utility value of this MonitorInterval, which is calculated
// when all sent packets are accounted for.
float utility;
// The number of packets in this monitor interval.
int n_packets_sent;
// The number of packets whose return status is known.
int n_packets_accounted_for;
// A sample of the RTT for each packet.
std::vector<PacketRttSample> packet_rtt_samples;
};
#ifdef QUIC_PORT
} // namespace gfe_quic
#endif
#endif // THIRD_PARTY_PCC_QUIC_PCC_MONITOR_INTERVAL_H_
| 5,090 | 28.091429 | 110 | h |
null | SymbolicPCC-main/src/pcc/monitor_interval/pcc_mi_analysis_group.h | #ifndef THIRD_PARTY_PCC_QUIC_PCC_MONITOR_INTERVAL_ANALYSIS_GROUP_H_
#define THIRD_PARTY_PCC_QUIC_PCC_MONITOR_INTERVAL_ANALYSIS_GROUP_H_
#include <deque>
#include <utility>
#include <vector>
#ifdef QUIC_PORT
#ifdef QUIC_PORT_LOCAL
#include "net/quic/core/congestion_control/pcc_monitor_interval.h"
#include "net/quic/core/quic_time.h"
#include "net/quic/core/quic_types.h"
#else
#include "gfe/quic/core/congestion_control/pcc_monitor_interval.h"
#include "gfe/quic/core/quic_time.h"
#include "gfe/quic/core/quic_types.h"
#endif
#else
#include "pcc_mi.h"
#endif
#ifdef QUIC_PORT
#ifdef QUIC_PORT_LOCAL
namespace net {
namespace {
}
#else
namespace gfe_quic {
#endif
using namespace net;
#endif
struct ComputedGradient {
QuicTime time;
QuicBandwidth rate;
float gradient;
};
class PccMonitorIntervalAnalysisGroup {
public:
explicit PccMonitorIntervalAnalysisGroup(int size);
PccMonitorIntervalAnalysisGroup(const PccMonitorIntervalAnalysisGroup&) = delete;
PccMonitorIntervalAnalysisGroup& operator=(const PccMonitorIntervalAnalysisGroup&) = delete;
PccMonitorIntervalAnalysisGroup(PccMonitorIntervalAnalysisGroup&&) = delete;
PccMonitorIntervalAnalysisGroup& operator=(PccMonitorIntervalAnalysisGroup&&) = delete;
#if defined(QUIC_PORT) && defined(QUIC_PORT_LOCAL)
~PccMonitorIntervalAnalysisGroup();
#else
~PccMonitorIntervalAnalysisGroup() {}
#endif
std::deque<MonitorInterval>::iterator Begin();
std::deque<MonitorInterval>::iterator End();
// Creates a new MonitorInterval and add it to the tail of the
// monitor interval queue, provided the necessary variables
// for MonitorInterval initialization.
void AddNewInterval(MonitorInterval& mi);
void RemoveOldestInterval();
MonitorInterval& GetMostRecentInterval();
bool Full();
bool Empty();
float ComputeWeightedUtilityGradient(QuicTime cur_time, float target_rate,
float time_decay, float rate_decay);
float ComputeUtilityGradient();
private:
void ComputeUtilityGradientVector_(std::vector<ComputedGradient>* gradients);
std::deque<MonitorInterval> monitor_intervals_;
int size_;
};
#ifdef QUIC_PORT
} // namespace gfe_quic
#endif
#endif // THIRD_PARTY_PCC_QUIC_PCC_MONITOR_INTERVAL_ANALYSIS_GROUP_H_
| 2,244 | 26.048193 | 94 | h |
null | SymbolicPCC-main/src/pcc/monitor_interval/pcc_mi_queue.h | #ifndef THIRD_PARTY_PCC_QUIC_PCC_MONITOR_QUEUE_H_
#define THIRD_PARTY_PCC_QUIC_PCC_MONITOR_QUEUE_H_
#include <deque>
#include <utility>
#include <vector>
#ifdef QUIC_PORT
#ifdef QUIC_PORT_LOCAL
#include "net/quic/core/congestion_control/send_algorithm_interface.h"
#include "net/quic/core/congestion_control/pcc_monitor_interval.h"
#include "net/quic/core/quic_time.h"
#include "net/quic/core/quic_types.h"
#else
#include "gfe/quic/core/congestion_control/send_algorithm_interface.h"
#include "gfe/quic/core/congestion_control/pcc_monitor_interval.h"
#include "gfe/quic/core/quic_time.h"
#include "gfe/quic/core/quic_types.h"
#endif
#else
#include "pcc_mi.h"
#include <cstdint>
#include <cstdlib>
#include <cmath>
#endif
#ifndef QUIC_PORT
typedef struct CongestionEvent {
int32_t packet_number;
int32_t bytes_acked;
int32_t bytes_lost;
uint64_t time;
} CongestionEvent;
typedef CongestionEvent AckedPacket;
typedef CongestionEvent LostPacket;
typedef std::vector<CongestionEvent> AckedPacketVector;
typedef std::vector<CongestionEvent> LostPacketVector;
#endif
#ifdef QUIC_PORT
#ifdef QUIC_PORT_LOCAL
namespace net {
namespace {
}
#else
namespace gfe_quic {
#endif
using namespace net;
#endif
// PccMonitorIntervalQueue contains a queue of MonitorIntervals.
// New MonitorIntervals are added to the tail of the queue.
// Existing MonitorIntervals are removed from the queue when all
// 'useful' intervals' utilities are available.
class PccMonitorIntervalQueue {
public:
explicit PccMonitorIntervalQueue();
PccMonitorIntervalQueue(const PccMonitorIntervalQueue&) = delete;
PccMonitorIntervalQueue& operator=(const PccMonitorIntervalQueue&) = delete;
PccMonitorIntervalQueue(PccMonitorIntervalQueue&&) = delete;
PccMonitorIntervalQueue& operator=(PccMonitorIntervalQueue&&) = delete;
#if defined(QUIC_PORT) && defined(QUIC_PORT_LOCAL)
~PccMonitorIntervalQueue();
#else
~PccMonitorIntervalQueue() {}
#endif
// Creates a new MonitorInterval and add it to the tail of the
// monitor interval queue, provided the necessary variables
// for MonitorInterval initialization.
void Push(MonitorInterval mi);
// Called when a packet belonging to current monitor interval is sent.
void OnPacketSent(QuicTime sent_time,
QuicPacketNumber packet_number,
QuicByteCount bytes);
// Called when packets are acked or considered as lost.
void OnCongestionEvent(const AckedPacketVector& acked_packets,
const LostPacketVector& lost_packets,
int64_t rtt_us,
QuicTime event_time);
// Returns the most recent MonitorInterval in the tail of the queue
const MonitorInterval& Current() const;
bool HasFinishedInterval(QuicTime cur_time);
MonitorInterval Pop();
bool Empty() const;
#if defined(QUIC_PORT) && defined(QUIC_PORT_LOCAL)
size_t Size() const { return monitor_intervals_.size(); }
#else
size_t Size() const;
#endif
private:
std::deque<MonitorInterval> monitor_intervals_;
};
#ifdef QUIC_PORT
} // namespace gfe_quic
#endif
#endif // THIRD_PARTY_PCC_QUIC_PCC_MONITOR_QUEUE_H_
| 3,163 | 28.849057 | 78 | h |
null | SymbolicPCC-main/src/pcc/rate_control/pcc_ixp_rc.h | // PCC (Performance Oriented Congestion Control) algorithm
#ifndef _PCC_IXP_RC_H_
#define _PCC_IXP_RC_H_
#include <vector>
#include <queue>
#include "../../core/options.h"
#include "pcc_rc.h"
#include <iostream>
struct RateSample {
double rate;
double u_mean;
double u_var;
double ud_mean;
double ud_var;
double ud_smallest;
int n_samples;
void AddSample(const MonitorInterval* first_mi, const MonitorInterval* second_mi);
double GetDeltaCertainty() const;
RateSample(double rate);
};
class PccIxpRateController : public PccRateController {
public:
PccIxpRateController(double call_freq, PccEventLogger* log);
~PccIxpRateController();
QuicBandwidth GetNextSendingRate(QuicBandwidth current_rate, QuicTime cur_time);
void MonitorIntervalFinished(const MonitorInterval& mi);
private:
double ComputeProjectedUtilityGradient();
double ComputeProjectedUtility(const RateSample* rs);
std::deque<RateSample*> rate_samples_;
int cur_replica_;
MonitorInterval* cur_mi_;
RateSample* cur_rs_;
PccEventLogger* log_;
bool last_change_pos_;
double step_size_;
};
#endif
| 1,133 | 22.625 | 86 | h |
null | SymbolicPCC-main/src/pcc/rate_control/pcc_python_rc.h |
#ifndef _PCC_PYTHON_RC_H_
#define _PCC_PYTHON_RC_H_
#include <mutex>
#include <queue>
#include <vector>
#include "pcc_rc.h"
#include <python3.5/Python.h>
#include <iostream>
#include <sstream>
#ifndef USEC_PER_SEC
#define USEC_PER_SEC 1000000
#endif
class PccPythonRateController : public PccRateController {
public:
PccPythonRateController(double call_freq, PccEventLogger* log);
~PccPythonRateController() {};
QuicBandwidth GetNextSendingRate(QuicBandwidth current_rate, QuicTime cur_time);
void MonitorIntervalFinished(const MonitorInterval& mi);
void Reset();
private:
static void InitializePython();
static int GetNextId();
static std::mutex interpreter_lock_;
static bool python_initialized_;
void GiveSample(int bytes_sent,
int bytes_acked,
int bytes_lost,
double send_start_time_sec,
double send_end_time_sec,
double recv_start_time_sec,
double recv_end_time_sec,
double first_ack_latency_sec,
double last_ack_latency_sec,
int packet_size,
double utility);
int id;
bool has_time_offset;
uint64_t time_offset_usec;
PyObject* module;
PyObject* give_sample_func;
PyObject* get_rate_func;
PyObject* reset_func;
};
#endif
| 1,363 | 22.118644 | 82 | h |
null | SymbolicPCC-main/src/pcc/rate_control/pcc_rc.h |
#ifndef _PCC_RC_H_
#define _PCC_RC_H_
#include "../monitor_interval/pcc_mi.h"
#include "../../core/options.h"
#include "../pcc_logger.h"
class PccRateController {
public:
PccRateController() {};
virtual ~PccRateController() {};
virtual QuicBandwidth GetNextSendingRate(QuicBandwidth current_rate, QuicTime cur_time) = 0;
virtual void MonitorIntervalFinished(const MonitorInterval& mi) = 0;
virtual void Reset() {std::cout << "DEFAULT RESET CALLED" << std::endl; };
};
#endif
| 501 | 25.421053 | 96 | h |
null | SymbolicPCC-main/src/pcc/utility/pcc_copa_ucalc.h |
#ifndef _PCC_COPA_UCALC_H_
#define _PCC_COPA_UCALC_H_
#include "pcc_ucalc.h"
class PccCopaUtilityCalculator : public PccUtilityCalculator {
public:
PccCopaUtilityCalculator(PccEventLogger* logger) {this->logger = logger; this->last_avg_rtt = 1000; };
~PccCopaUtilityCalculator() {};
float CalculateUtility(PccMonitorIntervalAnalysisGroup& past_monitor_intervals, MonitorInterval&
cur_monitor_interval);
private:
PccEventLogger* logger;
float last_avg_rtt;
};
#endif
| 502 | 25.473684 | 106 | h |
afterglowpy | afterglowpy-master/afterglowpy/integrate.h | #ifndef AFTERGLOWPY_INTEGRATE
#define AFTERGLOWPY_INTEGRATE
#include "interval.h"
/*
* Various routines for integrating 1D functions.
* trap() and simp() are fixed stencil implementations of the Trapezoid Rule
* and Simpson's Rule respectively.
*
* romb() is an adaptive Romberg integrator.
*
* trap_adapt() and simp_adapt() are globally adaptive integrators based on
* the Trapezoid and Simpson's rule, respectively. They successively bisect
* the integration domain into subintervals, prioritizing the subintervals
* with largest (estimated) error, until the total absolute error estimate
* is within tolerance.
*/
/*
* Integration routines
*/
double trap(double (*f)(double, void *), double xa, double xb, int N,
void *args, int (*errf)(void *));
double simp(double (*f)(double, void *), double xa, double xb, int N,
void *args, int (*errf)(void *));
double romb(double (*f)(double, void *), double xa, double xb, int N,
double atol, double rtol, void *args, int *Neval, double *eps,
int verbose, int (*errf)(void *), double *pfa, double *pfb);
double trap_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
double atol, double rtol, void *args, int *Neval,
double *eps, struct Mesh3 *mout, int verbose,
int (*errf)(void *), double *pfa, double *pfb);
double simp_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
double atol, double rtol, void *args, int *Neval,
double *eps, struct Mesh5 *mout, int verbose,
int (*errf)(void *), double *pfa, double *pfb);
double trapNL_adapt(double (*f)(double, void *), double xa, double xb,int Nmax,
double atol, double rtol, void *args, int *Neval,
double *eps, struct Mesh5 *mout, int verbose,
int (*errf)(void *), double *pfa, double *pfb);
double hybrid_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
double atol, double rtol, void *args, int *Neval,
double *eps, int verbose, int (*errf)(void *),
double *pfa, double *pfb);
double cadre_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
double atol, double rtol, void *args, int *Neval,
double *eps, int verbose, int (*errf)(void *),
double *pfa, double *pfb);
double gk49_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
double atol, double rtol, void *args, int *Neval,
double *eps, int verbose, int (*errf)(void *));
double gk715_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
double atol, double rtol, void *args, int *Neval,
double *eps, int verbose, int (*errf)(void *));
double gk1021_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
double atol, double rtol, void *args, int *Neval,
double *eps, int verbose, int (*errf)(void *));
/*
* Internal functions for trap_adapt and simp_adapt.
*/
double m_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
int (*processInterval)(double (*f)(double, void*), void *,
Interval *, int (*errf)(void *)),
int (*splitInterval)(double (*f)(double, void *), void *,
Interval *, Interval *, Interval *,
int (*errf)(void *)),
double atol, double rtol, void *args, int *Neval,
double *eps, struct Mesh *mout, int verbose,
int (*errf)(void *));
double m3_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
int (*initInterval)(double (*f)(double, void*), void *,
Interval3 *, int (*errf)(void *),
double *pfa, double *pfb),
int (*processInterval)(double (*f)(double, void*), void *,
Interval3 *, int (*errf)(void *)),
int (*splitInterval)(double (*f)(double, void *), void *,
Interval3 *, Interval3 *, Interval3 *,
int (*errf)(void *)),
double atol, double rtol, void *args, int *Neval,
double *eps, struct Mesh3 *mout, int verbose,
int (*errf)(void *), double *pfa, double *pfb);
double m5_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
int (*initInterval)(double (*f)(double, void*), void *,
Interval5 *, int (*errf)(void *),
double *pfa, double *pfb),
int (*processInterval)(double (*f)(double, void*), void *,
Interval5 *, int (*errf)(void *)),
int (*splitInterval)(double (*f)(double, void *), void *,
Interval5 *, Interval5 *, Interval5 *,
int (*errf)(void *)),
double atol, double rtol, void *args, int *Neval,
double *eps, struct Mesh5 *mout, int verbose,
int (*errf)(void *), double *pfa, double *pbf);
double m9_adapt(double (*f)(double, void *), double xa, double xb, int Nmax,
int (*initInterval)(double (*f)(double, void*), void *,
Interval9 *, int (*errf)(void *),
double *pfa, double *pfb),
int (*processInterval)(double (*f)(double, void*), void *,
Interval9 *, int (*errf)(void *)),
int (*splitInterval)(double (*f)(double, void *), void *,
Interval9 *, Interval9 *, Interval9 *,
int (*errf)(void *)),
double atol, double rtol, void *args, int *Neval,
double *eps, struct Mesh9 *mout, int verbose,
int (*errf)(void *), double *pfa, double *pbf);
int trapInitInterval(double (*f)(double, void *), void *args, Interval3 *i,
int (*errf)(void *), double *pfa, double *pfb);
int trapProcessInterval(double (*f)(double, void *), void *args, Interval3 *i,
int (*errf)(void *));
int trapSplitInterval(double (*f)(double, void *), void *args,
Interval3 *i0, Interval3 *i1, Interval3 *i2,
int (*errf)(void *));
int simpInitInterval(double (*f)(double, void *), void *args, Interval5 *i,
int (*errf)(void *), double *pfa, double *pfb);
int simpProcessInterval(double (*f)(double, void *), void *args, Interval5 *i,
int (*errf)(void *));
int simpSplitInterval(double (*f)(double, void *), void *args,
Interval5 *i0, Interval5 *i1, Interval5 *i2,
int (*errf)(void *));
int trapNLInitInterval(double (*f)(double, void *), void *args, Interval5 *i,
int (*errf)(void *), double *pfa, double *pfb);
int trapNLProcessInterval(double (*f)(double, void *), void *args,
Interval5 *i, int (*errf)(void *));
int trapNLSplitInterval(double (*f)(double, void *), void *args,
Interval5 *i0, Interval5 *i1, Interval5 *i2,
int (*errf)(void *));
int cadreInitInterval(double (*f)(double, void *), void *args, Interval9 *i,
int (*errf)(void *), double *pfa, double *pfb);
int cadreProcessInterval(double (*f)(double, void *), void *args,
Interval9 *i, int (*errf)(void *));
int cadreSplitInterval(double (*f)(double, void *), void *args,
Interval9 *i0, Interval9 *i1, Interval9 *i2,
int (*errf)(void *));
int gk49ProcessInterval(double (*f)(double, void *), void *args,
Interval *i, int (*errf)(void *));
int gk49SplitInterval(double (*f)(double, void *), void *args,
Interval *i0, Interval *i1, Interval *i2,
int (*errf)(void *));
int gk715ProcessInterval(double (*f)(double, void *), void *args,
Interval *i, int (*errf)(void *));
int gk715SplitInterval(double (*f)(double, void *), void *args,
Interval *i0, Interval *i1, Interval *i2,
int (*errf)(void *));
int gk1021ProcessInterval(double (*f)(double, void *), void *args,
Interval *i, int (*errf)(void *));
int gk1021SplitInterval(double (*f)(double, void *), void *args,
Interval *i0, Interval *i1, Interval *i2,
int (*errf)(void *));
int gk_compute(double (*f)(double, void *), void *args, int (*errf)(void *),
double c, double z0, const double xg[], const double xk[],
const double wg[], const double wgk[], int ng,
double *I, double *err);
#endif
| 9,276 | 54.885542 | 80 | h |
afterglowpy | afterglowpy-master/afterglowpy/interval.h | #ifndef AFTERGLOWPY_INTERVAL
#define AFTERGLOWPY_INTERVAL
/*
* Here are 3 helper structs for performing global adaptive integration.
* Each Mesh struct is a priority queue implemented with as a simple
* binary heap. Elements may be added, and the element with the worst error can
* be retrieved.
*
* Each mesh is a container of Intervals. An Interval is a primitive struct
* contains only its left and right bounds, the value of the integral and its
* error over that interval. The Interval3 and Interval5 are identical to
* Interval but contain 3 (or 5) extra slots to contain function memorized
* function values.
*
* The Mesh3 and Mesh5 are priority queues of Interval3s and Interval5s
* respectively.
*/
struct Interval
{
double a;
double b;
double I;
double err;
};
typedef struct Interval Interval;
struct Mesh
{
size_t totalSize;
size_t N;
struct Interval *heap;
};
typedef struct Mesh Mesh;
struct Interval3
{
double a;
double b;
double I;
double err;
double fa;
double fb;
double fm;
};
typedef struct Interval3 Interval3;
struct Mesh3
{
size_t totalSize;
size_t N;
struct Interval3 *heap;
};
typedef struct Mesh3 Mesh3;
struct Interval5
{
double a;
double b;
double I;
double err;
double fa;
double fb;
double fl;
double fm;
double fr;
};
typedef struct Interval5 Interval5;
struct Mesh5
{
size_t totalSize;
size_t N;
struct Interval5 *heap;
};
typedef struct Mesh5 Mesh5;
struct Interval9
{
double a;
double b;
double I;
double err;
double fa;
double fll;
double fl;
double flr;
double fm;
double frl;
double fr;
double frr;
double fb;
int refinement;
};
typedef struct Interval9 Interval9;
struct Mesh9
{
size_t totalSize;
size_t N;
struct Interval9 *heap;
};
typedef struct Mesh9 Mesh9;
void meshInit(struct Mesh *m);
void meshFree(struct Mesh *m);
void meshInsert(struct Mesh *m, struct Interval *i);
void meshExtract(struct Mesh *m, struct Interval *worst);
double meshTotalIntegral(struct Mesh *m);
double meshTotalError(struct Mesh *m);
void meshHeapifyUp(struct Mesh *m);
void meshHeapifyDown(struct Mesh *m);
int meshCheck(struct Mesh *m);
void meshWrite(struct Mesh *m, char **buf);
void mesh3Init(struct Mesh3 *m);
void mesh3Free(struct Mesh3 *m);
void mesh3Insert(struct Mesh3 *m, struct Interval3 *i);
void mesh3Extract(struct Mesh3 *m, struct Interval3 *worst);
double mesh3TotalIntegral(struct Mesh3 *m);
double mesh3TotalError(struct Mesh3 *m);
void mesh3HeapifyUp(struct Mesh3 *m);
void mesh3HeapifyDown(struct Mesh3 *m);
int mesh3Check(struct Mesh3 *m);
void mesh3Write(struct Mesh3 *m, char **buf);
void mesh5Init(struct Mesh5 *m);
void mesh5Free(struct Mesh5 *m);
void mesh5Insert(struct Mesh5 *m, struct Interval5 *i);
void mesh5Extract(struct Mesh5 *m, struct Interval5 *worst);
double mesh5TotalIntegral(struct Mesh5 *m);
double mesh5TotalError(struct Mesh5 *m);
void mesh5HeapifyUp(struct Mesh5 *m);
void mesh5HeapifyDown(struct Mesh5 *m);
int mesh5Check(struct Mesh5 *m);
void mesh5Write(struct Mesh5 *m, char **buf);
void mesh9Init(struct Mesh9 *m);
void mesh9Free(struct Mesh9 *m);
void mesh9Insert(struct Mesh9 *m, struct Interval9 *i);
void mesh9Extract(struct Mesh9 *m, struct Interval9 *worst);
double mesh9TotalIntegral(struct Mesh9 *m);
double mesh9TotalError(struct Mesh9 *m);
void mesh9HeapifyUp(struct Mesh9 *m);
void mesh9HeapifyDown(struct Mesh9 *m);
int mesh9Check(struct Mesh9 *m);
void mesh9Write(struct Mesh9 *m, char **buf);
void interval9Write(struct Interval9 *i, FILE *stream);
#endif
| 3,654 | 23.046053 | 79 | h |
afterglowpy | afterglowpy-master/afterglowpy/offaxis_struct.h | #ifndef AFTERGLOWPY_STRUCT
#define AFTERGLOWPY_STRUCT
// offaxis.h
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "integrate.h"
#define ERR_CHK_VOID(pars) if(pars->error){ return;}
#define ERR_CHK_INT(pars) if(pars->error){ return 0;}
#define ERR_CHK_DBL(pars) if(pars->error){ return 0.0;}
#define MSG_LEN 4096
#define DUMP_MSG_LEN_MAX 16384 //overkill: 200 lines * 80c per line = 16000
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// some physical and mathematical constants
#define PI 3.14159265358979323846
#define v_light 2.99792458e10 // speed of light in cm / s
#define invv_light 3.335640952e-11 // inverse speed of light s / cm
#define m_e 9.1093897e-28 // electron mass in g
#define m_p 1.6726231e-24 // proton mass in g
#define invm_e 1.097768383e27 // inverse electron mass in 1/g
#define invm_p 5.978633202e23 // inverse proton mass in 1/g
#define h_planck 6.6260755e-27 // Planck's constant in erg / s
#define h_bar 1.05457266e-27 // Planck's constant / 2 PI in erg /s
#define k_B 1.380658e-16 // Boltzmann's constant in erg / K
#define e_e 4.803e-10 // electron charge in Gaussian cgs units
#define sigma_T 6.65e-25 // Thomson cross section free electron cm^2
#define cgs2mJy 1e26 // quantity in cgs to mJy
#define mJy2cgs 1e-26 // quantity in mJy to cgs
#define deg2rad 0.017453292 // quantity in degrees to radians
#define rad2deg 57.29577951 // quantity in radians to degrees
#define sec2day 0.000011574 // quantity in seconds to days
#define day2sec 86400 // quantity in days to seconds
#define parsec 3.0857e18 // quantity in parsec to cm
#define Hz2eV 4.13566553853599E-15
#define eV2Hz 2.417991e+14
#define _cone -2
#define _tophat -1
#define _Gaussian 0
#define _powerlaw_core 1 //has a core as well
#define _Gaussian_core 2 // has a core as well
#define _spherical 3
#define _powerlaw 4
#define _exponential 5
#define _twocomponent 6
#define _exponential2 7
#define IC_COOLING_FLAG 1
#define EPS_E_BAR_FLAG 2
#define SSA_SMOOTH_FLAG 4
#define SSA_SHARP_FLAG 8
enum{INT_TRAP_FIXED, INT_TRAP_ADAPT, INT_SIMP_FIXED, INT_SIMP_ADAPT,
INT_ROMB_ADAPT, INT_TRAP_NL, INT_HYBRID, INT_CADRE,
INT_GK49_ADAPT, INT_GK715_ADAPT, INT_GK1021_ADAPT,
INT_UNDEFINED};
enum{GAMMA_INF, GAMMA_FLAT, GAMMA_EVENMASS, GAMMA_STRUCT};
struct fluxParams
{
double theta;
double phi;
double cp;
double ct;
double st;
double cto;
double sto;
double theta_obs;
double t_obs;
double nu_obs;
double d_L;
double E_iso;
double n_0;
double g_init;
double p;
double epsilon_E;
double epsilon_B;
double ksi_N;
double theta_h;
double E_iso_core;
double theta_core;
double theta_wing;
double b;
double E_tot;
double g_core;
double E_core_global;
double theta_core_global;
int envType;
double As;
double Rwind;
double L0;
double q;
double ts;
double current_theta_cone_hi;
double current_theta_cone_low;
double theta_obs_cur;
int tRes;
int latRes;
int spread;
int counterjet;
int int_type;
double rtol_struct;
double rtol_theta;
double rtol_phi;
int nmax_theta;
int nmax_phi;
double atol_theta;
double Rt0;
double Rt1;
double ta;
double tb;
double C_BMsqrd;
double C_STsqrd;
double t_NR;
double *t_table;
double *R_table;
double *u_table;
double *th_table;
double *mu_table;
int table_entries;
double *t_table_inner;
double *R_table_inner;
double *u_table_inner;
double *th_table_inner;
double *mu_table_inner;
int table_entries_inner;
int spec_type;
int gamma_type;
double (*f_E)(double, void *);
double *mask;
int nmask;
long nevals;
int error;
char *error_msg;
};
double dmin(const double a, const double b);
double f_E_tophat(double theta, void *params);
double f_E_Gaussian(double theta, void *params);
double f_E_powerlaw(double theta, void *params);
double f_E_twocomponent(double theta, void *params);
double f_E_exponential(double theta, void *params);
double f_Etot_tophat(void *params);
double f_Etot_Gaussian(void *params);
double f_Etot_powerlaw(void *params);
void make_R_table(struct fluxParams *pars);
void make_mu_table(struct fluxParams *pars);
double check_t_e(double t_e, double mu, double t_obs, double *mu_table, int N);
int searchSorted(double x, double *arr, int N);
double interpolateLin(int a, int b, double x, double *X, double *Y, int N);
double interpolateLog(int a, int b, double x, double *X, double *Y, int N);
double find_jet_edge(double phi, double cto, double sto, double theta0,
double *a_mu, double *a_thj, int N);
double costheta_integrand(double a_theta, void* params); // inner integral
double phi_integrand(double a_phi, void* params); // outer integral
double emissivity(double nu, double R, double mu, double te,
double u, double us, double n0, double p, double epse,
double epsB, double ksiN, int specType); //emissivity of
// a zone.
double flux(struct fluxParams *pars, double atol); // determine flux for a given t_obs
double flux_cone(double t_obs, double nu_obs, double E_iso, double theta_h,
double theta_cone_low, double theta_cone_hi,
double atol, struct fluxParams *pars);
double intensity(double theta, double phi, double tobs, double nuobs,
double theta_obs, double theta_cone_hi, double theta_cone_low,
struct fluxParams *pars);
void shockVals(double theta, double phi, double tobs,
double *t, double *R, double *u, double *thj,
double theta_obs, double theta_cone_hi, double theta_cone_low,
struct fluxParams *pars);
void intensity_cone(double *theta, double *phi, double *t, double *nu,
double *I, int N, double E_iso_core,
double theta_h_core, double theta_h_wing,
struct fluxParams *pars);
void intensity_struct(double *theta, double *phi, double *t, double *nu,
double *I, int N,
double E_iso_core,
double theta_h_core, double theta_h_wing,
int res_cones, double (*f_E)(double,void *),
struct fluxParams *pars);
void intensity_structCore(double *theta, double *phi, double *t, double *nu,
double *I, int N,
double E_iso_core,
double theta_h_core, double theta_h_wing,
int res_cones, double (*f_E)(double,void *),
struct fluxParams *pars);
void shockVals_cone(double *theta, double *phi, double *tobs,
double *t, double *R, double *u, double *thj, int N,
double E_iso_core, double theta_h_core, double theta_h_wing,
struct fluxParams *pars);
void shockVals_struct(double *theta, double *phi, double *tobs,
double *t, double *R, double *u, double *thj, int N,
double E_iso_core,
double theta_h_core, double theta_h_wing,
int res_cones, double (*f_E)(double,void *),
struct fluxParams *pars);
void shockVals_structCore(double *theta, double *phi, double *tobs,
double *t, double *R, double *u, double *thj, int N,
double E_iso_core,
double theta_h_core, double theta_h_wing,
int res_cones, double (*f_E)(double,void *),
struct fluxParams *pars);
void lc_tophat(double *t, double *nu, double *F, int Nt,
double E_iso, double theta_h, struct fluxParams *pars);
void lc_cone(double *t, double *nu, double *F, int Nt, double E_iso,
double theta_h, double theta_wing, struct fluxParams *pars);
void lc_powerlawCore(double *t, double *nu, double *F, int Nt,
double E_iso_core, double theta_h_core,
double theta_h_wing, double beta,
double *theta_c_arr, double *E_iso_arr,
int res_cones, struct fluxParams *pars);
void lc_powerlaw(double *t, double *nu, double *F, int Nt,
double E_iso_core, double theta_h_core,
double theta_h_wing,
double *theta_c_arr, double *E_iso_arr,
int res_cones, struct fluxParams *pars);
void lc_Gaussian(double *t, double *nu, double *F, int Nt,
double E_iso_core,
double theta_h_core, double theta_h_wing,
double *theta_c_arr, double *E_iso_arr,
int res_cones, struct fluxParams *pars);
void lc_GaussianCore(double *t, double *nu, double *F, int Nt,
double E_iso_core,
double theta_h_core, double theta_h_wing,
double *theta_c_arr, double *E_iso_arr,
int res_cones, struct fluxParams *pars);
void calc_flux_density(int jet_type, int spec_type,
double *t, double *nu, double *Fnu, int N,
struct fluxParams *fp);
void calc_intensity(int jet_type, int spec_type, double *theta, double *phi,
double *t, double *nu, double *Inu, int N,
struct fluxParams *fp);
void calc_shockVals(int jet_type, double *theta, double *phi, double *tobs,
double *t, double *R, double *u, double *thj, int N,
struct fluxParams *fp);
void setup_fluxParams(struct fluxParams *pars,
double d_L,
double theta_obs,
double E_iso_core, double theta_core, double theta_wing,
double b, double L0, double q, double ts,
double n_0,
double p,
double epsilon_E,
double epsilon_B,
double ksi_N,
double g0,
double E_core_global,
double theta_core_global,
double ta, double tb,
int tRes, int latRes, int int_type,
double rtol_struct, double rtol_phi, double rtol_theta,
int nmax_phi, int nmax_theta,
int spec_type,
double *mask, int nmask,
int spread, int counterjet, int gamma_type);
void set_jet_params(struct fluxParams *pars, double E_iso, double theta_h);
void set_obs_params(struct fluxParams *pars, double t_obs, double nu_obs,
double theta_obs_cur, double current_theta_cone_hi,
double current_theta_cone_low);
int check_error(void *params);
void set_error(struct fluxParams *pars, char msg[]);
void free_fluxParams(struct fluxParams *pars);
#endif
| 11,405 | 37.147157 | 86 | h |
afterglowpy | afterglowpy-master/afterglowpy/shockEvolution.c | #include <stdio.h>
#include <math.h>
#include "offaxis_struct.h"
#include "shockEvolution.h"
double shockVel(double u)
{
return 4*u*sqrt((u*u+1) / (8*u*u+9));
}
double E_inj(double te, double L0, double q, double ts)
{
if(te < T0_inj)
return L0*te;
if (te > ts)
te = ts;
double E = L0*T0_inj;
if(q == 0.0)
return L0*te;
else if(q == 1.0)
return E + L0*T0_inj*log(te/T0_inj);
else
return E + L0*T0_inj*(pow(te/T0_inj,1-q) - 1.0)/(1-q);
return 0.0;
}
double L_inj(double te, double L0, double q, double ts)
{
if(te <= T0_inj)
return L0;
else if(te < ts)
{
if(q == 0.0)
return L0;
else
return L0*pow(te/T0_inj,-q);
}
return 0.0;
}
double te_inj(double Ei, double L0, double q, double ts)
{
if(L0*T0_inj >= Ei)
return Ei / L0;
Ei -= L0*T0_inj;
double te;
if(q == 0)
te = Ei/L0;
else if (q == 1)
te = T0_inj * exp(Ei/(L0*T0_inj));
else
te = T0_inj * pow((1-q)*Ei/(L0*T0_inj)+1, 1.0/(1-q));
if(te > ts)
return -1.0;
return te;
}
double t_inj(double te, double t0, double te0, double L0, double q, double ts)
{
return t0*pow(1 + 16*(te-te0)/((2-q)*t0), 0.25*(2-q));
}
void shockInitDecel(double t0, double *R0, double *u0, void *argv)
{
double *args = (double *)argv;
double E0 = args[0];
double rho0 = args[2];
double L0 = args[6];
double q = args[7];
double ts = args[8];
double dr, R, u;
double c = v_light;
double c5 = c*c*c*c*c;
//First pass: assume no energy injection
double C = sqrt(9/(16.0*M_PI) * E0/(rho0*c5));
u = C * pow(t0, -1.5);
dr = 1.0/(u*u*16.0);
R = c*t0*(1-dr);
if(L0 < 0.0 || ts < 0.0)
{
//printf("No energy injection! E=%.3le\n", E0);
*R0 = R;
*u0 = u;
return;
}
//Check if energy injection is important
double te = t0*dr;
double Ei = E_inj(te, L0, q, ts);
if(Ei <= E0)
{
//printf("Energy injection not important! E0=%.3le Ei=%.3le\n", E0, Ei);
*R0 = R;
*u0 = u;
return;
}
//Second pass: use energy injection solution.
//Time for transition
double teb = te_inj(E0, L0, q, ts);
double t1 = pow(16*C*C*teb, 0.25);
//position at transition
double u1 = C * pow(t1, -1.5);
double dr1 = 1.0/(u1*u1*16.0);
//Account for initial constant Luminosity
if(teb < T0_inj)
{
//Lab time for T0_inj
double t0i = t_inj(T0_inj, t1, teb, L0, 0.0, ts);
if(t0 < t0i) //Praise be
{
//printf("Early energy injection.\n");
u = u1*pow(t0/t1, -0.5);
dr = (t1*dr1 + 2*(t0/(u*u)-t1/(u1*u1))/16.0) / t0;
*R0 = c*t0*(1-dr);
*u0 = u;
return;
}
//Move solution forwards.
u = u1*pow(t0i/t1, -0.5);
dr = (t1*dr1 + 2*(t0i/(u*u)-t1/(u1*u1))/16.0) / t0i;
t1 = t0i;
u1 = u;
dr1 = dr;
}
double te1 = dr1*t1;
//Get lab time when energy injection ends.
double tls = t_inj(ts, t1, te1, L0, q, ts);
if(t0 < tls)
{
//printf("Late energy injection.\n");
u = u1*pow(t0/t1, -0.5*(2+q)/(2-q));
dr = (t1*dr1 + (2-q)*(t0/(u*u)-t1/(u1*u1))/16.0) / t0;
*R0 = c*t0*(1-dr);
*u0 = u;
return;
}
//Energy injection is over!
//Just use original solution with boosted energy.
//printf("All energy injected.\n");
Ei = E_inj(ts, L0, q, ts);
C = sqrt(9/(16.0*M_PI) * (E0+Ei)/(rho0*c5));
u = C * pow(t0, -1.5);
*R0 = c*t0*(1 - 1/(16*u*u));
*u0 = u;
}
void shockInitFind(double t0, double *R0, double *u0, double tRes, void *argv)
{
double *args = (double *)argv;
double E0 = args[0];
double Mej = args[1];
double rho0 = args[2];
double L0 = args[6];
double q = args[7];
double ts = args[8];
//printf("shockInitFind: t0=%.6lg E0=%.6lg Mej=%.6lg rho0=%.6lg\n",
// t0, E0, Mej, rho0);
//printf(" L0=%.6lg q=%.6lg ts=%.6lg\n", L0, q, ts);
double u;
double c = v_light;
double c5 = c*c*c*c*c;
double C = sqrt(9/(16.0*M_PI) * E0/(rho0*c5));
double tNR = pow(C, 2.0/3.0);
//Time for deceleration
double td;
if(Mej > 0.0)
{
// gc, uc, beSc = coasting gamma, u, beta_shock
double gcmo = E0/(Mej *c*c);
double uc = sqrt(gcmo * (gcmo+2));
double gc = sqrt(1+uc*uc);
double beSc = 4*uc*gc / (4*uc*uc+3);
double Rd = pow(9*gc*gc*Mej / (4*M_PI*(gc+1)*(4*uc*uc+3)*rho0), 1./3.);
td = Rd / (beSc * c);
}
else
{
td = 0.0;
}
//Time for transition
double ti;
if(L0 > 0 && ts > 0)
{
double tei = te_inj(E0, L0, q, ts);
ti = pow(16*C*C*tei, 0.25);
if(tei < 0.0)
ti = 1.0e20 * tNR; //Arbitrary val
}
else
ti = 1.0e20 * tNR; //Arbitrary val
//printf(" td=%.6lg ti=%.6lg tNR=%.6lg\n", td, ti, tNR);
if(t0 < 0.01*tNR && t0 < 0.01*ti && t0 > 100*td)
{
//printf("the EASY way\n");
u = C*pow(t0, -1.5);
*R0 = c*t0*(1-1/(16*u*u));
*u0 = u;
return;
}
else if(t0 < 0.01 * td)
{
double gcmo = E0/(Mej *c*c);
double uc = sqrt(gcmo * (gcmo+2));
double gc = sqrt(1+uc*uc);
double beSc = 4*uc*gc / (4*uc*uc+3);
*R0 = beSc * c * t0;
*u0 = uc;
return;
}
double dt, x[2], x0[2], k1[2], k2[2], k3[2], k4[2];
double t00, u00, R00;
if(td > 0.0)
{
double gcmo = E0/(Mej *c*c);
double uc = sqrt(gcmo * (gcmo+2));
double gc = sqrt(1+uc*uc);
double beSc = 4*uc*gc / (4*uc*uc+3);
t00 = td<t0 ? 0.01*td : 0.01*t0;
R00 = beSc * c * t0;
u00 = uc;
}
else
{
t00 = ti < tNR ? 0.01*ti : 0.01*tNR;
u00 = C*pow(t00, -1.5);
R00 = c*t00*(1-1/(16*u00*u00));
}
//printf("t00=%.6le R00=%.6le u00=%.6le (tNR=%.3le ti=%.3le)\n", t00, R00, u00, tNR, ti);
x[0] = R00;
x[1] = u00;
double t = t00;
double fac = pow(10, 1.0/tRes);
int j;
while(t < t0)
{
dt = (fac-1)*t;
if(fac*t >= t0)
dt = t0-t;
x0[0] = x[0];
x0[1] = x[1];
Rudot2D(t, x, args, k1);
for(j=0; j<2; j++)
x[j] = x0[j] + 0.5*dt*k1[j];
Rudot2D(t, x, args, k2);
for(j=0; j<2; j++)
x[j] = x0[j] + 0.5*dt*k2[j];
Rudot2D(t, x, args, k3);
for(j=0; j<2; j++)
x[j] = x0[j] + dt*k3[j];
Rudot2D(t, x, args, k4);
for(j=0; j<2; j++)
x[j] = x0[j] + dt*(k1[j]+2*k2[j]+2*k3[j]+k4[j])/6.0;
t *= fac;
}
*R0 = x[0];
*u0 = x[1];
}
void Rudot2D(double t, double *x, void *argv, double *xdot)
{
double *args = (double *)argv;
double Mej = args[1];
double rho0 = args[2];
double Einj = args[3];
double k = args[4];
double umin = args[5];
double L0 = args[6];
double q = args[7];
double ts = args[8];
double R = x[0];
double u = x[1];
double g = sqrt(1+u*u);
double be = u/g;
double bes = 4*u*g/(4*u*u+3);
double dRdt = bes * v_light;
double dEdu = 0.0;
if(Einj > 0.0 && u>umin)
dEdu = -k*Einj*pow(u,-k-1);
double dEdt = 0.0;
double te = t - R/v_light;
if(L0 > 0.0 && te < ts)
{
double gs2 = (4*u*u+3)*(4*u*u+3) / (8*u*u+9);
dEdt = L_inj(te, L0, q, ts) / (gs2*(1+bes)); // Doppler factor (1-bes)
}
double num = -16*M_PI/3.0 * rho0*R*R * be*u*u * v_light
+ dEdt/(v_light*v_light);
double denom = be*Mej + 8*M_PI*rho0*R*R*R*u*(2*u*u+1)*(2*u*u+3)/(9*g*g*g*g)
- dEdu/(v_light*v_light);
double dudt = num/denom;
xdot[0] = dRdt;
xdot[1] = dudt;
}
void RuThdot3D(double t, double *x, void *argv, double *xdot, int spread)
{
double *args = (double *)argv;
double Mej = args[1];
double rho0 = args[2];
double Einj = args[3];
double k = args[4];
double umin = args[5];
double L0 = args[6];
double q = args[7];
double ts = args[8];
double thC = args[9];
double th0 = args[10];
double thCg = args[11];
double R = x[0];
double u = x[1];
double th = x[2];
double g = sqrt(1+u*u);
double be = u/g;
double bes = 4*u*g/(4*u*u+3);
double sinth = sin(0.5*th);
double costh = cos(0.5*th);
double om = 2*sinth*sinth;
double dRdt = 4*u*g/(4*u*u+3) * v_light;
double dThdt = 0.0;
//TODO: verify spreading procedure 190401
//if(spread && th < 0.5*M_PI && u < 1)
//if(spread && th < 0.5*M_PI && u*3.0*th < 1)
if(spread)
{
if(spread == 1)
{
double Q0 = 2.0;
double Q = sqrt(2.0)*3.0;
if(th < 0.5*M_PI && Q0*u*thC < 1)
{
double e = u*u/(g+1); // specific internal energy == gamma-1
//Sound speed from trans-relativistic EoS.
double cs = v_light * sqrt(e*(2+e)*(5+8*e+4*e*e)
/ (3*(1+e)*(1+e)*(1+2*e)*(3+2*e)));
double fac = u*thC*Q < 1.0 ? 1.0 : Q*(1-Q0*u*thC) / (Q-Q0);
/*
if(fac < 1.0)
{
double sharp = 3.0;
double f0 = exp(-sharp);
fac = (exp(sharp*(fac-1.0))-f0) / (1.0-f0);
}
*/
//fac = 0.0;
dThdt = fac * cs / (R*g);
}
}
else if(spread == 2)
{
double Q0 = 2.0;
double Q = sqrt(2)*3.0;
if(th < 0.5*M_PI && Q0*u*th0 < 1)
{
double e = u*u/(g+1); // specific internal energy == gamma-1
//Sound speed from trans-relativistic EoS.
double cs = v_light * sqrt(e*(2+e)*(5+8*e+4*e*e)
/ (3*(1+e)*(1+e)*(1+2*e)*(3+2*e)));
double fac = u*th0*Q < 1.0 ? 1.0 : Q*(1-Q0*u*th0) / (Q-Q0);
/*
if(fac < 1.0)
{
double sharp = 3.0;
double f0 = exp(-sharp);
fac = (exp(sharp*(fac-1.0))-f0) / (1.0-f0);
}
*/
//fac = 0.0;
dThdt = fac * cs / (R*g);
}
}
else if(spread == 3)
{
double Q0 = 2.0;
double Q = sqrt(2)*3.0;
if(th < 0.5*M_PI && Q0*u*thCg < 1)
{
double e = u*u/(g+1); // specific internal energy == gamma-1
//Sound speed from trans-relativistic EoS.
double cs = v_light * sqrt(e*(2+e)*(5+8*e+4*e*e)
/ (3*(1+e)*(1+e)*(1+2*e)*(3+2*e)));
double fac = u*thCg*Q < 1.0 ? 1.0 : Q*(1-Q0*u*thCg) / (Q-Q0);
/*
if(fac < 1.0)
{
double sharp = 3.0;
double f0 = exp(-sharp);
fac = (exp(sharp*(fac-1.0))-f0) / (1.0-f0);
}
*/
//fac = 0.0;
dThdt = fac * cs / (R*g);
}
}
else if(spread == 4)
{
double bew = 0.5*sqrt((2*u*u+3)/(4*u*u+3))*bes/g;
dThdt = bew * v_light / R;
}
else if(spread == 5)
{
double Q0 = 2.0;
double Q = sqrt(2.0)*3.0;
if(th < 0.5*M_PI && Q0*u*thC < 1)
{
double bew = 0.5*sqrt((2*u*u+3)/(4*u*u+3))*bes/g;
double fac = u*thC*Q < 1.0 ? 1.0 : Q*(1-Q0*u*thC) / (Q-Q0);
dThdt = fac * bew * v_light / R;
}
}
else if(spread == 6)
{
double Q0 = 2.0;
double Q = sqrt(2.0)*3.0;
if(th < 0.5*M_PI && Q0*u*thCg < 1)
{
double bew = 0.5*sqrt((2*u*u+3)/(4*u*u+3))*bes/g;
double fac = u*thCg*Q < 1.0 ? 1.0 : Q*(1-Q0*u*thCg) / (Q-Q0);
dThdt = fac * bew * v_light / R;
}
}
else if(spread == 7)
{
double Q0 = 2.0;
double Q = sqrt(2.0)*3.0;
if(th < 0.5*M_PI && Q0*u*thC < 1)
{
double bew = 0.5*sqrt((2*u*u+3)/(4*u*u+3))*bes/g;
double fac = u*thC*Q < 1.0 ? 1.0 : Q*(1-Q0*u*thC) / (Q-Q0);
if (th0 < thC)
fac *= tan(0.5*th0)/tan(0.5*thC); //th0/thC;
dThdt = fac * bew * v_light / R;
}
}
else if(spread == 8)
{
double Q0 = 2.0;
double Q = sqrt(2.0)*3.0;
if(th < 0.5*M_PI && Q0*u*thCg < 1)
{
double bew = 0.5*sqrt((2*u*u+3)/(4*u*u+3))*bes/g;
double fac = u*thCg*Q < 1.0 ? 1.0 : Q*(1-Q0*u*thCg) / (Q-Q0);
if (th0 < thCg)
fac *= tan(0.5*th0)/tan(0.5*thCg); //th0/thC;
dThdt = fac * bew * v_light / R;
}
}
}
double dEdu = 0.0;
if(Einj > 0.0 && u>umin)
dEdu = -k*Einj*pow(u,-k-1);
double dEdt = 0.0;
double te = t - R/v_light;
if(L0 > 0.0 && te < ts)
{
double gs2 = (4*u*u+3)*(4*u*u+3) / (8*u*u+9);
dEdt = L_inj(te, L0, q, ts) / (gs2*(1+bes)); // Doppler factor (1-bes)
}
double num = -16*M_PI/3.0 * om*rho0*R*R * be*u*u * v_light
-8*M_PI/9.0*rho0*R*R*R*(4*u*u+3)*be*be*sinth*costh*dThdt
+ om*dEdt/(v_light*v_light);
double denom = be*Mej
+ 8*M_PI*om*rho0*R*R*R*u*(2*u*u+1)*(2*u*u+3)/(9*g*g*g*g)
- dEdu/(v_light*v_light);
double dudt = num/denom;
xdot[0] = dRdt;
xdot[1] = dudt;
xdot[2] = dThdt;
}
void shockEvolveRK4(double *t, double *R, double *u, int N, double R0,
double u0, void *args)
{
int i,j;
double dt, x[2], x0[2], k1[2], k2[2], k3[2], k4[2];
R[0] = R0;
u[0] = u0;
for(i=0; i<N-1; i++)
{
dt = t[i+1] - t[i];
x0[0] = R[i];
x0[1] = u[i];
Rudot2D(t[i], x0, args, k1);
for(j=0; j<2; j++)
x[j] = x0[j] + 0.5*dt*k1[j];
Rudot2D(t[i], x, args, k2);
for(j=0; j<2; j++)
x[j] = x0[j] + 0.5*dt*k2[j];
Rudot2D(t[i], x, args, k3);
for(j=0; j<2; j++)
x[j] = x0[j] + dt*k3[j];
Rudot2D(t[i], x, args, k4);
for(j=0; j<2; j++)
x[j] = x0[j] + dt*(k1[j]+2*k2[j]+2*k3[j]+k4[j])/6.0;
R[i+1] = x[0];
u[i+1] = x[1];
}
}
void shockEvolveSpreadRK4(double *t, double *R, double *u, double *th, int N,
double R0, double u0, double th0, void *args,
int spread)
{
int i,j;
double dt, x[3], x0[3], k1[3], k2[3], k3[3], k4[3];
R[0] = R0;
u[0] = u0;
th[0] = th0;
for(i=0; i<N-1; i++)
{
dt = t[i+1] - t[i];
x0[0] = R[i];
x0[1] = u[i];
x0[2] = th[i];
RuThdot3D(t[i], x0, args, k1, spread);
for(j=0; j<3; j++)
x[j] = x0[j] + 0.5*dt*k1[j];
RuThdot3D(t[i], x, args, k2, spread);
for(j=0; j<3; j++)
x[j] = x0[j] + 0.5*dt*k2[j];
RuThdot3D(t[i], x, args, k3, spread);
for(j=0; j<3; j++)
x[j] = x0[j] + dt*k3[j];
RuThdot3D(t[i], x, args, k4, spread);
for(j=0; j<3; j++)
x[j] = x0[j] + dt*(k1[j]+2*k2[j]+2*k3[j]+k4[j])/6.0;
R[i+1] = x[0];
u[i+1] = x[1];
if(x[2] > 0.5*M_PI)
th[i+1] = 0.5*M_PI;
else
th[i+1] = x[2];
}
}
| 16,115 | 24.7856 | 93 | c |
afterglowpy | afterglowpy-master/afterglowpy/shockEvolution.h | #ifndef AFTERGLOWPY_SHOCK
#define AFTERGLOWPY_SHOCK
static const double T0_inj = 1.0e3;
double shockVel(double u);
double E_inj(double te, double L0, double q, double ts);
double L_inj(double te, double L0, double q, double ts);
void shockInitDecel(double t0, double *R0, double *u0, void *argv);
void shockInitFind(double t0, double *R0, double *u0, double tRes, void *argv);
void Rudot2D(double t, double *x, void *argv, double *xdot);
void RuThdot3D(double t, double *x, void *argv, double *xdot, int spread);
void shockEvolveRK4(double *t, double *R, double *u, int N, double R0,
double u0, void *args);
void shockEvolveSpreadRK4(double *t, double *R, double *u, double *th, int N,
double R0, double u0, double th0, void *args,
int spread);
#endif
| 834 | 40.75 | 79 | h |
afterglowpy | afterglowpy-master/afterglowpy/shockmodule.c | #include <Python.h>
#define NPY_NO_DEPRECATED_API NPY_1_11_API_VERSION
#include <numpy/arrayobject.h>
#include "shockEvolution.h"
static char shock_docstring[] =
"This module calculates evolution of relativistic shocks.";
static char shockEvolRK4_docstring[] =
"Evolve a spherical shock with RK4";
static char shockEvolSpreadRK4_docstring[] =
"Evolve a conical shock with RK4";
static PyObject *error_out(PyObject *m);
static PyObject *shock_shockEvolRK4(PyObject *self, PyObject *args);
static PyObject *shock_shockEvolSpreadRK4(PyObject *self, PyObject *args);
struct module_state
{
PyObject *error;
};
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state *) PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif
static PyMethodDef shockMethods[] = {
{"shockEvolRK4", shock_shockEvolRK4, METH_VARARGS, shockEvolRK4_docstring},
{"shockEvolSpreadRK4", shock_shockEvolSpreadRK4, METH_VARARGS,
shockEvolSpreadRK4_docstring},
{"error_out", (PyCFunction)error_out, METH_NOARGS, NULL},
{NULL, NULL, 0, NULL}};
#if PY_MAJOR_VERSION >= 3
static int shock_traverse(PyObject *m, visitproc visit, void *arg)
{
Py_VISIT(GETSTATE(m)->error);
return 0;
}
static int shock_clear(PyObject *m)
{
Py_CLEAR(GETSTATE(m)->error);
return 0;
}
static struct PyModuleDef shockModule = {
PyModuleDef_HEAD_INIT,
"shock", /* Module Name */
shock_docstring,
sizeof(struct module_state),
shockMethods,
NULL,
shock_traverse,
shock_clear,
NULL
};
#define INITERROR return NULL
PyMODINIT_FUNC PyInit_shock(void)
#else
#define INITERROR return
void initshock(void)
#endif
{
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&shockModule);
#else
PyObject *module = Py_InitModule3("shock", shockMethods, shock_docstring);
#endif
if(module == NULL)
INITERROR;
struct module_state *st = GETSTATE(module);
st->error = PyErr_NewException("shock.Error", NULL, NULL);
if(st->error == NULL)
{
Py_DECREF(module);
INITERROR;
}
//Load numpy stuff!
import_array();
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
static PyObject *error_out(PyObject *m)
{
struct module_state *st = GETSTATE(m);
PyErr_SetString(st->error, "something bad happened");
return NULL;
}
static PyObject *shock_shockEvolRK4(PyObject *self, PyObject *args)
{
PyObject *t_obj = NULL;
double R0, u0;
double Mej, rho0, Einj, k, umin, L0, q, ts;
//Parse Arguments
if(!PyArg_ParseTuple(args, "Odddddddddd", &t_obj, &R0, &u0, &Mej, &rho0,
&Einj, &k, &umin, &L0, &q, &ts))
{
PyErr_SetString(PyExc_RuntimeError, "Could not parse arguments.");
return NULL;
}
//Grab NUMPY arrays
PyArrayObject *t_arr;
t_arr = (PyArrayObject *) PyArray_FROM_OTF(t_obj, NPY_DOUBLE,
NPY_ARRAY_IN_ARRAY);
if(t_arr == NULL)
{
PyErr_SetString(PyExc_RuntimeError, "Could not read input arrays.");
Py_XDECREF(t_arr);
return NULL;
}
int t_ndim = (int) PyArray_NDIM(t_arr);
if(t_ndim != 1)
{
PyErr_SetString(PyExc_RuntimeError, "Array must be 1-D.");
Py_DECREF(t_arr);
return NULL;
}
int N = (int)PyArray_DIM(t_arr, 0);
double *t = (double *)PyArray_DATA(t_arr);
//Allocate output array
npy_intp dims[1] = {N};
PyObject *R_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE);
PyObject *u_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE);
if(R_obj == NULL || u_obj == NULL)
{
PyErr_SetString(PyExc_RuntimeError, "Could not make output arrays.");
Py_DECREF(t_arr);
Py_XDECREF(R_obj);
Py_XDECREF(u_obj);
return NULL;
}
double *R = PyArray_DATA((PyArrayObject *) R_obj);
double *u = PyArray_DATA((PyArrayObject *) u_obj);
// Evolve the shock!
double shockArgs[9] = {u0, Mej, rho0, Einj, k, umin, L0, q, ts};
shockEvolveRK4(t, R, u, N, R0, u0, shockArgs);
// Clean up!
Py_DECREF(t_arr);
//Build output
PyObject *ret = Py_BuildValue("NN", R_obj, u_obj);
return ret;
}
static PyObject *shock_shockEvolSpreadRK4(PyObject *self, PyObject *args)
{
PyObject *t_obj = NULL;
double R0, u0, th0;
double Mej, rho0, Einj, k, umin, L0, q, ts, thC;
int spread;
//Parse Arguments
if(!PyArg_ParseTuple(args, "Oddddddddddddi", &t_obj, &R0, &u0, &th0,
&Mej, &rho0, &Einj, &k, &umin, &L0, &q, &ts,
&thC, &spread))
{
PyErr_SetString(PyExc_RuntimeError, "Could not parse arguments.");
return NULL;
}
//Grab NUMPY arrays
PyArrayObject *t_arr;
t_arr = (PyArrayObject *) PyArray_FROM_OTF(t_obj, NPY_DOUBLE,
NPY_ARRAY_IN_ARRAY);
if(t_arr == NULL)
{
PyErr_SetString(PyExc_RuntimeError, "Could not read input arrays.");
Py_XDECREF(t_arr);
return NULL;
}
int t_ndim = (int) PyArray_NDIM(t_arr);
if(t_ndim != 1)
{
PyErr_SetString(PyExc_RuntimeError, "Array must be 1-D.");
Py_DECREF(t_arr);
return NULL;
}
int N = (int)PyArray_DIM(t_arr, 0);
double *t = (double *)PyArray_DATA(t_arr);
//Allocate output arrays
npy_intp dims[1] = {N};
PyObject *R_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE);
PyObject *u_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE);
PyObject *th_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE);
if(R_obj == NULL || u_obj == NULL || th_obj == NULL)
{
PyErr_SetString(PyExc_RuntimeError, "Could not make output arrays.");
Py_DECREF(t_arr);
Py_XDECREF(R_obj);
Py_XDECREF(u_obj);
Py_XDECREF(th_obj);
return NULL;
}
double *R = PyArray_DATA((PyArrayObject *) R_obj);
double *u = PyArray_DATA((PyArrayObject *) u_obj);
double *th = PyArray_DATA((PyArrayObject *) th_obj);
// Evolve the shock!
double shockArgs[12] = {u0, Mej, rho0, Einj, k, umin, L0, q, ts, thC, th0,
thC};
shockEvolveSpreadRK4(t, R, u, th, N, R0, u0, th0, shockArgs, spread);
// Clean up!
Py_DECREF(t_arr);
//Build output
PyObject *ret = Py_BuildValue("NNN", R_obj, u_obj, th_obj);
return ret;
}
| 6,487 | 26.146444 | 79 | c |
FMM3D | FMM3D-master/c/cprini.h |
#include <stdio.h>
void cprin_init(char *str1, char *str2);
void cprin_master(char *mes, float *ap, int *afp, double *adp, char *acp, int m,
int n, int itype, char *str17, char *str27, int i1, int i2);
void cprin_all(char *mes, float *ap, int *afp, double *adp, char *acp,
int m, int n, int itype, FILE *str);
void cprinf(char *mes, int *ip, int n);
void cprind(char *mes, double *adp, int n);
void cprind_matrix(char *mes, double *adp, int m, int n);
void cprinz(char *mes, double _Complex *adp, int n);
void cprin_message(char *mes);
void cprin_skipline(int n);
void cprin_start_stop(int i1, int i2);
| 649 | 23.074074 | 80 | h |
FMM3D | FMM3D-master/c/hfmm3d_c.h | #include "utils.h"
void hfmm3d_s_c_p_(double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *pot, int *ier);
void hfmm3d_s_c_g_(double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *pot, CPX *grad, int *ier);
void hfmm3d_s_d_p_(double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, CPX *pot, int *ier);
void hfmm3d_s_d_g_(double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, CPX *pot,
CPX *grad, int *ier);
void hfmm3d_s_cd_p_(double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *dipvec, CPX *pot, int *ier);
void hfmm3d_s_cd_g_(double *eps, CPX *zk, int *nsource,
double *source, CPX* charge, CPX *dipvec, CPX *pot,
CPX *grad, int *ier);
void hfmm3d_t_c_p_(double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, int *nt, double *targ,
CPX *pottarg, int *ier);
void hfmm3d_t_c_g_(double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, int *nt, double *targ,
CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_t_d_p_(double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, int *nt, double *targ,
CPX *pottarg, int *ier);
void hfmm3d_t_d_g_(double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, int *nt, double *targ,
CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_t_cd_p_(double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *dipvec, int *nt,
double *targ, CPX *pottarg, int *ier);
void hfmm3d_t_cd_g_(double *eps, CPX *zk, int *nsource,
double *source, CPX* charge, CPX *dipvec, int *nt,
double *targ, CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_st_c_p_(double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *pot,
int *nt, double *targ, CPX *pottarg, int *ier);
void hfmm3d_st_c_g_(double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *pot, CPX *grad,
int *nt, double *targ, CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_st_d_p_(double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, CPX *pot,
int *nt, double *targ,
CPX *pottarg, int *ier);
void hfmm3d_st_d_g_(double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, CPX *pot, CPX *grad,
int *nt, double *targ,
CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_st_cd_p_(double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *dipvec, CPX *pot,
int *nt, double *targ, CPX *pottarg, int *ier);
void hfmm3d_st_cd_g_(double *eps, CPX *zk, int *nsource,
double *source, CPX* charge, CPX *dipvec, CPX *pot,
CPX *grad, int *nt,
double *targ, CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_s_c_p_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *pot, int *ier);
void hfmm3d_s_c_g_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *pot, CPX *grad, int *ier);
void hfmm3d_s_d_p_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, CPX *pot, int *ier);
void hfmm3d_s_d_g_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, CPX *pot,
CPX *grad, int *ier);
void hfmm3d_s_cd_p_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *dipvec, CPX *pot, int *ier);
void hfmm3d_s_cd_g_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX* charge, CPX *dipvec, CPX *pot,
CPX *grad, int *ier);
void hfmm3d_t_c_p_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, int *nt, double *targ,
CPX *pottarg, int *ier);
void hfmm3d_t_c_g_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, int *nt, double *targ,
CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_t_d_p_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, int *nt, double *targ,
CPX *pottarg, int *ier);
void hfmm3d_t_d_g_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, int *nt, double *targ,
CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_t_cd_p_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *dipvec, int *nt,
double *targ, CPX *pottarg, int *ier);
void hfmm3d_t_cd_g_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX* charge, CPX *dipvec, int *nt,
double *targ, CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_st_c_p_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *pot,
int *nt, double *targ, CPX *pottarg, int *ier);
void hfmm3d_st_c_g_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *pot, CPX *grad,
int *nt, double *targ, CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_st_d_p_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, CPX *pot,
int *nt, double *targ,
CPX *pottarg, int *ier);
void hfmm3d_st_d_g_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *dipvec, CPX *pot, CPX *grad,
int *nt, double *targ,
CPX *pottarg, CPX *gradtarg, int *ier);
void hfmm3d_st_cd_p_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX *charge, CPX *dipvec, CPX *pot,
int *nt, double *targ, CPX *pottarg, int *ier);
void hfmm3d_st_cd_g_vec_(int *nd, double *eps, CPX *zk, int *nsource,
double *source, CPX* charge, CPX *dipvec, CPX *pot,
CPX *grad, int *nt,
double *targ, CPX *pottarg, CPX *gradtarg, int *ier);
void h3ddirectcp_(int *nd, CPX *zk, double *source, CPX *charge, int *ns,
double *targ, int *nt, CPX *pot, double *thresh);
void h3ddirectcg_(int *nd, CPX *zk, double *source, CPX *charge, int *ns,
double *targ, int *nt, CPX *pot, CPX* grad, double *thresh);
void h3ddirectdp_(int *nd, CPX *zk, double *source, CPX *dipvec, int *ns,
double *targ, int *nt, CPX *pot, double *thresh);
void h3ddirectdg_(int *nd, CPX *zk, double *source, CPX *dipvec, int *ns,
double *targ, int *nt, CPX *pot, CPX* grad, double *thresh);
void h3ddirectcdp_(int *nd, CPX *zk, double *source, CPX *charge,
CPX *dipvec, int *ns, double *targ, int *nt, CPX *pot,
double *thresh);
void h3ddirectcdg_(int *nd, CPX *zk, double *source, CPX *charge,
CPX *dipvec, int *ns, double *targ, int *nt, CPX *pot,
CPX* grad, double *thresh);
| 7,773 | 35.669811 | 82 | h |
FMM3D | FMM3D-master/c/hfmm3d_vec_example.c | #include "stdlib.h"
#include "stdio.h"
#include "math.h"
#include "hfmm3d_c.h"
#include "complex.h"
#include "cprini.h"
int main(int argc, char **argv)
{
cprin_init("stdout", "fort.13");
cprin_skipline(2);
int ns=2000;
int nt=1999;
int nd=5;
int ier=0;
double *source = (double *)malloc(3*ns*sizeof(double));
double *targ = (double *)malloc(3*nt*sizeof(double));
CPX *charge = (CPX *)malloc(ns*nd*sizeof(CPX));
CPX *dipvec = (CPX *)malloc(3*ns*nd*sizeof(CPX));
CPX *pot = (CPX *)malloc(ns*nd*sizeof(CPX));
CPX *pottarg = (CPX *)malloc(3*ns*nd*sizeof(CPX));
// initialize arrays
for(int i=0;i<ns;i++)
{
source[3*i] = pow(rand01(),2);
source[3*i+1] = pow(rand01(),2);
source[3*i+2] = pow(rand01(),2);
}
for(int i=0;i<nd*ns;i++)
{
charge[i] = rand01() + I*rand01();
dipvec[3*i] = rand01() + I*rand01();
dipvec[3*i+1] = rand01() + I*rand01();
dipvec[3*i+2] = rand01() + I*rand01();
}
for(int i=0;i<nt;i++)
{
targ[3*i] = rand01();
targ[3*i+1] = rand01();
targ[3*i+2] = rand01();
}
double eps = 0.5e-6;
CPX zk = 1.1 + 0.01*I;
cprin_message("this code is an example c driver.");
cprin_message("on output, the code prints sample pot,pottarg");
cprin_skipline(2);
// call the fmm routine
hfmm3d_st_cd_p_vec_(&nd, &eps, &zk, &ns, source, charge, dipvec,
pot, &nt, targ, pottarg, &ier);
cprinz("pot=",pot,12);
cprinz("grad=",pottarg,12);
return 0;
}
| 1,455 | 21.75 | 67 | c |
FMM3D | FMM3D-master/c/lfmm3d_c.h | #include "utils.h"
void lfmm3d_s_c_p_(double *eps, int *nsource,
double *source, double *charge, double *pot, int *ier);
void lfmm3d_s_c_g_(double *eps, int *nsource,
double *source, double *charge, double *pot, double *grad, int *ier);
void lfmm3d_s_c_h_(double *eps, int *nsource,
double *source, double *charge, double *pot, double *grad,
double *hess, int* ier);
void lfmm3d_s_d_p_(double *eps, int *nsource,
double *source, double *dipvec, double *pot, int *ier);
void lfmm3d_s_d_g_(double *eps, int *nsource,
double *source, double *dipvec, double *pot,
double *grad, int *ier);
void lfmm3d_s_d_h_(double *eps, int *nsource,
double *source, double *dipvec, double *pot,
double *grad, double *hess, int* ier);
void lfmm3d_s_cd_p_(double *eps, int *nsource,
double *source, double *charge, double *dipvec, double *pot, int *ier);
void lfmm3d_s_cd_g_(double *eps, int *nsource,
double *source, double* charge, double *dipvec, double *pot,
double *grad, int *ier);
void lfmm3d_s_cd_h_(double *eps, int *nsource,
double *source, double* charge, double *dipvec, double *pot,
double *grad, double *hess, int* ier);
void lfmm3d_t_c_p_(double *eps, int *nsource,
double *source, double *charge, int *nt, double *targ,
double *pottarg, int *ier);
void lfmm3d_t_c_g_(double *eps, int *nsource,
double *source, double *charge, int *nt, double *targ,
double *pottarg, double *gradtarg, int *ier);
void lfmm3d_t_c_h_(double *eps, int *nsource,
double *source, double *charge, int *nt, double *targ,
double *pottarg, double *gradtarg,
double *hesstarg, int *ier);
void lfmm3d_t_d_p_(double *eps, int *nsource,
double *source, double *dipvec, int *nt, double *targ,
double *pottarg, int *ier);
void lfmm3d_t_d_g_(double *eps, int *nsource,
double *source, double *dipvec, int *nt, double *targ,
double *pottarg, double *gradtarg, int *ier);
void lfmm3d_t_d_h_(double *eps, int *nsource,
double *source, double *dipvec, int *nt, double *targ,
double *pottarg, double *gradtarg, double *hesstarg, int *ier);
void lfmm3d_t_cd_p_(double *eps, int *nsource,
double *source, double *charge, double *dipvec, int *nt,
double *targ, double *pottarg, int *ier);
void lfmm3d_t_cd_g_(double *eps, int *nsource,
double *source, double* charge, double *dipvec, int *nt,
double *targ, double *pottarg, double *gradtarg, int *ier);
void lfmm3d_t_cd_h_(double *eps, int *nsource,
double *source, double* charge, double *dipvec, int *nt,
double *targ, double *pottarg, double *gradtarg,
double *hesstarg, int *ier);
void lfmm3d_st_c_p_(double *eps, int *nsource,
double *source, double *charge, double *pot,
int *nt, double *targ, double *pottarg, int *ier);
void lfmm3d_st_c_g_(double *eps, int *nsource,
double *source, double *charge, double *pot, double *grad,
int *nt, double *targ, double *pottarg, double *gradtarg, int *ier);
void lfmm3d_st_c_h_(double *eps, int *nsource,
double *source, double *charge, double *pot, double *grad,
double *hess, int *nt, double *targ, double *pottarg,
double *gradtarg, double *hesstarg, int *ier);
void lfmm3d_st_d_p_(double *eps, int *nsource,
double *source, double *dipvec, double *pot,
int *nt, double *targ,
double *pottarg, int *ier);
void lfmm3d_st_d_g_(double *eps, int *nsource,
double *source, double *dipvec, double *pot, double *grad,
int *nt, double *targ,
double *pottarg, double *gradtarg, int *ier);
void lfmm3d_st_d_h_(double *eps, int *nsource,
double *source, double *dipvec, double *pot, double *grad,
double *hess, int *nt, double *targ,
double *pottarg, double *gradtarg,
double *hesstarg, int *ier);
void lfmm3d_st_cd_p_(double *eps, int *nsource,
double *source, double *charge, double *dipvec, double *pot,
int *nt, double *targ, double *pottarg, int *ier);
void lfmm3d_st_cd_g_(double *eps, int *nsource,
double *source, double* charge, double *dipvec, double *pot,
double *grad, int *nt,
double *targ, double *pottarg, double *gradtarg, int *ier);
void lfmm3d_st_cd_h_(double *eps, int *nsource,
double *source, double* charge, double *dipvec, double *pot,
double *grad, double *hess, int *nt,
double *targ, double *pottarg, double *gradtarg,
double *hesstarg, int *ier);
void lfmm3d_s_c_p_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, double *pot, int *ier);
void lfmm3d_s_c_g_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, double *pot, double *grad, int *ier);
void lfmm3d_s_c_h_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, double *pot, double *grad,
double *hess, int* ier);
void lfmm3d_s_d_p_vec_(int *nd, double *eps, int *nsource,
double *source, double *dipvec, double *pot, int *ier);
void lfmm3d_s_d_g_vec_(int *nd, double *eps, int *nsource,
double *source, double *dipvec, double *pot,
double *grad, int *ier);
void lfmm3d_s_d_h_vec_(int *nd, double *eps, int *nsource,
double *source, double *dipvec, double *pot,
double *grad, double *hess, int* ier);
void lfmm3d_s_cd_p_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, double *dipvec, double *pot, int *ier);
void lfmm3d_s_cd_g_vec_(int *nd, double *eps, int *nsource,
double *source, double* charge, double *dipvec, double *pot,
double *grad, int *ier);
void lfmm3d_s_cd_h_vec_(int *nd, double *eps, int *nsource,
double *source, double* charge, double *dipvec, double *pot,
double *grad, double *hess, int* ier);
void lfmm3d_t_c_p_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, int *nt, double *targ,
double *pottarg, int *ier);
void lfmm3d_t_c_g_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, int *nt, double *targ,
double *pottarg, double *gradtarg, int *ier);
void lfmm3d_t_c_h_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, int *nt, double *targ,
double *pottarg, double *gradtarg,
double *hesstarg, int *ier);
void lfmm3d_t_d_p_vec_(int *nd, double *eps, int *nsource,
double *source, double *dipvec, int *nt, double *targ,
double *pottarg, int *ier);
void lfmm3d_t_d_g_vec_(int *nd, double *eps, int *nsource,
double *source, double *dipvec, int *nt, double *targ,
double *pottarg, double *gradtarg, int *ier);
void lfmm3d_t_d_h_vec_(int *nd, double *eps, int *nsource,
double *source, double *dipvec, int *nt, double *targ,
double *pottarg, double *gradtarg, double *hesstarg, int *ier);
void lfmm3d_t_cd_p_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, double *dipvec, int *nt,
double *targ, double *pottarg, int *ier);
void lfmm3d_t_cd_g_vec_(int *nd, double *eps, int *nsource,
double *source, double* charge, double *dipvec, int *nt,
double *targ, double *pottarg, double *gradtarg, int *ier);
void lfmm3d_t_cd_h_vec_(int *nd, double *eps, int *nsource,
double *source, double* charge, double *dipvec, int *nt,
double *targ, double *pottarg, double *gradtarg,
double *hesstarg, int *ier);
void lfmm3d_st_c_p_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, double *pot,
int *nt, double *targ, double *pottarg, int *ier);
void lfmm3d_st_c_g_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, double *pot, double *grad,
int *nt, double *targ, double *pottarg, double *gradtarg, int *ier);
void lfmm3d_st_c_h_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, double *pot, double *grad,
double *hess, int *nt, double *targ, double *pottarg,
double *gradtarg, double *hesstarg, int *ier);
void lfmm3d_st_d_p_vec_(int *nd, double *eps, int *nsource,
double *source, double *dipvec, double *pot,
int *nt, double *targ,
double *pottarg, int *ier);
void lfmm3d_st_d_g_vec_(int *nd, double *eps, int *nsource,
double *source, double *dipvec, double *pot, double *grad,
int *nt, double *targ,
double *pottarg, double *gradtarg, int *ier);
void lfmm3d_st_d_h_vec_(int *nd, double *eps, int *nsource,
double *source, double *dipvec, double *pot, double *grad,
double *hess, int *nt, double *targ,
double *pottarg, double *gradtarg,
double *hesstarg, int *ier);
void lfmm3d_st_cd_p_vec_(int *nd, double *eps, int *nsource,
double *source, double *charge, double *dipvec, double *pot,
int *nt, double *targ, double *pottarg, int *ier);
void lfmm3d_st_cd_g_vec_(int *nd, double *eps, int *nsource,
double *source, double* charge, double *dipvec, double *pot,
double *grad, int *nt,
double *targ, double *pottarg, double *gradtarg, int *ier);
void lfmm3d_st_cd_h_vec_(int *nd, double *eps, int *nsource,
double *source, double* charge, double *dipvec, double *pot,
double *grad, double *hess, int *nt,
double *targ, double *pottarg, double *gradtarg,
double *hesstarg, int *ier);
void l3ddirectcp_(int *nd, double *source, double *charge, int *ns,
double *targ, int *nt, double *pot, double *thresh);
void l3ddirectcg_(int *nd, double *source, double *charge, int *ns,
double *targ, int *nt, double *pot, double* grad, double *thresh);
void l3ddirectch_(int *nd, double *source, double *charge, int *ns,
double *targ, int *nt, double *pot, double* grad,
double *hess, double *thresh);
void l3ddirectdp_(int *nd, double *source, double *dipvec, int *ns,
double *targ, int *nt, double *pot, double *thresh);
void l3ddirectdg_(int *nd, double *source, double *dipvec, int *ns,
double *targ, int *nt, double *pot, double* grad, double *thresh);
void l3ddirectdh_(int *nd, double *source, double *dipvec, int *ns,
double *targ, int *nt, double *pot, double* grad,
double *hess, double *thresh);
void l3ddirectcdp_(int *nd, double *source, double *charge,
double *dipvec, int *ns, double *targ, int *nt, double *pot,
double *thresh);
void l3ddirectcdg_(int *nd, double *source, double *charge,
double *dipvec, int *ns, double *targ, int *nt, double *pot,
double* grad, double *thresh);
void l3ddirectcdh_(int *nd, double *source, double *charge,
double *dipvec, int *ns, double *targ, int *nt, double *pot,
double* grad, double *hess, double *thresh);
| 12,636 | 39.764516 | 91 | h |
FMM3D | FMM3D-master/c/lfmm3d_vec_example.c | #include "stdlib.h"
#include "stdio.h"
#include "math.h"
#include "lfmm3d_c.h"
#include "complex.h"
#include "cprini.h"
int main(int argc, char **argv)
{
cprin_init("stdout", "fort.13");
cprin_skipline(2);
int ns=2000;
int nt=1999;
int nd=5;
int ier=0;
double *source = (double *)malloc(3*ns*sizeof(double));
double *targ = (double *)malloc(3*nt*sizeof(double));
double *charge = (double *)malloc(ns*nd*sizeof(double));
double *dipvec = (double *)malloc(3*ns*nd*sizeof(double));
double *pot = (double *)malloc(ns*nd*sizeof(double));
double *pottarg = (double *)malloc(3*ns*nd*sizeof(double));
// initialize arrays
for(int i=0;i<ns;i++)
{
source[3*i] = pow(rand01(),2);
source[3*i+1] = pow(rand01(),2);
source[3*i+2] = pow(rand01(),2);
}
for(int i=0;i<nd*ns;i++)
{
charge[i] = rand01();
dipvec[3*i] = rand01();
dipvec[3*i+1] = rand01();
dipvec[3*i+2] = rand01();
}
for(int i=0;i<nt;i++)
{
targ[3*i] = rand01();
targ[3*i+1] = rand01();
targ[3*i+2] = rand01();
}
double eps = 0.5e-6;
cprin_message("this code is an example c driver.");
cprin_message("on output, the code prints sample pot,pottarg");
cprin_skipline(2);
// call the fmm routine
lfmm3d_st_cd_p_vec_(&nd, &eps, &ns, source, charge, dipvec,
pot, &nt, targ, pottarg, &ier);
cprind("pot=",pot,12);
cprind("grad=",pottarg,12);
return 0;
}
| 1,410 | 21.396825 | 65 | c |
FMM3D | FMM3D-master/c/utils.h | #ifndef UTILS_H
#define UTILS_H
#include <stdint.h>
#include <complex.h>
typedef double complex CPX;
#define rand01() ((double)rand()/RAND_MAX)
void dzero(int n, double *a);
void czero(int n, CPX *a);
void comp_err_helm(int n,int pg, int pgt, CPX *pot, CPX *potex, CPX *pottarg, CPX *pottargex,
CPX *grad, CPX *gradex, CPX *gradtarg, CPX *gradtargex, double *err);
void comp_err_lap(int n,int pg, int pgt, double *pot, double *potex,
double *pottarg, double *pottargex, double *grad,
double *gradex, double *gradtarg, double *gradtargex,
double *hess, double *hessex, double *hesstarg,
double *hesstargex, double *err);
#endif
| 683 | 30.090909 | 93 | h |
FMM3D | FMM3D-master/vec-kernels/include/sctl/stacktrace.h | #ifndef _SCTL_STACKTRACE_H_
#define _SCTL_STACKTRACE_H_
#include <sctl/common.hpp>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <cxxabi.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
namespace SCTL_NAMESPACE {
inline void print_stacktrace(FILE* out = stderr, int skip = 1) {
// Get addresses
void* addrlist[256];
int addrlen = backtrace(addrlist, 255);
for (int i = 0; i < addrlen; i++) addrlist[i] = (char*)addrlist[i] - 1;
// Get symbols
char** symbollist = backtrace_symbols(addrlist, addrlen);
// Get filename
char fname[10240];
#ifdef __APPLE__
uint32_t size = sizeof(fname);
_NSGetExecutablePath(fname, &size);
#elif __linux__
ssize_t fname_len = ::readlink("/proc/self/exe", fname, sizeof(fname) - 1);
fname[fname_len] = '\0';
#endif
// Print
for (int i = skip; i < addrlen; i++) {
// Get command
char cmd[10240+256+43];
#ifdef __APPLE__
sprintf(cmd, "atos -o %s %p 2> /dev/null", fname, addrlist[i]); // on mac
#elif __linux__
sprintf(cmd, "addr2line -f -C -i -e %s %p 2> /dev/null", fname, addrlist[i]);
#endif
// Execute command
FILE* pipe = popen(cmd, "r");
if (!pipe) continue;
char buffer0[10240];
char buffer1[10240];
char* fgets_ret0 = fgets(buffer0, sizeof(buffer0) - 1, pipe);
char* fgets_ret1 = fgets(buffer1, sizeof(buffer1) - 1, pipe);
for (int j = 0; j < (int)sizeof(buffer0) - 1; j++) {
if (buffer0[j] == '\n') buffer0[j] = ' ';
}
for (int j = 0; j < (int)sizeof(buffer1) - 1; j++) {
if (buffer1[j] == '\n') buffer1[j] = ' ';
}
pclose(pipe);
// Print output
if (fgets_ret0 != nullptr && fgets_ret1 != nullptr && buffer0[0] != '?' && buffer0[0] != '\0') {
fprintf(out, "[%d] %s: %s\n", i - skip, buffer1, buffer0);
} else {
fprintf(out, "[%d] %p: %s\n", i - skip, addrlist[i], symbollist[i]);
}
}
fprintf(stderr, "\n");
}
inline void abortHandler(int signum, siginfo_t* si, void* unused) {
static bool first_time = true;
SCTL_UNUSED(unused);
SCTL_UNUSED(si);
#pragma omp critical(SCTL_STACK_TRACE)
if (first_time) {
first_time = false;
const char* name = nullptr;
switch (signum) {
case SIGABRT:
name = "SIGABRT";
break;
case SIGSEGV:
name = "SIGSEGV";
break;
case SIGBUS:
name = "SIGBUS";
break;
case SIGILL:
name = "SIGILL";
break;
case SIGFPE:
name = "SIGFPE";
break;
}
if (name)
fprintf(stderr, "\nCaught signal %d (%s)\n", signum, name);
else
fprintf(stderr, "\nCaught signal %d\n", signum);
print_stacktrace(stderr, 2);
}
exit(signum);
}
inline int SetSigHandler() {
struct sigaction sa;
sa.sa_flags = SA_RESTART | SA_SIGINFO;
sa.sa_sigaction = abortHandler;
sigemptyset(&sa.sa_mask);
sigaction(SIGABRT, &sa, nullptr);
sigaction(SIGSEGV, &sa, nullptr);
sigaction(SIGBUS, &sa, nullptr);
sigaction(SIGILL, &sa, nullptr);
sigaction(SIGFPE, &sa, nullptr);
sigaction(SIGPIPE, &sa, nullptr);
return 0;
}
} // end namespace
#endif // _SCTL_STACKTRACE_H_
| 3,186 | 23.898438 | 100 | h |
sentencepiece | sentencepiece-master/src/bpe_model.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef BPE_MODEL_H_
#define BPE_MODEL_H_
#include "model_interface.h"
#include "sentencepiece_model.pb.h"
namespace sentencepiece {
namespace bpe {
// Segmentation model with BPE (Byte Pair Encoding)
// Details:
// Neural Machine Translation of Rare Words with Subword Units
// https://arxiv.org/abs/1508.07909
//
// https://en.wikipedia.org/wiki/Byte_pair_encoding
class Model : public ModelInterface {
public:
explicit Model(const ModelProto &model_proto);
~Model() override;
EncodeResult Encode(absl::string_view normalized) const override {
return SampleEncode(normalized, 0.0);
}
// Sampling with BPE-dropout: https://arxiv.org/pdf/1910.13267.pdf
// `alpha` is dropout probability in BPE-dropout paper.
// Skips merge operation with `alpha` probability.
// When alpha <= 0.0, no sampling is performed.
EncodeResult SampleEncode(absl::string_view normalized,
float alpha) const override;
bool IsSampleEncodeAvailable() const override { return true; }
bool IsNBestEncodeAvailable() const override { return false; }
};
} // namespace bpe
} // namespace sentencepiece
#endif // BPE_MODEL_H_
| 1,748 | 32 | 75 | h |
sentencepiece | sentencepiece-master/src/bpe_model_trainer.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef BPE_MODEL_TRAINER_H_
#define BPE_MODEL_TRAINER_H_
#include <cstdint>
#include <limits>
#include <set>
#include <string>
#include <vector>
#include "sentencepiece_model.pb.h"
#include "third_party/absl/container/flat_hash_map.h"
#include "trainer_interface.h"
namespace sentencepiece {
namespace bpe {
// Trainer class for BPE model.
class Trainer : public TrainerInterface {
public:
Trainer(const TrainerSpec &trainer_spec,
const NormalizerSpec &normalizer_spec,
const NormalizerSpec &denormalizer_spec)
: TrainerInterface::TrainerInterface(trainer_spec, normalizer_spec,
denormalizer_spec) {}
util::Status Train() override;
private:
// Symbol represents a character or symbol bigram.
struct Symbol {
const Symbol *left; // left symbol in bigram
const Symbol *right; // right symbol in bigram
string_util::UnicodeText chars; // all flattend chracter sequence
bool is_unk; // true if this symbol is unknown.
uint64_t fp; // fingerprint of this symbol.
uint64_t freq; // frequency of this symbol.
// Position list. Use set so that we can keep the order of occurrence.
// See EncodePos/DecodePos.
std::set<uint64_t> positions;
bool IsBigram() const { return left != nullptr && right != nullptr; }
std::string ToString() const;
Symbol() : left(nullptr), right(nullptr), is_unk(false), fp(0), freq(0) {}
};
struct Position {
int sid; // sentence id
int left; // left symbol index
int right; // right symbol index
};
// Encodes sid, left and right bigram index into uint64_t.
// Encoded value keeps the order of sid, left and right.
static uint64_t EncodePos(int sid, int l, int r) {
CHECK_GE(l, 0);
CHECK_GE(r, 0);
CHECK_LE(l, std::numeric_limits<uint16_t>::max());
CHECK_LE(r, std::numeric_limits<uint16_t>::max());
const uint64_t n = (static_cast<uint64_t>(sid) << 32) |
(static_cast<uint64_t>(l) << 16) |
r;
return n;
}
// Decodes sid, left and right bigram index from uint64_t.
static Position DecodePos(uint64_t n) {
Position p;
p.sid = n >> 32;
p.left = (n >> 16) & 0xffff;
p.right = n & 0xffff;
return p;
}
// Gets unary (character) symbol from the char code |c|.
// The return value is cached.
Symbol *GetCharSymbol(char32 c);
// Gets symbol pair from left/right symbols. The return value is cached.
Symbol *GetPairSymbol(const Symbol *left, const Symbol *right);
// Computes the frequency of |symbol| and update symbol->freq field.
void ComputeFreq(Symbol *symbol) const;
// Returns the valid index before symbols_[sid][index].
int GetNextIndex(int sid, int index) const;
// Returns the valid index after symbols_[sid][index].
int GetPrevIndex(int sid, int index) const;
// Makes a new bigram from [symbols_[sid][left], symbols_[sid][right]] and
// Adds it to symbols_cache_ and active_symbols_.
void AddNewPair(int sid, int left, int right);
// Resets the fequency of bigram [symbols_[sid][left] symbols_[sid][right]],
// if this bigram is not |best|.
void ResetFreq(int sid, int left, int right, const Symbol *best);
// Updates |active_symbols_| by copying the top 5% frequent symbols in
// symbols_cache_.
void UpdateActiveSymbols();
// All unique symbols. Key is a fingerprint of Symbol.
absl::flat_hash_map<uint64_t, Symbol *> symbols_cache_;
// Set of symbols from which we find the best symbol in each iteration.
std::set<Symbol *> active_symbols_;
// Stores symbols allocated in heap so that we can delete them at onece.
std::vector<Symbol *> allocated_;
// Sentences. symbols_[sid][index] stores a symbol in sentence_[sid][index].
std::vector<std::vector<Symbol *>> symbols_;
};
} // namespace bpe
} // namespace sentencepiece
#endif // BPE_MODEL_TRAINER_H_
| 4,590 | 33.780303 | 78 | h |
sentencepiece | sentencepiece-master/src/builder.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef BUILDER_H_
#define BUILDER_H_
#include <map>
#include <string>
#include <vector>
#include "common.h"
#include "sentencepiece_model.pb.h"
#include "sentencepiece_processor.h"
#include "third_party/absl/strings/string_view.h"
namespace sentencepiece {
namespace normalizer {
// Builder creates a text normalization rule from user-defined string
// to string mappings. The normalization mapping is compiled into
// a single and compact blob index which is stored into the model proto.
// This class also provides pre-defined rules based on Unicode NFKC.
// https://en.wikipedia.org/wiki/Unicode_equivalence#Normalization
class Builder {
public:
Builder() = delete;
~Builder() = delete;
// Basic Unicode character sequence.
using Chars = std::vector<char32>;
// String-to-string mapping.
using CharsMap = std::map<Chars, Chars>;
static util::Status CompileCharsMap(const CharsMap &chars_map,
std::string *output);
// Decompiles `blob` into `chars_map`.
static util::Status DecompileCharsMap(absl::string_view blob,
CharsMap *chars_map);
// Returns a pre-compiled binary index with `name`.
static util::Status GetPrecompiledCharsMap(absl::string_view name,
std::string *output);
// Makes a normalization mapping based on NFKC.
//
// Note that Normalizer/Builder classes do not support
// full NFKC normalization, since full NFKC normalization cannot
// be implemented with a simple longest matching string-to-string
// replacement. One unsupported normalization is multiple combining
// marks.
//
// Strings with multiple combining marks cannot correctly
// be normalized, because it needs to sort the combining marks
// with Canonical_Combining_Class (CCC).
// http://unicode.org/reports/tr15/#Multiple_Mark_Figure
//
// Example:
// Original: U+1E0B U+0323
// Decomposed: U+0064 U+0307 U+0323
// NFKD: U+0064 U+0323 U+0307 (Combining characters are sorted by CCC)
// NFKC: U+1E0D U+0307 (U+0064 U+0323 => U+1E0D)
//
// To support the normalization above with a longest matching, we need to
// enumerate all possible permutations of combining marks in advance,
// which is not feasible. For example, suppose the case there are three
// combining marks X, Y and Z, which are sorted into one canonical order
// Z, Y, X with NFK(D|C). In this case, all permutations (XYZ, XZY, YXZ...)
// are normalized into ZYX. When we implement this normalization with
// a longest matching, we need to have 3! rules. XYZ=>ZYX, XZY=>ZYX..
// Since Unicode has more than 100 combining characters, it is not possible
// to expand all permutations.
//
// We will not implement the full NFKC in SentencePiece because
// 1) It is unusual to see decomposed Unicode characters in real text.
// 2) Providing a flexible, user-customizable, and self-contained
// normalizer is the goal of SentencePiece.
//
// TODO(taku): Make NFC, NFD, and NFKD mapping if necessary.
static util::Status BuildNFKCMap(CharsMap *chars_map);
// Makes an NFKC-based mapping with NMT specific modifications around
// whitespaces.
static util::Status BuildNmtNFKCMap(CharsMap *chars_map);
// Merge Unicode case folding mapping into `chars_map`.
static util::Status MergeUnicodeCaseFoldMap(CharsMap *chars_map);
// Makes NFKC with Unicode case folding.
static util::Status BuildNFKC_CFMap(CharsMap *chars_map);
// Makes NMT NFKC with Unicode case folding.
static util::Status BuildNmtNFKC_CFMap(CharsMap *chars_map);
// Given NFKC maps, convert them to NFKD.
static util::Status BuildNFKDMap(CharsMap *chars_map);
// Builds Chars map save in `filename`.
// Format:
// src_uchar1 src_uchar2 ... <tab> trg_uchar1 trg_uchar2...
// (src|trg)_ucharX must be a hex of Unicode code point.
static util::Status LoadCharsMap(absl::string_view filename,
CharsMap *chars_map);
// Saves Chars map to `filename` as TSV.
static util::Status SaveCharsMap(absl::string_view filename,
const CharsMap &chars_map);
private:
FRIEND_TEST(BuilderTest, RemoveRedundantMapTest);
// Removes redundant rules from `chars_map`.
// When char_maps have "aa" => "bb" and "a" => "b", the first
// rule is not necessary since the second rule can cover the first rule.
static util::Status RemoveRedundantMap(CharsMap *chars_map);
};
} // namespace normalizer
} // namespace sentencepiece
#endif // BUILDER_H_
| 5,203 | 38.424242 | 80 | h |
sentencepiece | sentencepiece-master/src/char_model.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef CHAR_MODEL_H_
#define CHAR_MODEL_H_
#include "model_interface.h"
#include "sentencepiece_model.pb.h"
namespace sentencepiece {
namespace character {
// Tokenize text into character sequence
class Model : public ModelInterface {
public:
explicit Model(const ModelProto &model_proto);
~Model() override;
EncodeResult Encode(absl::string_view normalized) const override;
};
} // namespace character
} // namespace sentencepiece
#endif // CHAR_MODEL_H_
| 1,061 | 29.342857 | 75 | h |
sentencepiece | sentencepiece-master/src/char_model_trainer.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef CHAR_MODEL_TRAINER_H_
#define CHAR_MODEL_TRAINER_H_
#include "sentencepiece_model.pb.h"
#include "trainer_interface.h"
namespace sentencepiece {
namespace character {
// Trainer class for character model.
class Trainer : public TrainerInterface {
public:
Trainer(const TrainerSpec &trainer_spec,
const NormalizerSpec &normalizer_spec,
const NormalizerSpec &denormalizer_spec)
: TrainerInterface::TrainerInterface(trainer_spec, normalizer_spec,
denormalizer_spec) {}
util::Status Train() override;
};
} // namespace character
} // namespace sentencepiece
#endif // CHAR_MODEL_TRAINER_H_
| 1,265 | 32.315789 | 75 | h |
sentencepiece | sentencepiece-master/src/common.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef COMMON_H_
#define COMMON_H_
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "config.h"
#include "third_party/absl/strings/string_view.h"
#if defined(_WIN32) && !defined(__CYGWIN__)
#define OS_WIN
#else
#define OS_UNIX
#endif
#ifdef OS_WIN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t char32;
typedef uint32_t uint32;
typedef uint64_t uint64;
static constexpr uint32 kUnicodeError = 0xFFFD;
#if defined(OS_WIN) && defined(UNICODE) && defined(_UNICODE)
#define WPATH(path) (::sentencepiece::win32::Utf8ToWide(path).c_str())
#else
#define WPATH(path) (path)
#endif
template <typename T, size_t N>
char (&ArraySizeHelper(T (&array)[N]))[N];
#ifndef _MSC_VER
template <typename T, size_t N>
char (&ArraySizeHelper(const T (&array)[N]))[N];
#endif // !_MSC_VER
#define arraysize(array) (sizeof(ArraySizeHelper(array)))
#if defined(_FREEBSD)
#include <sys/endian.h>
#endif
#if !defined(__APPLE__) && !defined(_WIN32) && !defined(_FREEBSD)
#include <endian.h>
#if BYTE_ORDER == __BIG_ENDIAN
#define IS_BIG_ENDIAN
#endif
#endif
namespace sentencepiece {
#ifdef OS_WIN
namespace win32 {
std::wstring Utf8ToWide(const absl::string_view input);
} // namespace win32
#endif
#ifdef IS_BIG_ENDIAN
namespace util {
inline uint32 Swap32(uint32 x) { return __builtin_bswap32(x); }
} // namespace util
#endif
namespace error {
void Abort();
void Exit(int code);
void SetTestCounter(int c);
void ResetTestMode();
bool GetTestCounter();
class Die {
public:
explicit Die(bool die) : die_(die) {}
~Die() {
std::cerr << std::endl;
if (die_) {
Abort();
}
}
int operator&(std::ostream &) { return 0; }
private:
bool die_;
};
} // namespace error
namespace logging {
enum LogSeverity {
LOG_INFO = 0,
LOG_WARNING = 1,
LOG_ERROR = 2,
LOG_FATAL = 3,
LOG_SEVERITY_SIZE = 4,
};
int GetMinLogLevel();
void SetMinLogLevel(int v);
inline const char *BaseName(const char *path) {
#ifdef OS_WIN
const char *p = strrchr(path, '\\');
#else
const char *p = strrchr(path, '/');
#endif
if (p == nullptr) return path;
return p + 1;
}
} // namespace logging
} // namespace sentencepiece
#define LOG(severity) \
(::sentencepiece::logging::GetMinLogLevel() > \
::sentencepiece::logging::LOG_##severity) \
? 0 \
: ::sentencepiece::error::Die( \
::sentencepiece::logging::LOG_##severity >= \
::sentencepiece::logging::LOG_FATAL) & \
std::cerr << ::sentencepiece::logging::BaseName(__FILE__) << "(" \
<< __LINE__ << ") " \
<< "LOG(" << #severity << ") "
#define CHECK(condition) \
(condition) ? 0 \
: ::sentencepiece::error::Die(true) & \
std::cerr << ::sentencepiece::logging::BaseName(__FILE__) \
<< "(" << __LINE__ << ") [" << #condition \
<< "] "
#define CHECK_STREQ(a, b) CHECK_EQ(std::string(a), std::string(b))
#define CHECK_EQ(a, b) CHECK((a) == (b))
#define CHECK_NE(a, b) CHECK((a) != (b))
#define CHECK_GE(a, b) CHECK((a) >= (b))
#define CHECK_LE(a, b) CHECK((a) <= (b))
#define CHECK_GT(a, b) CHECK((a) > (b))
#define CHECK_LT(a, b) CHECK((a) < (b))
#define FRIEND_TEST(a, b) friend class a##_Test_##b;
#define CHECK_OK(expr) \
do { \
const auto _status = expr; \
CHECK(_status.ok()) << _status.ToString(); \
} while (0)
#define CHECK_NOT_OK(expr) \
do { \
const auto _status = expr; \
CHECK(!_status.ok()) << _status.ToString(); \
} while (0)
#define RETURN_IF_ERROR(expr) \
do { \
const auto _status = expr; \
if (!_status.ok()) return _status; \
} while (0)
#endif // COMMON_H_
| 5,206 | 26.405263 | 79 | h |
sentencepiece | sentencepiece-master/src/filesystem.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef FILESYSTEM_H_
#define FILESYSTEM_H_
#include <stdio.h>
#include <fstream>
#include <memory>
#include <string>
#include "common.h"
#include "sentencepiece_processor.h"
#include "third_party/absl/strings/string_view.h"
namespace sentencepiece {
namespace filesystem {
class ReadableFile {
public:
ReadableFile() {}
explicit ReadableFile(absl::string_view filename, bool is_binary = false) {}
virtual ~ReadableFile() {}
virtual util::Status status() const = 0;
virtual bool ReadLine(std::string *line) = 0;
virtual bool ReadAll(std::string *line) = 0;
};
class WritableFile {
public:
WritableFile() {}
explicit WritableFile(absl::string_view filename, bool is_binary = false) {}
virtual ~WritableFile() {}
virtual util::Status status() const = 0;
virtual bool Write(absl::string_view text) = 0;
virtual bool WriteLine(absl::string_view text) = 0;
};
std::unique_ptr<ReadableFile> NewReadableFile(absl::string_view filename,
bool is_binary = false);
std::unique_ptr<WritableFile> NewWritableFile(absl::string_view filename,
bool is_binary = false);
} // namespace filesystem
} // namespace sentencepiece
#endif // FILESYSTEM_H_
| 1,852 | 29.883333 | 78 | h |
sentencepiece | sentencepiece-master/src/freelist.h | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef FREELIST_H_
#define FREELIST_H_
#include <string.h>
#include <vector>
namespace sentencepiece {
namespace model {
// Simple FreeList that allocates a chunk of T at once.
template <class T>
class FreeList {
public:
FreeList() = delete;
explicit FreeList(size_t chunk_size) : chunk_size_(chunk_size) {}
virtual ~FreeList() {
for (auto& chunk : freelist_) delete[] chunk;
}
// `Free` doesn't free the object but reuse the allocated memory chunks.
void Free() {
const int size = std::min<int>(chunk_index_ + 1, freelist_.size());
for (int i = 0; i < size; ++i) {
T* chunk = freelist_[i];
memset(static_cast<void*>(chunk), 0, sizeof(*chunk) * chunk_size_);
}
chunk_index_ = 0;
element_index_ = 0;
}
// Returns the number of allocated elements.
size_t size() const { return chunk_size_ * chunk_index_ + element_index_; }
void swap(FreeList<T>& other) {
std::swap(freelist_, other.freelist_);
std::swap(element_index_, other.element_index_);
std::swap(chunk_index_, other.chunk_index_);
std::swap(chunk_size_, other.chunk_size_);
}
// Returns the element as an array.
T* operator[](size_t index) const {
return freelist_[index / chunk_size_] + index % chunk_size_;
}
// Allocates new element.
T* Allocate() {
if (element_index_ >= chunk_size_) {
++chunk_index_;
element_index_ = 0;
}
if (chunk_index_ == freelist_.size()) {
T* chunk = new T[chunk_size_];
memset(static_cast<void*>(chunk), 0, sizeof(*chunk) * chunk_size_);
freelist_.push_back(chunk);
}
T* result = freelist_[chunk_index_] + element_index_;
++element_index_;
return result;
}
private:
std::vector<T*> freelist_;
// The last element is stored at freelist_[chunk_index_][element_index_]
size_t element_index_ = 0;
size_t chunk_index_ = 0;
size_t chunk_size_ = 0; // Do not modify except in swap()
};
} // namespace model
} // namespace sentencepiece
#endif // FREELIST_H_
| 2,605 | 27.637363 | 77 | h |
sentencepiece | sentencepiece-master/src/init.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef INIT_H_
#define INIT_H_
#include "common.h"
#include "third_party/absl/flags/flag.h"
#include "third_party/absl/flags/parse.h"
#ifdef _USE_EXTERNAL_PROTOBUF
#include "google/protobuf/message_lite.h"
#else
#include "third_party/protobuf-lite/google/protobuf/message_lite.h"
#endif
ABSL_DECLARE_FLAG(int32, minloglevel);
namespace sentencepiece {
inline void ParseCommandLineFlags(const char *usage, int *argc, char ***argv,
bool remove_arg = true) {
const auto unused_args = absl::ParseCommandLine(*argc, *argv);
if (remove_arg) {
char **argv_val = *argv;
*argv = argv_val = argv_val + *argc - unused_args.size();
std::copy(unused_args.begin(), unused_args.end(), argv_val);
*argc = static_cast<int>(unused_args.size());
}
logging::SetMinLogLevel(absl::GetFlag(FLAGS_minloglevel));
}
inline void ShutdownLibrary() {
google::protobuf::ShutdownProtobufLibrary();
#ifdef HAS_ABSL_CLEANUP_FLAGS
absl::CleanupFlags();
#endif
}
class ScopedResourceDestructor {
public:
ScopedResourceDestructor() {}
~ScopedResourceDestructor() { ShutdownLibrary(); }
};
} // namespace sentencepiece
#endif // INIT_H_
| 1,770 | 28.032787 | 77 | h |
sentencepiece | sentencepiece-master/src/model_factory.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef MODEL_FACTORY_H_
#define MODEL_FACTORY_H_
#include <memory>
#include "model_interface.h"
#include "sentencepiece_model.pb.h"
namespace sentencepiece {
class ModelFactory {
public:
// Creates Model instance from |model_proto|.
static std::unique_ptr<ModelInterface> Create(const ModelProto &model_proto);
};
} // namespace sentencepiece
#endif // MODEL_FACTORY_H_
| 972 | 29.40625 | 79 | h |
sentencepiece | sentencepiece-master/src/model_interface.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef MODEL_INTERFACE_H_
#define MODEL_INTERFACE_H_
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "common.h"
#include "normalizer.h"
#include "sentencepiece_model.pb.h"
#include "sentencepiece_processor.h"
#include "third_party/absl/container/flat_hash_map.h"
#include "third_party/absl/strings/string_view.h"
#include "third_party/darts_clone/darts.h"
#include "util.h"
namespace sentencepiece {
// "_this_is_a_pen" => ["_this", "_is", "_a", "_pen"]
std::vector<absl::string_view> SplitIntoWords(
absl::string_view text, bool treat_ws_as_suffix = false,
bool allow_ws_only_pieces = false);
// Converts byte (0-255) to piece (e.g., 58 -> "<0x3A>").
std::string ByteToPiece(unsigned char c);
// Converts piece to byte (e.g., "<0x3A>" -> 58). Returns -1 if `piece` is not
// a valid byte piece.
int PieceToByte(absl::string_view piece);
using EncodeResult = std::vector<std::pair<absl::string_view, int>>;
using NBestEncodeResult = std::vector<std::pair<EncodeResult, float>>;
class ModelProto;
// Underlying model interface.
// Given a normalized string, returns a sequence of sentence pieces with ids.
class ModelInterface {
public:
using PieceToIdMap = absl::flat_hash_map<absl::string_view, int>;
// string_util::string_view_hash>;
absl::string_view unk_piece() const;
absl::string_view bos_piece() const;
absl::string_view eos_piece() const;
absl::string_view pad_piece() const;
// `model_proto` should not be deleted until ModelInterface is destroyed.
explicit ModelInterface(const ModelProto &model_proto);
ModelInterface() {}
virtual ~ModelInterface();
// Returns Status.
// Encode/Decode functions are valid only when status is OK.
virtual util::Status status() const { return status_; }
virtual const ModelProto &model_proto() const { return *model_proto_; }
virtual const normalizer::PrefixMatcher *prefix_matcher() const {
return matcher_.get();
}
// Given a normalized string, returns a sequence of sentence pieces with ids.
// The concatenation of pieces must be the same as `normalized`.
virtual EncodeResult Encode(absl::string_view normalized) const = 0;
// The same as above, but returns nbest result with score.
virtual NBestEncodeResult NBestEncode(absl::string_view normalized,
int nbest_size) const {
LOG(ERROR) << "Not implemented.";
return NBestEncodeResult();
}
virtual EncodeResult SampleEncode(absl::string_view normalized,
float alpha) const {
LOG(ERROR) << "Not implemented.";
return EncodeResult();
}
// Sample `samples` many tokenisations from the segmentation lattice
// If `wor` is true, the samples are taken without replacement, and the scores
// are the inclusion probabilities of the elements in the sample; otherwise
// the samples are taken with replacement and the scores are the log-probs of
// sample elements
// If `include_best` is true, the best tokenisation is always included in the
// sample, and the remaining elements are sampled excluding the best.
virtual NBestEncodeResult SampleEncodeAndScore(absl::string_view normalized,
float alpha, int samples,
bool wor,
bool include_best) const {
LOG(ERROR) << "Not implemented.";
return {{EncodeResult(), 0.0}};
}
// Calculates the entropy of the segmentation lattice with inverse temperature
// `alpha`. Uses a novel dynamic program to calculate the entropy.
virtual float CalculateEntropy(absl::string_view normalized,
float alpha) const {
LOG(ERROR) << "Not implemented.";
return 0.0;
}
// Return true if SampleEncode returns a valid result.
virtual bool IsSampleEncodeAvailable() const { return false; }
// Return true if NBestEncode returns a valid result.
virtual bool IsNBestEncodeAvailable() const { return false; }
// Return true if SampleEncodeAndScore returns a valid result.
virtual bool IsSampleEncodeAndScoreAvailable() const { return false; }
// Return true if CalculateEntropy returns a valid result.
virtual bool IsCalculateEntropyAvailable() const { return false; }
// Returns the vocab id of `piece`.
// Returns UNK(0) if `piece` is unknown
virtual int PieceToId(absl::string_view piece) const;
// Returns the string representation of vocab with `id`.
// id must be 0 <= id < GetPieceSize().
virtual const std::string &IdToPiece(int id) const {
return model_proto_->pieces(id).piece();
}
// Returns the size of sentence pieces, which is the same
// as the size of vocabulary for NMT.
virtual int GetPieceSize() const {
if (!model_proto_) return 0;
return model_proto_->pieces_size();
}
// Returns the score of `id`.
// Score represents a log probability of the piece.
// We can roughly estimate the unigram frequency of the piece.
virtual float GetScore(int id) const {
return model_proto_->pieces(id).score();
}
// Returns true if `id` is unknown symbol.
virtual bool IsUnknown(int id) const {
return (model_proto_->pieces(id).type() ==
ModelProto::SentencePiece::UNKNOWN);
}
// Returns true if `id` is control symbol.
virtual bool IsControl(int id) const {
return (model_proto_->pieces(id).type() ==
ModelProto::SentencePiece::CONTROL);
}
// Returns true if `id` is unused symbol.
virtual bool IsUnused(int id) const {
return (model_proto_->pieces(id).type() ==
ModelProto::SentencePiece::UNUSED);
}
// Returns true if `id` is user defined symbol.
virtual bool IsUserDefined(int id) const {
return (model_proto_->pieces(id).type() ==
ModelProto::SentencePiece::USER_DEFINED);
}
// Returns true if `id` is byte symbol.
virtual bool IsByte(int id) const {
return (model_proto_->pieces(id).type() == ModelProto::SentencePiece::BYTE);
}
virtual bool ByteFallbackEnabled() const {
return model_proto_ && model_proto_->trainer_spec().byte_fallback();
}
// Verifies if the `expected` and `actual` outputs are equivalent. `expected`
// and `actual` are sentence pieces joined by space (` `). Normally it means
// that the two strings are identical. In some model, due to float rounding
// errors, the strings may not be identical, but they may be still equivalent
// provided their scores are close enough (by some espilon).
virtual bool VerifyOutputsEquivalent(absl::string_view expected,
absl::string_view actual) const {
return expected == actual;
}
protected:
void InitializePieces();
// Non-virtual (inlined) implementation for faster execution.
inline float GetScoreInlined(int id) const {
return model_proto_->pieces(id).score();
}
inline bool IsUnknownInlined(int id) const {
return (model_proto_->pieces(id).type() ==
ModelProto::SentencePiece::UNKNOWN);
}
inline bool IsControlInlined(int id) const {
return (model_proto_->pieces(id).type() ==
ModelProto::SentencePiece::CONTROL);
}
inline bool IsUnusedInlined(int id) const {
return (model_proto_->pieces(id).type() ==
ModelProto::SentencePiece::UNUSED);
}
inline bool IsUserDefinedInlined(int id) const {
return (model_proto_->pieces(id).type() ==
ModelProto::SentencePiece::USER_DEFINED);
}
inline bool IsByteInlined(int id) const {
return (model_proto_->pieces(id).type() == ModelProto::SentencePiece::BYTE);
}
const ModelProto *model_proto_ = nullptr;
// PrefixMatcher for user defined symbols.
std::unique_ptr<normalizer::PrefixMatcher> matcher_;
// piece -> id map for normal pieces
PieceToIdMap pieces_;
// piece -> id map for control, unknown, and byte pieces
PieceToIdMap reserved_id_map_;
// unknown id.
int unk_id_ = 0;
// status.
util::Status status_;
};
} // namespace sentencepiece
#endif // MODEL_INTERFACE_H_
| 8,751 | 34.008 | 80 | h |
sentencepiece | sentencepiece-master/src/normalizer.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef NORMALIZER_NORMALIZER_H_
#define NORMALIZER_NORMALIZER_H_
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "common.h"
#include "sentencepiece_model.pb.h"
#include "sentencepiece_processor.h"
#include "third_party/absl/strings/string_view.h"
#include "third_party/darts_clone/darts.h"
namespace sentencepiece {
namespace normalizer {
// Given a list of strings, finds the longest string which is a
// prefix of a query.
class PrefixMatcher {
public:
// Initializes the PrefixMatcher with `dic`.
explicit PrefixMatcher(const std::set<absl::string_view> &dic);
// Finds the longest string in dic, which is a prefix of `w`.
// Returns the UTF8 byte length of matched string.
// `found` is set if a prefix match exists.
// If no entry is found, consumes one Unicode character.
int PrefixMatch(absl::string_view w, bool *found = nullptr) const;
// Replaces entries in `w` with `out`.
std::string GlobalReplace(absl::string_view w, absl::string_view out) const;
private:
std::unique_ptr<Darts::DoubleArray> trie_;
};
// Normalizer implements a simple text normalizer with
// user-defined string-to-string rules and leftmost longest
// matching. The rules of Normalizer are built with
// Builder::CompileCharsMap() method. Pre-compiled rules are
// also available via Builder::GetPrecompiledCharsMap(<name>) method.
//
// The motivation of Normalizer is to make flexible, user-customizable
// and self-contained normalizer. All the logic of normalization is
// encoded in the model proto which allows us to define language/task
// dependent normalization rules without breaking the default rule.
class Normalizer {
public:
// Instantiates Normalizer with |spec|.
// |spec| should not be deleted until Normalizer is destroyed.
explicit Normalizer(const NormalizerSpec &spec);
Normalizer(const NormalizerSpec &spec, const TrainerSpec &trainer_Spec);
virtual ~Normalizer();
virtual void SetPrefixMatcher(const PrefixMatcher *matcher) {
matcher_ = matcher;
}
// Returns Status.
// Normalizes function is valid only when status is OK.
virtual util::Status status() const { return status_; }
// Normalizes a plain utf8 string into an internal representation for
// Sentencepiece model. |norm_to_orig| stores the byte-alignment from
// normalized string to the original input.
// This function can do the following normalizations:
// - Character normalization.
// (NFKC / full-width to half-width conversion etc).
// - Adds a prefix space.
// - Replaces a space with a meta symbol.
// - Removing heading, tailing and other redundant spaces.
virtual util::Status Normalize(absl::string_view input,
std::string *normalized,
std::vector<size_t> *norm_to_orig) const;
// Returns a normalized string without alignments.
// This function is used in sentencepiece training.
virtual std::string Normalize(absl::string_view input) const;
friend class Builder;
private:
FRIEND_TEST(NormalizerTest, EncodeDecodePrecompiledCharsMapTest);
void Init();
// Normalizes the prefix of |input| and returns the pair of
// normalized prefix and length we must consume after
// normalization.
// Here's the sample code for the full text normalization.
//
// string output;
// absl::string_view input = "...";
// while (!input.empty()) {
// const auto p = normalizer.NormalizePrefix(input);
// output.append(p.first.data(), p.first.size());
// input.remove_prefix(p.second);
// }
std::pair<absl::string_view, int> NormalizePrefix(
absl::string_view input) const;
// Encodes trie_blob and normalized string and return compiled blob.
static std::string EncodePrecompiledCharsMap(absl::string_view trie_blob,
absl::string_view normalized);
// Decodes blob into trie_blob and normalized string.
static util::Status DecodePrecompiledCharsMap(absl::string_view blob,
absl::string_view *trie_blob,
absl::string_view *normalized,
std::string *buffer = nullptr);
// Maximum size of the return value of Trie, which corresponds
// to the maximum size of shared common prefix in the chars map.
static constexpr int kMaxTrieResultsSize = 32;
// Internal trie for efficient longest matching.
std::unique_ptr<Darts::DoubleArray> trie_;
// "\0" delimitered output string.
// the value of |trie_| stores pointers to this string.
const char *normalized_ = nullptr;
// Spec for normalization.
const NormalizerSpec *spec_;
// Prefix matcher;
const PrefixMatcher *matcher_ = nullptr;
// Split hello world into "hello_" and "world_" instead of
// "_hello" and "_world".
const bool treat_whitespace_as_suffix_ = false;
#ifdef IS_BIG_ENDIAN
// Stores the blob for TRIE encoded in big-endian.
std::string precompiled_charsmap_buffer_;
#endif
// Normalizer's status.
util::Status status_;
};
} // namespace normalizer
} // namespace sentencepiece
#endif // NORMALIZER_NORMALIZER_H_
| 5,817 | 35.3625 | 79 | h |
sentencepiece | sentencepiece-master/src/pretokenizer_for_training.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef PRETOKENIZER_FOR_TRAINING_H_
#define PRETOKENIZER_FOR_TRAINING_H_
#include <memory>
#include <string>
#include "common.h"
#include "sentencepiece.pb.h"
#include "sentencepiece_processor.h"
#include "third_party/absl/strings/string_view.h"
namespace sentencepiece {
namespace pretokenizer {
class PretokenizerForTrainingInterface {
public:
PretokenizerForTrainingInterface() {}
virtual ~PretokenizerForTrainingInterface() {}
virtual util::Status status() const = 0;
// Puts kUPPBoundaryStr before and after the pre-tokenizer's segmentation
// when there are no spaces between these tokens.
// Example1:
// input: 東京です
// segmentation: piece[0] = {0, 6}, piece[1] = {6, 12}
// output: 東京<tab>です (here kUPPBoundaryStr is <tab>)
//
// Example2:
// input: I love sentencepiece
// segmentation: piece[0] = {0, 1}, piece[1] = {2, 6},
// piece[2] = {7, 15}, piece[3] = {15, 20}
// output: I love sentence<tab>piece.
std::vector<std::string> PreTokenize(absl::string_view text) const;
// Returns pre-tokenized result.
// Note that the pre-tokenized constraint is specified with the
// byte offsets (SentencePiece::begin, SentencePiece::end) over
// the input text.
virtual SentencePieceText Tokenize(absl::string_view text) const = 0;
private:
static std::string Preprocess(absl::string_view text);
static std::vector<std::string> Postprocess(const SentencePieceText &spt);
};
} // namespace pretokenizer
} // namespace sentencepiece
#endif // PRETOKENIZER_FOR_TRAINING_H_
| 2,136 | 32.390625 | 76 | h |
sentencepiece | sentencepiece-master/src/sentencepiece_trainer.h | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef SENTENCEPIECE_TRAINER_H_
#define SENTENCEPIECE_TRAINER_H_
#include <string>
#include <unordered_map>
#include "sentencepiece_processor.h"
namespace sentencepiece {
class TrainerSpec;
class NormalizerSpec;
namespace pretokenizer {
class PretokenizerForTrainingInterface;
} // namespace pretokenizer
// Iterator over the training sentences.
// Training sentences are loaded sequentially as follows:
//
// for (; !it.done(); it.Next()) {
// const std::string &s = it.value();
// }
// RETURN_IF_ERROR(it.status());
//
class SentenceIterator {
public:
virtual ~SentenceIterator() {}
// Returns true if iteration finishes (including error case).
// Uses SentenceIterator::status() method to know whether
// all sentences are loaded successfully.
virtual bool done() const = 0;
virtual void Next() = 0;
virtual const std::string &value() const = 0;
virtual util::Status status() const = 0;
};
class SentencePieceTrainer {
public:
// Trains SentencePiece model with `trainer_spec`.
// Default `normalizer_spec` is used.
// When `sentence_iterator` is passed, load sentences from the iterator.
static util::Status Train(const TrainerSpec &trainer_spec,
SentenceIterator *sentence_iterator = nullptr,
std::string *serialized_model_proto = nullptr);
// Trains SentencePiece model with `trainer_spec` and
// `normalizer_spec`.
// When `sentence_iterator` is passed, load sentences from the iterator.
static util::Status Train(const TrainerSpec &trainer_spec,
const NormalizerSpec &normalizer_spec,
SentenceIterator *sentence_iterator = nullptr,
std::string *serialized_model_proto = nullptr);
// Trains SentencePiece model with `trainer_spec`, `normalizer_spec`
// and `denormalizer_spec`.
// When `sentence_iterator` is passed, load sentences from the iterator.
static util::Status Train(const TrainerSpec &trainer_spec,
const NormalizerSpec &normalizer_spec,
const NormalizerSpec &denormalizer_spec,
SentenceIterator *sentence_iterator = nullptr,
std::string *serialized_model_proto = nullptr);
// Trains SentencePiece model with command-line string in `args`,
// e.g.,
// '--input=data --model_prefix=m --vocab_size=8192 model_type=unigram'
// When `sentence_iterator` is passed, load sentences from the iterator.
static util::Status Train(absl::string_view args,
SentenceIterator *sentence_iterator = nullptr,
std::string *serialized_model_proto = nullptr);
// Trains SentencePiece model with mapin `kwargs`.
// e.g., {{"input", "data"}, {"model_prefix, "m"}, {"vocab_size", "8192"}...}
static util::Status Train(
const std::unordered_map<std::string, std::string> &kwargs,
SentenceIterator *sentence_iterator = nullptr,
std::string *serialized_model_proto = nullptr);
// Handy function to make a normalizer spec from the pre-compiled
// normalization name. Do not use this method in production as it crashes
// When `name` is invalid. Useful for unittesting.
static NormalizerSpec GetNormalizerSpec(absl::string_view name);
// Populates necessary fields (precompiled_charmap) from
// `NormalizerSpec::name` or `NormalizerSpec::normalization_rule_tsv`.
static util::Status PopulateNormalizerSpec(NormalizerSpec *normalizer_spec,
bool is_denormalizer = false);
// Overrides `trainer_spec`, `normalizer_spec`, `denormalizer_spec` with the
// std::unordered_map in `kargs`.
static util::Status MergeSpecsFromArgs(
const std::unordered_map<std::string, std::string> &kwargs,
TrainerSpec *trainer_spec, NormalizerSpec *normalizer_spec,
NormalizerSpec *denormalizer_spec);
// Overrides `trainer_spec`, `normalizer_spec`, `denormalizer_spec` with the
// command line flags in `args`.
static util::Status MergeSpecsFromArgs(absl::string_view args,
TrainerSpec *trainer_spec,
NormalizerSpec *normalizer_spec,
NormalizerSpec *denormalizer_spec);
// Injects global pre-tokenizer that are applied in training time.
// Pretokenizer is only used for extracting pieces.
// TODO(taku): It would be better to inject per `trainer_spec`.
static util::Status SetPretokenizerForTraining(
const pretokenizer::PretokenizerForTrainingInterface *pretokenizer);
// Returns the current pretokenizer. if no pretokenizer is defined, returns
// nullptr.
static const pretokenizer::PretokenizerForTrainingInterface *
GetPretokenizerForTraining();
// Helper function to set `field_name=value` in `message`.
// When `field_name` is repeated, multiple values can be passed
// with comma-separated values. `field_name` must not be a nested message.
// The body of these functions are automatically generated with
// data/gen_spec_parser.pl
static util::Status SetProtoField(absl::string_view name,
absl::string_view value,
TrainerSpec *message);
static util::Status SetProtoField(absl::string_view name,
absl::string_view value,
NormalizerSpec *message);
// Populates model type from string representation, e.g., "bpe".
// Supported model: "unigram", "bpe", "word", "char".
static util::Status PopulateModelTypeFromString(absl::string_view type,
TrainerSpec *trainer_spec);
private:
SentencePieceTrainer() {}
~SentencePieceTrainer() {}
};
} // namespace sentencepiece
#endif // SENTENCEPIECE_TRAINER_H_
| 6,523 | 41.640523 | 79 | h |
sentencepiece | sentencepiece-master/src/spec_parser.h | // Copyright 2016 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef SPEC_PARSER_H_
#define SPEC_PARSER_H_
#include <string>
#include <vector>
#include "sentencepiece_processor.h"
#include "third_party/absl/strings/ascii.h"
#include "third_party/absl/strings/str_split.h"
#include "util.h"
namespace sentencepiece {
#define PARSE_STRING(param_name) \
if (name == #param_name) { \
message->set_##param_name(std::string(value)); \
return util::OkStatus(); \
}
#define PARSE_REPEATED_STRING(param_name) \
if (name == #param_name) { \
for (const std::string &val : util::StrSplitAsCSV(value)) { \
message->add_##param_name(val); \
} \
return util::OkStatus(); \
}
#define PARSE_BYTE(param_name) \
if (name == #param_name) { \
message->set_##param_name(value.data(), value.size()); \
return util::OkStatus(); \
}
#define PARSE_INT32(param_name) \
if (name == #param_name) { \
int32 v; \
if (!string_util::lexical_cast(value, &v)) \
return util::StatusBuilder(util::StatusCode::kInvalidArgument, GTL_LOC) \
<< "cannot parse \"" << value << "\" as int."; \
message->set_##param_name(v); \
return util::OkStatus(); \
}
#define PARSE_UINT64(param_name) \
if (name == #param_name) { \
uint64 v; \
if (!string_util::lexical_cast(value, &v)) \
return util::StatusBuilder(util::StatusCode::kInvalidArgument, GTL_LOC) \
<< "cannot parse \"" << value << "\" as int."; \
message->set_##param_name(v); \
return util::OkStatus(); \
}
#define PARSE_DOUBLE(param_name) \
if (name == #param_name) { \
double v; \
if (!string_util::lexical_cast(value, &v)) \
return util::StatusBuilder(util::StatusCode::kInvalidArgument, GTL_LOC) \
<< "cannot parse \"" << value << "\" as int."; \
message->set_##param_name(v); \
return util::OkStatus(); \
}
#define PARSE_BOOL(param_name) \
if (name == #param_name) { \
bool v; \
if (!string_util::lexical_cast(value.empty() ? "true" : value, &v)) \
return util::StatusBuilder(util::StatusCode::kInvalidArgument, GTL_LOC) \
<< "cannot parse \"" << value << "\" as bool."; \
message->set_##param_name(v); \
return util::OkStatus(); \
}
#define PARSE_ENUM(param_name, map_name) \
if (name == #param_name) { \
const auto it = map_name.find(absl::AsciiStrToUpper(value)); \
if (it == map_name.end()) \
return util::StatusBuilder(util::StatusCode::kInvalidArgument, GTL_LOC) \
<< "unknown enumeration value of \"" << value << "\" as " \
<< #map_name; \
message->set_##param_name(it->second); \
return util::OkStatus(); \
}
#define PRINT_PARAM(param_name) \
os << " " << #param_name << ": " << message.param_name() << "\n";
#define PRINT_REPEATED_STRING(param_name) \
for (const auto &v : message.param_name()) \
os << " " << #param_name << ": " << v << "\n";
#define PRINT_ENUM(param_name, map_name) \
const auto it = map_name.find(message.param_name()); \
if (it == map_name.end()) \
os << " " << #param_name << ": unknown\n"; \
else \
os << " " << #param_name << ": " << it->second << "\n";
inline std::string PrintProto(const TrainerSpec &message,
absl::string_view name) {
std::ostringstream os;
os << name << " {\n";
PRINT_REPEATED_STRING(input);
PRINT_PARAM(input_format);
PRINT_PARAM(model_prefix);
static const std::map<TrainerSpec::ModelType, std::string> kModelType_Map = {
{TrainerSpec::UNIGRAM, "UNIGRAM"},
{TrainerSpec::BPE, "BPE"},
{TrainerSpec::WORD, "WORD"},
{TrainerSpec::CHAR, "CHAR"},
};
PRINT_ENUM(model_type, kModelType_Map);
PRINT_PARAM(vocab_size);
PRINT_REPEATED_STRING(accept_language);
PRINT_PARAM(self_test_sample_size);
PRINT_PARAM(character_coverage);
PRINT_PARAM(input_sentence_size);
PRINT_PARAM(shuffle_input_sentence);
PRINT_PARAM(seed_sentencepiece_size);
PRINT_PARAM(shrinking_factor);
PRINT_PARAM(max_sentence_length);
PRINT_PARAM(num_threads);
PRINT_PARAM(num_sub_iterations);
PRINT_PARAM(max_sentencepiece_length);
PRINT_PARAM(split_by_unicode_script);
PRINT_PARAM(split_by_number);
PRINT_PARAM(split_by_whitespace);
PRINT_PARAM(split_digits);
PRINT_PARAM(pretokenization_delimiter);
PRINT_PARAM(treat_whitespace_as_suffix);
PRINT_PARAM(allow_whitespace_only_pieces);
PRINT_REPEATED_STRING(control_symbols);
PRINT_REPEATED_STRING(user_defined_symbols);
PRINT_PARAM(required_chars);
PRINT_PARAM(byte_fallback);
PRINT_PARAM(vocabulary_output_piece_score);
PRINT_PARAM(train_extremely_large_corpus);
PRINT_PARAM(hard_vocab_limit);
PRINT_PARAM(use_all_vocab);
PRINT_PARAM(unk_id);
PRINT_PARAM(bos_id);
PRINT_PARAM(eos_id);
PRINT_PARAM(pad_id);
PRINT_PARAM(unk_piece);
PRINT_PARAM(bos_piece);
PRINT_PARAM(eos_piece);
PRINT_PARAM(pad_piece);
PRINT_PARAM(unk_surface);
PRINT_PARAM(enable_differential_privacy);
PRINT_PARAM(differential_privacy_noise_level);
PRINT_PARAM(differential_privacy_clipping_threshold);
os << "}\n";
return os.str();
}
inline std::string PrintProto(const NormalizerSpec &message,
absl::string_view name) {
std::ostringstream os;
os << name << " {\n";
PRINT_PARAM(name);
PRINT_PARAM(add_dummy_prefix);
PRINT_PARAM(remove_extra_whitespaces);
PRINT_PARAM(escape_whitespaces);
PRINT_PARAM(normalization_rule_tsv);
os << "}\n";
return os.str();
}
util::Status SentencePieceTrainer::SetProtoField(absl::string_view name,
absl::string_view value,
TrainerSpec *message) {
CHECK_OR_RETURN(message);
PARSE_REPEATED_STRING(input);
PARSE_STRING(input_format);
PARSE_STRING(model_prefix);
static const std::map<std::string, TrainerSpec::ModelType> kModelType_Map = {
{"UNIGRAM", TrainerSpec::UNIGRAM},
{"BPE", TrainerSpec::BPE},
{"WORD", TrainerSpec::WORD},
{"CHAR", TrainerSpec::CHAR},
};
PARSE_ENUM(model_type, kModelType_Map);
PARSE_INT32(vocab_size);
PARSE_REPEATED_STRING(accept_language);
PARSE_INT32(self_test_sample_size);
PARSE_DOUBLE(character_coverage);
PARSE_UINT64(input_sentence_size);
PARSE_BOOL(shuffle_input_sentence);
PARSE_INT32(seed_sentencepiece_size);
PARSE_DOUBLE(shrinking_factor);
PARSE_INT32(max_sentence_length);
PARSE_INT32(num_threads);
PARSE_INT32(num_sub_iterations);
PARSE_INT32(max_sentencepiece_length);
PARSE_BOOL(split_by_unicode_script);
PARSE_BOOL(split_by_number);
PARSE_BOOL(split_by_whitespace);
PARSE_BOOL(split_digits);
PARSE_STRING(pretokenization_delimiter);
PARSE_BOOL(treat_whitespace_as_suffix);
PARSE_BOOL(allow_whitespace_only_pieces);
PARSE_REPEATED_STRING(control_symbols);
PARSE_REPEATED_STRING(user_defined_symbols);
PARSE_STRING(required_chars);
PARSE_BOOL(byte_fallback);
PARSE_BOOL(hard_vocab_limit);
PARSE_BOOL(vocabulary_output_piece_score);
PARSE_BOOL(train_extremely_large_corpus);
PARSE_BOOL(use_all_vocab);
PARSE_INT32(unk_id);
PARSE_INT32(bos_id);
PARSE_INT32(eos_id);
PARSE_INT32(pad_id);
PARSE_STRING(unk_piece);
PARSE_STRING(bos_piece);
PARSE_STRING(eos_piece);
PARSE_STRING(pad_piece);
PARSE_STRING(unk_surface);
PARSE_BOOL(enable_differential_privacy);
PARSE_DOUBLE(differential_privacy_noise_level);
PARSE_UINT64(differential_privacy_clipping_threshold);
return util::StatusBuilder(util::StatusCode::kNotFound, GTL_LOC)
<< "unknown field name \"" << name << "\" in TrainerSpec.";
}
util::Status SentencePieceTrainer::SetProtoField(absl::string_view name,
absl::string_view value,
NormalizerSpec *message) {
CHECK_OR_RETURN(message);
PARSE_STRING(name);
PARSE_BYTE(precompiled_charsmap);
PARSE_BOOL(add_dummy_prefix);
PARSE_BOOL(remove_extra_whitespaces);
PARSE_BOOL(escape_whitespaces);
PARSE_STRING(normalization_rule_tsv);
return util::StatusBuilder(util::StatusCode::kNotFound, GTL_LOC)
<< "unknown field name \"" << name << "\" in NormalizerSpec.";
}
#undef PARSE_STRING
#undef PARSE_REPEATED_STRING
#undef PARSE_BOOL
#undef PARSE_BYTE
#undef PARSE_INT32
#undef PARSE_DUOBLE
#undef PARSE_ENUM
#undef PRINT_MAP
#undef PRINT_REPEATED_STRING
#undef PRINT_ENUM
} // namespace sentencepiece
#endif // SPEC_PARSER_H_
| 10,925 | 37.607774 | 79 | h |
sentencepiece | sentencepiece-master/src/testharness.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef TESTHARNESS_H_
#define TESTHARNESS_H_
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include "common.h"
#include "third_party/absl/flags/flag.h"
#include "third_party/absl/flags/parse.h"
#include "third_party/absl/strings/string_view.h"
ABSL_DECLARE_FLAG(std::string, test_tmpdir);
ABSL_DECLARE_FLAG(std::string, test_srcdir);
namespace sentencepiece {
namespace test {
// Run some of the tests registered by the TEST() macro.
// TEST(Foo, Hello) { ... }
// TEST(Foo, World) { ... }
//
// Returns 0 if all tests pass.
// Dies or returns a non-zero value if some test fails.
int RunAllTests();
// An instance of Tester is allocated to hold temporary state during
// the execution of an assertion.
class Tester {
public:
Tester(const char *fname, int line) : ok_(true), fname_(fname), line_(line) {}
~Tester() {
if (!ok_) {
std::cerr << "[ NG ] " << fname_ << ":" << line_ << ":" << ss_.str()
<< std::endl;
exit(-1);
}
}
Tester &Is(bool b, const char *msg) {
if (!b) {
ss_ << " failed: " << msg;
ok_ = false;
}
return *this;
}
Tester &IsNear(double val1, double val2, double abs_error, const char *msg1,
const char *msg2) {
const double diff = std::fabs(val1 - val2);
if (diff > abs_error) {
ss_ << "The difference between (" << msg1 << ") and (" << msg2 << ") is "
<< diff << ", which exceeds " << abs_error << ", where\n"
<< msg1 << " evaluates to " << val1 << ",\n"
<< msg2 << " evaluates to " << val2;
ok_ = false;
}
return *this;
}
#define BINARY_OP(name, op) \
template <class X, class Y> \
Tester &name(const X &x, const Y &y, const char *msg1, const char *msg2) { \
if (!(x op y)) { \
ss_ << " failed: " << msg1 << (" " #op " ") << msg2; \
ok_ = false; \
} \
return *this; \
}
BINARY_OP(IsEq, ==)
BINARY_OP(IsNe, !=)
BINARY_OP(IsGe, >=)
BINARY_OP(IsGt, >)
BINARY_OP(IsLe, <=)
BINARY_OP(IsLt, <)
#undef BINARY_OP
// Attach the specified value to the error message if an error has occurred
template <class V>
Tester &operator<<(const V &value) {
if (!ok_) {
ss_ << " " << value;
}
return *this;
}
private:
bool ok_;
const char *fname_;
int line_;
std::stringstream ss_;
};
#define EXPECT_TRUE(c) \
sentencepiece::test::Tester(__FILE__, __LINE__).Is((c), #c)
#define EXPECT_FALSE(c) \
sentencepiece::test::Tester(__FILE__, __LINE__).Is((!(c)), #c)
#define EXPECT_STREQ(a, b) \
sentencepiece::test::Tester(__FILE__, __LINE__) \
.IsEq(std::string(a), std::string(b), #a, #b)
#define EXPECT_EQ(a, b) \
sentencepiece::test::Tester(__FILE__, __LINE__).IsEq((a), (b), #a, #b)
#define EXPECT_NE(a, b) \
sentencepiece::test::Tester(__FILE__, __LINE__).IsNe((a), (b), #a, #b)
#define EXPECT_GE(a, b) \
sentencepiece::test::Tester(__FILE__, __LINE__).IsGe((a), (b), #a, #b)
#define EXPECT_GT(a, b) \
sentencepiece::test::Tester(__FILE__, __LINE__).IsGt((a), (b), #a, #b)
#define EXPECT_LE(a, b) \
sentencepiece::test::Tester(__FILE__, __LINE__).IsLe((a), (b), #a, #b)
#define EXPECT_LT(a, b) \
sentencepiece::test::Tester(__FILE__, __LINE__).IsLt((a), (b), #a, #b)
#define EXPECT_NEAR(a, b, c) \
sentencepiece::test::Tester(__FILE__, __LINE__).IsNear((a), (b), (c), #a, #b)
#define EXPECT_OK(c) EXPECT_EQ(c, ::sentencepiece::util::OkStatus())
#define EXPECT_NOT_OK(c) EXPECT_NE(c, ::sentencepiece::util::OkStatus())
#define EXPECT_DEATH(statement, condition) \
{ \
sentencepiece::error::SetTestCounter(1); \
statement; \
sentencepiece::error::SetTestCounter(0); \
};
#define ASSERT_TRUE EXPECT_TRUE
#define ASSERT_FALSE EXPECT_FALSE
#define ASSERT_STREQ EXPECT_STREQ
#define ASSERT_EQ EXPECT_EQ
#define ASSERT_NE EXPECT_NE
#define ASSERT_GE EXPECT_GE
#define ASSERT_GT EXPECT_GT
#define ASSERT_LE EXPECT_LE
#define ASSERT_LT EXPECT_LT
#define ASSERT_NEAR EXPECT_NEAR
#define ASSERT_NOT_OK EXPECT_NOT_OK
#define ASSERT_DEATH ASSERT_DEATH
template <typename T>
class TestWithParam {
public:
using ParamType = T;
virtual void SetUp() {}
virtual void TearDown() {}
virtual ~TestWithParam() {}
virtual ParamType GetParam() const { return ParamType(); }
};
template <typename T>
std::vector<T> ValuesIn(const std::vector<T> &v) {
return v;
}
#define TCONCAT(a, b, c) TCONCAT1(a, b, c)
#define TCONCAT1(a, b, c) a##b##c
#define INSTANTIATE_TEST_SUITE_P(suite_base, base, params) \
std::vector<base::ParamType> TCONCAT(base, _get_params_, base)() { \
return params; \
}
#define TEST(base, name) \
class TCONCAT(base, _Test_, name) { \
public: \
void _Run(); \
static void _RunIt() { \
TCONCAT(base, _Test_, name) t; \
t._Run(); \
} \
}; \
bool TCONCAT(base, _Test_ignored_, name) = \
sentencepiece::test::RegisterTest(#base, #name, \
&TCONCAT(base, _Test_, name)::_RunIt); \
void TCONCAT(base, _Test_, name)::_Run()
#define TEST_P(base, name) \
std::vector<base::ParamType> TCONCAT(base, _get_params_, base)(); \
class TCONCAT(base, _Test_p_, name) : public base { \
public: \
const std::vector<ParamType> GetParams() const { \
return TCONCAT(base, _get_params_, base)(); \
} \
ParamType param_; \
void SetParam(const ParamType ¶m) { param_ = param; } \
const ParamType GetParam() { return param_; } \
void _Run(); \
static void _RunIt() { \
TCONCAT(base, _Test_p_, name) t; \
for (const auto ¶m : t.GetParams()) { \
t.SetParam(param); \
t.SetUp(); \
t._Run(); \
t.TearDown(); \
} \
} \
}; \
bool TCONCAT(base, _Test_p_ignored_, name) = \
sentencepiece::test::RegisterTest( \
#base, #name, &TCONCAT(base, _Test_p_, name)::_RunIt); \
void TCONCAT(base, _Test_p_, name)::_Run()
// Register the specified test. Typically not used directly, but
// invoked via the macro expansion of TEST.
extern bool RegisterTest(const char *base, const char *name, void (*func)());
} // namespace test
} // namespace sentencepiece
#endif // TESTHARNESS_H_
| 8,718 | 38.098655 | 80 | h |
sentencepiece | sentencepiece-master/src/trainer_factory.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef TRAINER_FACTORY_H_
#define TRAINER_FACTORY_H_
#include <memory>
#include "sentencepiece_model.pb.h"
#include "trainer_interface.h"
namespace sentencepiece {
class TrainerFactory {
public:
// Creates Trainer instance from |trainer_spec| and |normalizer_spec|.
static std::unique_ptr<TrainerInterface> Create(
const TrainerSpec &trainer_spec, const NormalizerSpec &normalizer_spec,
const NormalizerSpec &denormalizer_spec);
};
} // namespace sentencepiece
#endif // TRAINER_FACTORY_H_
| 1,104 | 31.5 | 77 | h |
sentencepiece | sentencepiece-master/src/trainer_interface.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef TRAINER_INTERFACE_H_
#define TRAINER_INTERFACE_H_
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "common.h"
#include "filesystem.h"
#include "sentencepiece_model.pb.h"
#include "sentencepiece_processor.h"
#include "sentencepiece_trainer.h"
#include "third_party/absl/container/flat_hash_map.h"
#include "util.h"
namespace sentencepiece {
template <typename K, typename V>
std::vector<std::pair<K, V>> Sorted(const std::vector<std::pair<K, V>> &m) {
std::vector<std::pair<K, V>> v = m;
std::sort(v.begin(), v.end(),
[](const std::pair<K, V> &p1, const std::pair<K, V> &p2) {
return (p1.second > p2.second ||
(p1.second == p2.second && p1.first < p2.first));
});
return v;
}
template <typename K, typename V>
std::vector<std::pair<K, V>> Sorted(const absl::flat_hash_map<K, V> &m) {
std::vector<std::pair<K, V>> v(m.begin(), m.end());
return Sorted(v);
}
class MultiFileSentenceIterator : public SentenceIterator {
public:
explicit MultiFileSentenceIterator(const std::vector<std::string> &files);
~MultiFileSentenceIterator() {}
bool done() const override;
void Next() override;
const std::string &value() const override { return value_; }
util::Status status() const override;
private:
void TryRead();
bool read_done_ = false;
size_t file_index_ = 0;
std::vector<std::string> files_;
std::string value_;
std::unique_ptr<filesystem::ReadableFile> fp_;
};
// Base trainer class
class TrainerInterface {
public:
using Sentence = std::pair<std::string, int64>;
using Sentences = std::vector<Sentence>;
static const char32 kWSChar;
static const char32 kUNKChar;
static const char32 kUPPBoundaryChar;
static const char kWSStr[];
static const char kUNKStr[];
static const char kUPPBoundaryStr[];
TrainerInterface(const TrainerSpec &trainer_spec,
const NormalizerSpec &normalizer_spec,
const NormalizerSpec &denormalizer_spec);
virtual ~TrainerInterface();
// Loads sentence from `sentence_iterator` and stores the model
// to `output_model_proto`.
virtual util::Status Train(SentenceIterator *sentence_iterator,
ModelProto *output_model_proto) {
sentence_iterator_ = sentence_iterator;
output_model_proto_ = output_model_proto;
return Train();
}
virtual util::Status Train() { return status(); }
virtual util::Status status() const { return status_; }
FRIEND_TEST(TrainerInterfaceTest, IsValidSentencePieceTest);
FRIEND_TEST(TrainerInterfaceTest, OverrideSpecialPiecesTest);
FRIEND_TEST(TrainerInterfaceTest, BytePiecesTest);
FRIEND_TEST(TrainerInterfaceTest, SerializeTest);
FRIEND_TEST(TrainerInterfaceTest, CharactersTest);
// Loads all sentences from spec.input() or SentenceIterator.
// It loads at most input_sentence_size sentences.
util::Status LoadSentences();
protected:
// Returns true if |piece| is valid sentence piece.
// The result is affected by
// max_sentencepiece_length, split_by_whiespace, split_by_unicode_script.
bool IsValidSentencePiece(const string_util::UnicodeText &piece) const;
// Splits all sentencecs by whitespaces and
// replace the |sentences_| with tokenized string.
// e.g.,
// [ ["hello world ", 1], ["hi world]" ] =>
// [ ["hello", 1], ["hi", 1], ["world", 2] ]
void SplitSentencesByWhitespace();
// Save model files into spec.model_prefix().
util::Status Save() const;
// Set of characters which must be included in the final vocab.
// The value of this map stores the frequency.
absl::flat_hash_map<char32, int64> required_chars_;
// Final output pieces
std::vector<std::pair<std::string, float>> final_pieces_;
// All sentences.
Sentences sentences_;
// Trainer spec.
TrainerSpec trainer_spec_;
// Normalizer spec
NormalizerSpec normalizer_spec_;
// Denormalizer spec
NormalizerSpec denormalizer_spec_;
// Reserved control pieces. e.g., <unk>, <s>, </s>.
// key is vocab id.
std::map<int, std::pair<std::string, ModelProto::SentencePiece::Type>>
meta_pieces_;
// Detect errors on initialization.
util::Status status_;
// Loads sentences from SentenceIterator if not null.
SentenceIterator *sentence_iterator_ = nullptr;
// Emits model to this proto instead of file.
ModelProto *output_model_proto_ = nullptr;
private:
// Serialize final_pieces_ to |model_proto|.
util::Status Serialize(ModelProto *model_proto) const;
// Saves the best sentence split with the current model for debugging.
util::Status SaveSplits(absl::string_view filename) const;
// Saves model file.
util::Status SaveModel(absl::string_view filename) const;
// Saves vocabulary file for NMT.
util::Status SaveVocab(absl::string_view filename) const;
// Initializes `meta_pieces_` from TrainerSpec.
util::Status InitMetaPieces();
// Randomly sampled raw sentences for self-testing.
std::vector<std::string> self_test_samples_;
};
} // namespace sentencepiece
#endif // TRAINER_INTERFACE_H_
| 5,727 | 30.130435 | 76 | h |
sentencepiece | sentencepiece-master/src/unigram_model.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef UNIGRAM_MODEL_H_
#define UNIGRAM_MODEL_H_
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "common.h"
#include "freelist.h"
#include "model_interface.h"
#include "sentencepiece_model.pb.h"
#include "third_party/darts_clone/darts.h"
namespace sentencepiece {
namespace unigram {
// Lattice represents a search space of sentence piece segmentation.
class Lattice {
public:
Lattice();
virtual ~Lattice();
struct Node {
absl::string_view piece; // Sentence piece representation.
uint32 pos; // Unicode position in the sentence.
uint32 length; // Unicode length, not UT8 byte.
uint32 node_id; // unique id in the current lattice.
int id; // vocab id. (maybe -1 for UNK)
float score; // logprob of this sentencepiece.
float backtrace_score; // backtrace info used in Viterbi.
Node *prev; // best previous node on Viterbi path.
std::string DebugString() const;
};
// Returns bos node.
Node *bos_node() const;
// Returns eos node.
Node *eos_node() const;
// Returns nodes starting at |pos|.
const std::vector<Node *> &begin_nodes(int pos) const;
// Returns nodes ending at |pos|.
const std::vector<Node *> &end_nodes(int pos) const;
// Returns Unicode character length.
int size() const;
// Returns multi-byte (utf8) length.
int utf8_size() const;
// Returns the substring of sentence. sentence[pos:]
const char *surface(int pos) const;
// Returns immutable sentence. The same as surface(0)
const char *sentence() const;
// Clears the lattice.
void Clear();
// Sets new sentence.
void SetSentence(absl::string_view sentence);
// Inserts a new node at [pos, pos + length - 1].
// After calling this method, The caller must set Node::score and Node::id.
Node *Insert(int pos, int length);
using LatticePathWithScore = std::pair<std::vector<Node *>, float>;
// Returns Viterbi path. All nodes must be populated in advance.
LatticePathWithScore Viterbi();
// Runs forwards/backwards algorithm, returns vector with normalised
// transition probs.
std::vector<float> ForwardAlgorithm(float theta) const;
std::vector<float> BackwardAlgorithm(float theta) const;
// Returns n-best results.
std::vector<LatticePathWithScore> NBest(size_t nbest_size, bool sample,
float theta);
// Samples one path from the lattice according to the
// generation probability (Product of piece probabilities).
// `theta` is a smoothing parameter.
std::vector<Node *> Sample(float theta);
// Calculates the entropy of the lattice.
float CalculateEntropy(float theta) const;
// Populates marginal probability of every node in this lattice.
// |freq| is the frequency of the sentence.
// for (auto *node : all_nodes_) {
// (*expected)[node->id] += marginal_prob_of_node * freq;
// }
// Returns the log-likelihood of this sentence.
float PopulateMarginal(float freq, std::vector<float> *expected) const;
private:
// Returns new node.
// Lattice class has the ownership of the returned value.
Node *NewNode();
absl::string_view sentence_;
std::vector<const char *> surface_;
std::vector<std::vector<Node *>> begin_nodes_;
std::vector<std::vector<Node *>> end_nodes_;
model::FreeList<Node> node_allocator_;
};
class Model : public ModelInterface {
public:
explicit Model(const ModelProto &model_proto);
Model() {}
~Model() override;
EncodeResult Encode(absl::string_view normalized) const override;
NBestEncodeResult NBestEncode(absl::string_view normalized,
int nbest_size) const override;
EncodeResult SampleEncode(absl::string_view normalized,
float theta) const override;
NBestEncodeResult SampleEncodeAndScore(absl::string_view normalized,
float theta, int samples, bool wor,
bool include_best) const override;
float CalculateEntropy(absl::string_view normalized,
float theta) const override;
bool IsSampleEncodeAvailable() const override { return true; }
bool IsSampleEncodeAndScoreAvailable() const override { return true; }
bool IsCalculateEntropyAvailable() const override { return true; }
bool IsNBestEncodeAvailable() const override { return true; }
// Returns the minimum score in sentence pieces.
// min_score() - 10 is used for the cost of unknown sentence.
float min_score() const { return min_score_; }
// Returns the maximum score in sentence pieces.
// max_score() is used for the cost of user defined symbols.
float max_score() const { return max_score_; }
// Populates all sentence pieces to the |lattice|.
// After calling this function, lattice.Viterbi() returns the
// best segmentation.
void PopulateNodes(Lattice *lattice) const;
// Returns a vocab id of |piece|.
int PieceToId(absl::string_view piece) const override;
// Verifies if two outputs are equivalent by comparing their scores.
bool VerifyOutputsEquivalent(absl::string_view expected,
absl::string_view actual) const override;
enum EncoderVersion {
kOptimized, // The optimized encoder.
kOriginal // The original encoder.
};
void SetEncoderVersion(EncoderVersion encoder_version) {
encoder_version_ = encoder_version;
}
// Returns the current encoder version in use.
EncoderVersion GetEncoderVersion() const { return encoder_version_; }
protected:
// Builds a Trie index.
void BuildTrie(std::vector<std::pair<absl::string_view, int>> *pieces);
// The optimized Viterbi encode.
// Main differences from the original function:
// 1. Memorizes the best path at each postion so far,
// 2. No need to store the Lattice nodes,
// 3. Works in utf-8 directly,
// 4. Defines a new struct with fewer fields than Lattice,
// 5. Does not depend on `class Lattice` nor call `SetSentence()`,
// `PopulateNodes()`, or `Viterbi()`. It does everything in one function.
// For detailed explanations please see the comments inside the function body.
EncodeResult EncodeOptimized(absl::string_view normalized) const;
float min_score_ = 0.0;
float max_score_ = 0.0;
std::unique_ptr<Darts::DoubleArray> trie_;
// Maximum size of the return value of Trie, which corresponds
// to the maximum size of shared common prefix in the sentence pieces.
int trie_results_size_;
// encoder version.
EncoderVersion encoder_version_ = kOptimized;
};
} // namespace unigram
} // namespace sentencepiece
#endif // UNIGRAM_MODEL_H_
| 7,324 | 32.600917 | 80 | h |
sentencepiece | sentencepiece-master/src/unigram_model_trainer.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef UNIGRAM_MODEL_TRAINER_H_
#define UNIGRAM_MODEL_TRAINER_H_
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "sentencepiece_model.pb.h"
#include "third_party/absl/strings/string_view.h"
#include "trainer_interface.h"
#include "unigram_model.h"
#include "util.h"
namespace sentencepiece {
namespace unigram {
using string_util::UnicodeText;
class TrainerModel : public Model {
public:
using SentencePieces = std::vector<std::pair<std::string, float>>;
TrainerModel() {}
TrainerModel(const ModelProto &model_proto) = delete;
TrainerModel(const TrainerSpec &trainer_spec,
const NormalizerSpec &normalizaiton_spec);
~TrainerModel() override;
// Returns the sentencepieces.
// The meta symbols, e.g., </s> are NOT included.
const SentencePieces &GetSentencePieces() const;
// Sets sentencepieces. The sentencepieces are moved.
// The meta symbols, e.g., </s> are NOT included.
void SetSentencePieces(SentencePieces &&sentencepieces);
EncodeResult Encode(absl::string_view normalized) const override {
return {};
}
private:
SentencePieces sentencepieces_;
TrainerSpec trainer_spec_;
NormalizerSpec normalizer_spec_;
ModelProto model_proto_data_;
};
class Trainer : public TrainerInterface {
public:
Trainer(const TrainerSpec &trainer_spec,
const NormalizerSpec &normalizer_spec,
const NormalizerSpec &denormalizer_spec)
: TrainerInterface::TrainerInterface(trainer_spec, normalizer_spec,
denormalizer_spec) {}
TrainerModel::SentencePieces MakeSeedSentencePieces();
util::Status Train() override;
private:
FRIEND_TEST(TrainerTest, IsValidSentencePieceTest);
// Makes seed pieces from the training corpus.
// The size of seed pieces is determined by seed_sentencepiece_size.
// node_int_type should be of integer type (int32 or int64),
// determined by train_extremely_large_corpus.
template <typename node_int_type>
TrainerModel::SentencePieces MakeSeedSentencePiecesInternal();
// Executes the E step of EM and returns expected count.
// The index of return array is the vocab id.
// |objective| is a negative likelihood of the current model.
// |num_token| is the number of total tokens to tokenize
// training corpus.
std::vector<float> RunEStep(const TrainerModel &model, float *objective,
int64 *num_tokens) const;
// Executes the M step of EM with the expected frequency and
// returns new pieces.
TrainerModel::SentencePieces RunMStep(
const TrainerModel &model, const std::vector<float> &expected) const;
// Heuristically prunes the current pieces.
// This is called after each EM sub-iteration.
TrainerModel::SentencePieces PruneSentencePieces(
const TrainerModel &model) const;
// Makes the final sentence pieces by incorporating the required characters
// and control/user defined symbols.
TrainerModel::SentencePieces FinalizeSentencePieces(
const TrainerModel &model) const;
// When the size of SentencePieces becomes less than desired_vocab_size_,
// break the main training loop. desired_vocab_size_ = 1.1 * vocab_size_
// for now.
int desired_vocab_size_;
};
} // namespace unigram
} // namespace sentencepiece
#endif // UNIGRAM_MODEL_TRAINER_H_
| 3,939 | 32.965517 | 77 | h |
sentencepiece | sentencepiece-master/src/util.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef UTIL_H_
#define UTIL_H_
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <functional>
#include <memory>
#include <random>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include "common.h"
#include "sentencepiece_processor.h"
#include "third_party/absl/strings/string_view.h"
#ifdef SPM_NO_THREADLOCAL
#include <pthread.h>
#endif
namespace sentencepiece {
template <typename T>
std::ostream &operator<<(std::ostream &out, const std::vector<T> &v) {
for (const auto n : v) {
out << " " << n;
}
return out;
}
uint32 GetRandomGeneratorSeed();
// String utilities
namespace string_util {
template <typename Target>
inline bool lexical_cast(absl::string_view arg, Target *result) {
std::stringstream ss;
return (ss << arg.data() && ss >> *result);
}
template <>
inline bool lexical_cast(absl::string_view arg, bool *result) {
const char *kTrue[] = {"1", "t", "true", "y", "yes"};
const char *kFalse[] = {"0", "f", "false", "n", "no"};
std::string lower_value = std::string(arg);
std::transform(lower_value.begin(), lower_value.end(), lower_value.begin(),
::tolower);
for (size_t i = 0; i < 5; ++i) {
if (lower_value == kTrue[i]) {
*result = true;
return true;
} else if (lower_value == kFalse[i]) {
*result = false;
return true;
}
}
return false;
}
template <>
inline bool lexical_cast(absl::string_view arg, std::string *result) {
*result = std::string(arg);
return true;
}
template <typename T>
inline bool DecodePOD(absl::string_view str, T *result) {
if (sizeof(*result) != str.size()) {
return false;
}
memcpy(result, str.data(), sizeof(T));
return true;
}
template <typename T>
inline std::string EncodePOD(const T &value) {
std::string s;
s.resize(sizeof(T));
memcpy(const_cast<char *>(s.data()), &value, sizeof(T));
return s;
}
template <typename T>
inline std::string IntToHex(T value) {
std::ostringstream os;
os << std::hex << std::uppercase << value;
return os.str();
}
template <typename T>
inline T HexToInt(absl::string_view value) {
T n;
std::istringstream is(value.data());
is >> std::hex >> n;
return n;
}
template <typename T>
inline size_t Itoa(T val, char *s) {
char *org = s;
if (val < 0) {
*s++ = '-';
val = -val;
}
char *t = s;
T mod = 0;
while (val) {
mod = val % 10;
*t++ = static_cast<char>(mod) + '0';
val /= 10;
}
if (s == t) {
*t++ = '0';
}
*t = '\0';
std::reverse(s, t);
return static_cast<size_t>(t - org);
}
template <typename T>
std::string SimpleItoa(T val) {
char buf[32];
Itoa<T>(val, buf);
return std::string(buf);
}
// Return length of a single UTF-8 source character
inline size_t OneCharLen(const char *src) {
return "\1\1\1\1\1\1\1\1\1\1\1\1\2\2\3\4"[(*src & 0xFF) >> 4];
}
// Return (x & 0xC0) == 0x80;
// Since trail bytes are always in [0x80, 0xBF], we can optimize:
inline bool IsTrailByte(char x) { return static_cast<signed char>(x) < -0x40; }
inline bool IsValidCodepoint(char32 c) {
return (static_cast<uint32>(c) < 0xD800) || (c >= 0xE000 && c <= 0x10FFFF);
}
bool IsStructurallyValid(absl::string_view str);
using UnicodeText = std::vector<char32>;
char32 DecodeUTF8(const char *begin, const char *end, size_t *mblen);
inline char32 DecodeUTF8(absl::string_view input, size_t *mblen) {
return DecodeUTF8(input.data(), input.data() + input.size(), mblen);
}
inline bool IsValidDecodeUTF8(absl::string_view input, size_t *mblen) {
const char32 c = DecodeUTF8(input, mblen);
return c != kUnicodeError || *mblen == 3;
}
size_t EncodeUTF8(char32 c, char *output);
std::string UnicodeCharToUTF8(const char32 c);
UnicodeText UTF8ToUnicodeText(absl::string_view utf8);
std::string UnicodeTextToUTF8(const UnicodeText &utext);
} // namespace string_util
// other map/ptr utilties
namespace port {
template <class Collection, class Key>
bool ContainsKey(const Collection &collection, const Key &key) {
return collection.find(key) != collection.end();
}
template <class Collection>
const typename Collection::value_type::second_type &FindOrDie(
const Collection &collection,
const typename Collection::value_type::first_type &key) {
typename Collection::const_iterator it = collection.find(key);
CHECK(it != collection.end()) << "Map key not found: " << key;
return it->second;
}
template <class Collection>
const typename Collection::value_type::second_type &FindWithDefault(
const Collection &collection,
const typename Collection::value_type::first_type &key,
const typename Collection::value_type::second_type &value) {
typename Collection::const_iterator it = collection.find(key);
if (it == collection.end()) {
return value;
}
return it->second;
}
template <class Collection>
bool InsertIfNotPresent(Collection *const collection,
const typename Collection::value_type &vt) {
return collection->insert(vt).second;
}
template <class Collection>
bool InsertIfNotPresent(
Collection *const collection,
const typename Collection::value_type::first_type &key,
const typename Collection::value_type::second_type &value) {
return InsertIfNotPresent(collection,
typename Collection::value_type(key, value));
}
template <class Collection>
void InsertOrDie(Collection *const collection,
const typename Collection::value_type::first_type &key,
const typename Collection::value_type::second_type &data) {
CHECK(InsertIfNotPresent(collection, key, data)) << "duplicate key";
}
// hash
inline void mix(uint64 &a, uint64 &b, uint64 &c) { // 64bit version
a -= b;
a -= c;
a ^= (c >> 43);
b -= c;
b -= a;
b ^= (a << 9);
c -= a;
c -= b;
c ^= (b >> 8);
a -= b;
a -= c;
a ^= (c >> 38);
b -= c;
b -= a;
b ^= (a << 23);
c -= a;
c -= b;
c ^= (b >> 5);
a -= b;
a -= c;
a ^= (c >> 35);
b -= c;
b -= a;
b ^= (a << 49);
c -= a;
c -= b;
c ^= (b >> 11);
a -= b;
a -= c;
a ^= (c >> 12);
b -= c;
b -= a;
b ^= (a << 18);
c -= a;
c -= b;
c ^= (b >> 22);
}
inline uint64 FingerprintCat(uint64 x, uint64 y) {
uint64 b = 0xe08c1d668b756f82; // more of the golden ratio
mix(x, b, y);
return y;
}
} // namespace port
namespace random {
std::mt19937 *GetRandomGenerator();
template <typename T>
class ReservoirSampler {
public:
explicit ReservoirSampler(std::vector<T> *sampled, uint64 size)
: sampled_(sampled), size_(size), engine_(GetRandomGeneratorSeed()) {}
explicit ReservoirSampler(std::vector<T> *sampled, uint64 size, uint64 seed)
: sampled_(sampled), size_(size), engine_(seed) {}
virtual ~ReservoirSampler() {}
void Add(const T &item) {
if (size_ == 0) return;
++total_;
if (sampled_->size() < size_) {
sampled_->push_back(item);
} else {
std::uniform_int_distribution<uint64> dist(0, total_ - 1);
const uint64 n = dist(engine_);
if (n < sampled_->size()) (*sampled_)[n] = item;
}
}
uint64 total_size() const { return total_; }
private:
std::vector<T> *sampled_ = nullptr;
uint64 size_ = 0;
uint64 total_ = 0;
std::mt19937 engine_;
};
} // namespace random
namespace util {
inline std::string JoinPath(absl::string_view path) {
return std::string(path.data(), path.size());
}
template <typename... T>
inline std::string JoinPath(absl::string_view first, const T &...rest) {
#ifdef OS_WIN
return JoinPath(first) + "\\" + JoinPath(rest...);
#else
return JoinPath(first) + "/" + JoinPath(rest...);
#endif
}
std::string StrError(int errnum);
std::vector<std::string> StrSplitAsCSV(absl::string_view text);
inline Status OkStatus() { return Status(); }
#define DECLARE_ERROR(FUNC) \
inline util::Status FUNC##Error(absl::string_view str) { \
return util::Status(StatusCode::k##FUNC, str.data()); \
} \
inline bool Is##FUNC(const util::Status &status) { \
return status.code() == StatusCode::k##FUNC; \
}
DECLARE_ERROR(Cancelled)
DECLARE_ERROR(InvalidArgument)
DECLARE_ERROR(NotFound)
DECLARE_ERROR(AlreadyExists)
DECLARE_ERROR(ResourceExhausted)
DECLARE_ERROR(Unavailable)
DECLARE_ERROR(FailedPrecondition)
DECLARE_ERROR(OutOfRange)
DECLARE_ERROR(Unimplemented)
DECLARE_ERROR(Internal)
DECLARE_ERROR(Aborted)
DECLARE_ERROR(DeadlineExceeded)
DECLARE_ERROR(DataLoss)
DECLARE_ERROR(Unknown)
DECLARE_ERROR(PermissionDenied)
DECLARE_ERROR(Unauthenticated)
#define GTL_LOC (0)
class StatusBuilder {
public:
explicit StatusBuilder(StatusCode code) : code_(code) {}
explicit StatusBuilder(StatusCode code, int loc) : code_(code) {}
template <typename T>
StatusBuilder &operator<<(const T &value) {
os_ << value;
return *this;
}
operator Status() const { return Status(code_, os_.str()); }
private:
StatusCode code_;
std::ostringstream os_;
};
#define CHECK_OR_RETURN(condition) \
if (condition) { \
} else /* NOLINT */ \
return ::sentencepiece::util::StatusBuilder( \
::sentencepiece::util::StatusCode::kInternal) \
<< __FILE__ << "(" << __LINE__ << ") [" << #condition << "] "
#define CHECK_EQ_OR_RETURN(a, b) CHECK_OR_RETURN((a) == (b))
#define CHECK_NE_OR_RETURN(a, b) CHECK_OR_RETURN((a) != (b))
#define CHECK_GE_OR_RETURN(a, b) CHECK_OR_RETURN((a) >= (b))
#define CHECK_LE_OR_RETURN(a, b) CHECK_OR_RETURN((a) <= (b))
#define CHECK_GT_OR_RETURN(a, b) CHECK_OR_RETURN((a) > (b))
#define CHECK_LT_OR_RETURN(a, b) CHECK_OR_RETURN((a) < (b))
} // namespace util
namespace port {
template <typename T>
void STLDeleteElements(std::vector<T *> *vec) {
for (auto item : *vec) {
delete item;
}
vec->clear();
}
} // namespace port
class ThreadPool {
public:
ThreadPool(int32 n) {}
virtual ~ThreadPool() {
for (auto &task : tasks_) {
task.join();
}
}
void Schedule(std::function<void()> closure) { tasks_.emplace_back(closure); }
void StartWorkers() {}
private:
std::vector<std::thread> tasks_;
};
} // namespace sentencepiece
#endif // UTIL_H_
| 10,907 | 24.191686 | 80 | h |
sentencepiece | sentencepiece-master/src/word_model.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef WORD_MODEL_H_
#define WORD_MODEL_H_
#include "model_interface.h"
#include "sentencepiece_model.pb.h"
namespace sentencepiece {
namespace word {
// Tokenize text with whitespaces.
class Model : public ModelInterface {
public:
explicit Model(const ModelProto &model_proto);
~Model() override;
EncodeResult Encode(absl::string_view normalized) const override;
};
} // namespace word
} // namespace sentencepiece
#endif // WORD_MODEL_H_
| 1,045 | 28.885714 | 75 | h |
sentencepiece | sentencepiece-master/src/word_model_trainer.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef WORD_MODEL_TRAINER_H_
#define WORD_MODEL_TRAINER_H_
#include "sentencepiece_model.pb.h"
#include "trainer_interface.h"
namespace sentencepiece {
namespace word {
// Trainer class for word model.
//
// Word model simply counts the frequency of
// space-delimited tokens, then keep top
// |vocab_size| frequent tokens.
class Trainer : public TrainerInterface {
public:
Trainer(const TrainerSpec &trainer_spec,
const NormalizerSpec &normalizer_spec,
const NormalizerSpec &denormalizer_spec)
: TrainerInterface::TrainerInterface(trainer_spec, normalizer_spec,
denormalizer_spec) {}
util::Status Train() override;
};
} // namespace word
} // namespace sentencepiece
#endif // WORD_MODEL_TRAINER_H_
| 1,372 | 31.690476 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/container/flat_hash_map.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef ABSL_CONTAINER_FLAT_HASH_MAP_
#define ABSL_CONTAINER_FLAT_HASH_MAP_
#include <unordered_map>
namespace absl {
template <typename K, typename V, typename Hash = std::hash<K>,
typename Eq = std::equal_to<K>,
typename Allocator = std::allocator<std::pair<const K, V>>>
using flat_hash_map = std::unordered_map<K, V, Hash, Eq, Allocator>;
}
#endif // ABSL_CONTAINER_FLAT_HASH_MAP_
| 1,001 | 32.4 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/container/flat_hash_set.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef ABSL_CONTAINER_FLAT_HASH_SET_
#define ABSL_CONTAINER_FLAT_HASH_SET_
#include <unordered_set>
namespace absl {
template <typename T, typename Hash = std::hash<T>,
typename Eq = std::equal_to<T>,
typename Allocator = std::allocator<T>>
using flat_hash_set = std::unordered_set<T, Hash, Eq, Allocator>;
}
#endif // ABSL_CONTAINER_FLAT_HASH_SET_
| 966 | 31.233333 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/flags/flag.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef ABSL_FLAGS_FLAG_H_
#define ABSL_FLAGS_FLAG_H_
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace absl {
namespace internal {
struct FlagFunc;
void RegisterFlag(const std::string &name, std::shared_ptr<FlagFunc> func);
} // namespace internal
template <typename T>
class Flag {
public:
Flag(const char *name, const char *type, const char *help,
const T &defautl_value);
virtual ~Flag();
const T &value() const;
void set_value(const T &value);
void set_value_as_str(const std::string &value_as_str);
private:
T value_;
std::shared_ptr<internal::FlagFunc> func_;
};
template <typename T>
const T &GetFlag(const Flag<T> &flag) {
return flag.value();
}
template <typename T, typename V>
void SetFlag(Flag<T> *flag, const V &v) {
const T value(v);
flag->set_value(value);
}
#define HAS_ABSL_CLEANUP_FLAGS
void CleanupFlags();
} // namespace absl
#define ABSL_FLAG(Type, name, defautl_value, help) \
absl::Flag<Type> FLAGS_##name(#name, #Type, help, defautl_value);
#define ABSL_DECLARE_FLAG(Type, name) extern absl::Flag<Type> FLAGS_##name;
#endif // ABSL_FLAGS_FLAG_H_
| 1,745 | 24.304348 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/flags/parse.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef ABSL_FLAGS_PARSE_H_
#define ABSL_FLAGS_PARSE_H_
#include <vector>
namespace absl {
std::vector<char *> ParseCommandLine(int argc, char *argv[]);
} // namespace absl
#endif // ABSL_FLAGS_PARSE_H_
| 799 | 29.769231 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/memory/memory.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// -----------------------------------------------------------------------------
// File: string_view.h
// -----------------------------------------------------------------------------
//
// This file contains the definition of the `absl::string_view` class. A
// `string_view` points to a contiguous span of characters, often part or all of
// another `std::string`, double-quoted std::string literal, character array, or
// even another `string_view`.
//
// This `absl::string_view` abstraction is designed to be a drop-in
// replacement for the C++17 `std::string_view` abstraction.
#ifndef ABSL_MEMORY_MEMORY_H_
#define ABSL_MEMORY_MEMORY_H_
#include <memory>
namespace absl {
// Trait to select overloads and return types for MakeUnique.
template <typename T>
struct MakeUniqueResult {
using scalar = std::unique_ptr<T>;
};
template <typename T>
struct MakeUniqueResult<T[]> {
using array = std::unique_ptr<T[]>;
};
template <typename T, size_t N>
struct MakeUniqueResult<T[N]> {
using invalid = void;
};
// MakeUnique<T>(...) is an early implementation of C++14 std::make_unique.
// It is designed to be 100% compatible with std::make_unique so that the
// eventual switchover will be a simple renaming operation.
template <typename T, typename... Args>
typename MakeUniqueResult<T>::scalar make_unique(Args &&... args) { // NOLINT
return std::unique_ptr<T>(
new T(std::forward<Args>(args)...)); // NOLINT(build/c++11)
}
// Overload for array of unknown bound.
// The allocation of arrays needs to use the array form of new,
// and cannot take element constructor arguments.
template <typename T>
typename MakeUniqueResult<T>::array make_unique(size_t n) {
return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
}
// Reject arrays of known bound.
template <typename T, typename... Args>
typename MakeUniqueResult<T>::invalid make_unique(Args &&... /* args */) =
delete; // NOLINT
} // namespace absl
#endif // ABSL_MEMORY_MEMORY_H_
| 2,592 | 35.013889 | 80 | h |
sentencepiece | sentencepiece-master/third_party/absl/random/distributions.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef ABSL_CONTAINER_DISTRIBUTIONS_H_
#define ABSL_CONTAINER_DISTRIBUTIONS_H_
#include <random>
#include "random.h"
namespace absl {
template <typename T>
T Gaussian(SharedBitGen &generator, T mean, T stddev) {
std::normal_distribution<> dist(mean, stddev);
return dist(*generator.engine());
}
} // namespace absl
#endif // ABSL_CONTAINER_DISTRIBUTIONS_H_
| 959 | 29 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/random/random.h | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.!
#ifndef ABSL_CONTAINER_RANDOM_H_
#define ABSL_CONTAINER_RANDOM_H_
#include <random>
#include "../../../src/util.h"
using sentencepiece::random::GetRandomGenerator;
namespace absl {
class SharedBitGen {
public:
std::mt19937 *engine() { return GetRandomGenerator(); }
};
} // namespace absl
#endif // ABSL_CONTAINER_RANDOM_H_
| 926 | 26.264706 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/ascii.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ABSL_STRINGS_ASCII_H_
#define ABSL_STRINGS_ASCII_H_
#include <ctype.h>
#include <string>
#include "third_party/absl/strings/string_view.h"
namespace absl {
inline std::string AsciiStrToUpper(absl::string_view value) {
std::string upper_value = std::string(value);
std::transform(upper_value.begin(), upper_value.end(), upper_value.begin(),
::toupper);
return upper_value;
}
inline std::string AsciiStrToLower(absl::string_view value) {
std::string lower_value = std::string(value);
std::transform(lower_value.begin(), lower_value.end(), lower_value.begin(),
::tolower);
return lower_value;
}
} // namespace absl
#endif // ABSL_STRINGS_ASCII_H_
| 1,309 | 30.190476 | 77 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/match.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ABSL_STRINGS_MATCH_H_
#define ABSL_STRINGS_MATCH_H_
#include <string>
#include "third_party/absl/strings/string_view.h"
namespace absl {
inline bool StartsWith(absl::string_view text, absl::string_view prefix) {
return prefix.empty() ||
(text.size() >= prefix.size() &&
memcmp(text.data(), prefix.data(), prefix.size()) == 0);
}
inline bool EndsWith(absl::string_view text, absl::string_view suffix) {
return suffix.empty() || (text.size() >= suffix.size() &&
memcmp(text.data() + (text.size() - suffix.size()),
suffix.data(), suffix.size()) == 0);
}
} // namespace absl
#endif // ABSL_STRINGS_MATCH_H_
| 1,308 | 32.564103 | 79 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/numbers.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ABSL_STRINGS_NUMBERS_H_
#define ABSL_STRINGS_NUMBERS_H_
#include <sstream>
#include "third_party/absl/strings/string_view.h"
namespace absl {
// TODO(taku): Re-implement this, as it is slow.
template <typename T>
inline bool SimpleAtoi(absl::string_view s, T *result) {
std::stringstream ss;
return (ss << s.data() && ss >> *result);
}
} // namespace absl
#endif // ABSL_STRINGS_NUMBERS_H_
| 1,012 | 28.794118 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/str_cat.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ABSL_STRINGS_STR_CAT_H_
#define ABSL_STRINGS_STR_CAT_H_
#include <sstream>
#include <string>
#include "third_party/absl/strings/numbers.h"
#include "third_party/absl/strings/string_view.h"
namespace absl {
inline std::string StrCat(int v) {
std::ostringstream os;
os << v;
return os.str();
}
inline std::string StrCat(absl::string_view str) {
return std::string(str.data(), str.size());
}
template <typename... T>
inline std::string StrCat(absl::string_view first, const T &...rest) {
return StrCat(first) + StrCat(rest...);
}
template <typename... T>
inline std::string StrCat(int first, const T &...rest) {
return StrCat(first) + StrCat(rest...);
}
inline void StrAppend(std::string *base, absl::string_view str) {
base->append(str.data(), str.size());
}
} // namespace absl
#endif // ABSL_STRINGS_STR_CAT_H_
| 1,447 | 26.320755 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/str_format.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ABSL_STRINGS_STR_FORMAT_H
#define ABSL_STRINGS_STR_FORMAT_H
#include <stdio.h>
#include <string>
#include "third_party/absl/strings/string_view.h"
namespace absl {
template <typename... Args>
std::string StrFormat(const char *format, Args const &... args) {
const int len = ::snprintf(nullptr, 0, format, args...);
std::string s;
s.resize(len);
::snprintf(&s[0], s.size() + 1, format, args...);
return s;
}
} // namespace absl
#endif // ABSL_MEMORY_MEMORY_H_
| 1,088 | 27.657895 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/str_join.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ABSL_STRINGS_STR_JOIN_H_
#define ABSL_STRINGS_STR_JOIN_H_
#include <string>
#include "third_party/absl/strings/string_view.h"
namespace absl {
namespace {
template <typename T>
inline size_t Itoa(T val, char *s) {
char *org = s;
if (val < 0) {
*s++ = '-';
val = -val;
}
char *t = s;
T mod = 0;
while (val) {
mod = val % 10;
*t++ = static_cast<char>(mod) + '0';
val /= 10;
}
if (s == t) {
*t++ = '0';
}
*t = '\0';
std::reverse(s, t);
return static_cast<size_t>(t - org);
}
} // namespace
inline std::string StrJoin(const std::vector<std::string> &tokens,
absl::string_view delim) {
std::string result;
if (!tokens.empty()) {
result.append(tokens[0]);
}
for (size_t i = 1; i < tokens.size(); ++i) {
result.append(delim.data(), delim.size());
result.append(tokens[i]);
}
return result;
}
inline std::string StrJoin(const std::vector<absl::string_view> &tokens,
absl::string_view delim) {
std::string result;
if (!tokens.empty()) {
result.append(tokens[0].data(), tokens[0].size());
}
for (size_t i = 1; i < tokens.size(); ++i) {
result.append(delim.data(), delim.size());
result.append(tokens[i].data(), tokens[i].size());
}
return result;
}
inline std::string StrJoin(const std::vector<int> &tokens,
absl::string_view delim) {
std::string result;
char buf[32];
if (!tokens.empty()) {
const size_t len = Itoa(tokens[0], buf);
result.append(buf, len);
}
for (size_t i = 1; i < tokens.size(); ++i) {
result.append(delim.data(), delim.size());
const size_t len = Itoa(tokens[i], buf);
result.append(buf, len);
}
return result;
}
} // namespace absl
#endif // ABSL_STRINGS_STR_CAT_H_
| 2,413 | 24.145833 | 75 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/str_replace.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ABSL_STRINGS_STR_REPLACE_H_
#define ABSL_STRINGS_STR_REPLACE_H_
#include <string>
#include "third_party/absl/strings/string_view.h"
namespace absl {
inline void StringReplace(absl::string_view s, absl::string_view oldsub,
absl::string_view newsub, bool replace_all,
std::string *res) {
if (oldsub.empty()) {
res->append(s.data(), s.size());
return;
}
absl::string_view::size_type start_pos = 0;
do {
const absl::string_view::size_type pos = s.find(oldsub, start_pos);
if (pos == absl::string_view::npos) {
break;
}
res->append(s.data() + start_pos, pos - start_pos);
res->append(newsub.data(), newsub.size());
start_pos = pos + oldsub.size();
} while (replace_all);
res->append(s.data() + start_pos, s.size() - start_pos);
}
inline std::string StringReplace(absl::string_view s, absl::string_view oldsub,
absl::string_view newsub, bool replace_all) {
std::string ret;
StringReplace(s, oldsub, newsub, replace_all, &ret);
return ret;
}
inline std::string StrReplaceAll(
absl::string_view s,
const std::vector<std::pair<absl::string_view, absl::string_view>>
&patterns) {
std::string prev(s.data(), s.size());
std::string result;
for (const auto &it : patterns) {
result.clear();
StringReplace(prev, it.first, it.second, true, &result);
prev = result;
}
return result;
}
} // namespace absl
#endif // ABSL_STRINGS_STR_REPLACE_H_
| 2,127 | 29.84058 | 79 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/str_split.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ABSL_STRINGS_STR_SPLIT_H_
#define ABSL_STRINGS_STR_SPLIT_H_
#include <string>
#include <vector>
#include "third_party/absl/strings/string_view.h"
namespace absl {
namespace internal {
class Splitter {
public:
Splitter(absl::string_view str, absl::string_view delim, bool allow_empty) {
size_t current_pos = 0;
size_t found_pos = 0;
while ((found_pos = str.find_first_of(delim, current_pos)) !=
absl::string_view::npos) {
if ((allow_empty && found_pos >= current_pos) ||
(!allow_empty && found_pos > current_pos)) {
result_.push_back(str.substr(current_pos, found_pos - current_pos));
}
current_pos = found_pos + 1;
}
if (str.size() > current_pos) {
result_.push_back(str.substr(current_pos, str.size() - current_pos));
}
}
template <class T>
operator std::vector<T>() const;
using const_iterator = std::vector<absl::string_view>::const_iterator;
const_iterator begin() const { return result_.begin(); }
const_iterator end() const { return result_.end(); }
private:
std::vector<absl::string_view> result_;
};
template <>
inline Splitter::operator std::vector<std::string>() const {
std::vector<std::string> x(result_.size());
for (size_t i = 0; i < x.size(); ++i)
x[i].assign(result_[i].data(), result_[i].size());
return x;
}
template <>
inline Splitter::operator std::vector<absl::string_view>() const {
return result_;
}
} // namespace internal
inline constexpr bool AllowEmpty() { return true; };
inline internal::Splitter StrSplit(absl::string_view str,
absl::string_view delim,
bool allow_empty = false) {
return internal::Splitter(str, delim, allow_empty);
}
inline internal::Splitter StrSplit(absl::string_view str, const char c,
bool allow_empty = false) {
char delim[2];
delim[0] = c;
delim[1] = '\0';
return internal::Splitter(str, delim, allow_empty);
}
} // namespace absl
#endif // ABSL_STRINGS_STR_SPLIT_H_
| 2,669 | 29.689655 | 78 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/string_view.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// -----------------------------------------------------------------------------
// File: string_view.h
// -----------------------------------------------------------------------------
//
// This file contains the definition of the `absl::string_view` class. A
// `string_view` points to a contiguous span of characters, often part or all of
// another `std::string`, double-quoted std::string literal, character array, or
// even another `string_view`.
//
// This `absl::string_view` abstraction is designed to be a drop-in
// replacement for the C++17 `std::string_view` abstraction.
#ifndef ABSL_STRINGS_STRING_VIEW_H_
#define ABSL_STRINGS_STRING_VIEW_H_
#include <algorithm>
#include <string_view>
namespace absl {
using std::string_view;
// ClippedSubstr()
//
// Like `s.substr(pos, n)`, but clips `pos` to an upper bound of `s.size()`.
// Provided because std::string_view::substr throws if `pos > size()`
inline string_view ClippedSubstr(string_view s, size_t pos,
size_t n = string_view::npos) {
pos = std::min(pos, static_cast<size_t>(s.size()));
return s.substr(pos, n);
}
// NullSafeStringView()
//
// Creates an `absl::string_view` from a pointer `p` even if it's null-valued.
// This function should be used where an `absl::string_view` can be created from
// a possibly-null pointer.
inline string_view NullSafeStringView(const char* p) {
return p ? string_view(p) : string_view();
}
} // namespace absl
#endif // ABSL_STRINGS_STRING_VIEW_H_
| 2,106 | 35.327586 | 80 | h |
sentencepiece | sentencepiece-master/third_party/absl/strings/strip.h | //
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef ABSL_STRINGS_STRIP_H_
#define ABSL_STRINGS_STRIP_H_
#include <string>
#include "third_party/absl/strings/match.h"
namespace absl {
inline bool ConsumePrefix(absl::string_view *str, absl::string_view expected) {
if (!absl::StartsWith(*str, expected)) return false;
str->remove_prefix(expected.size());
return true;
}
} // namespace absl
#endif // ABSL_STRINGS_STRIP_H
| 991 | 29.060606 | 79 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/any.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_ANY_H__
#define GOOGLE_PROTOBUF_ANY_H__
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class FieldDescriptor;
class Message;
namespace internal {
extern const char kAnyFullTypeName[]; // "google.protobuf.Any".
extern const char kTypeGoogleApisComPrefix[]; // "type.googleapis.com/".
extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/".
std::string GetTypeUrl(StringPiece message_name,
StringPiece type_url_prefix);
// Helper class used to implement google::protobuf::Any.
class PROTOBUF_EXPORT AnyMetadata {
typedef ArenaStringPtr UrlType;
typedef ArenaStringPtr ValueType;
public:
// AnyMetadata does not take ownership of "type_url" and "value".
constexpr AnyMetadata(UrlType* type_url, ValueType* value)
: type_url_(type_url), value_(value) {}
// Packs a message using the default type URL prefix: "type.googleapis.com".
// The resulted type URL will be "type.googleapis.com/<message_full_name>".
template <typename T>
void PackFrom(const T& message) {
InternalPackFrom(message, kTypeGoogleApisComPrefix, T::FullMessageName());
}
void PackFrom(const Message& message);
// Packs a message using the given type URL prefix. The type URL will be
// constructed by concatenating the message type's full name to the prefix
// with an optional "/" separator if the prefix doesn't already end with "/".
// For example, both PackFrom(message, "type.googleapis.com") and
// PackFrom(message, "type.googleapis.com/") yield the same result type
// URL: "type.googleapis.com/<message_full_name>".
template <typename T>
void PackFrom(const T& message, StringPiece type_url_prefix) {
InternalPackFrom(message, type_url_prefix, T::FullMessageName());
}
void PackFrom(const Message& message, StringPiece type_url_prefix);
// Unpacks the payload into the given message. Returns false if the message's
// type doesn't match the type specified in the type URL (i.e., the full
// name after the last "/" of the type URL doesn't match the message's actual
// full name) or parsing the payload has failed.
template <typename T>
bool UnpackTo(T* message) const {
return InternalUnpackTo(T::FullMessageName(), message);
}
bool UnpackTo(Message* message) const;
// Checks whether the type specified in the type URL matches the given type.
// A type is considered matching if its full name matches the full name after
// the last "/" in the type URL.
template <typename T>
bool Is() const {
return InternalIs(T::FullMessageName());
}
private:
void InternalPackFrom(const MessageLite& message,
StringPiece type_url_prefix,
StringPiece type_name);
bool InternalUnpackTo(StringPiece type_name,
MessageLite* message) const;
bool InternalIs(StringPiece type_name) const;
UrlType* type_url_;
ValueType* value_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AnyMetadata);
};
// Get the proto type name from Any::type_url value. For example, passing
// "type.googleapis.com/rpc.QueryOrigin" will return "rpc.QueryOrigin" in
// *full_type_name. Returns false if the type_url does not have a "/"
// in the type url separating the full type name.
//
// NOTE: this function is available publicly as:
// google::protobuf::Any() // static method on the generated message type.
bool ParseAnyTypeUrl(StringPiece type_url, std::string* full_type_name);
// Get the proto type name and prefix from Any::type_url value. For example,
// passing "type.googleapis.com/rpc.QueryOrigin" will return
// "type.googleapis.com/" in *url_prefix and "rpc.QueryOrigin" in
// *full_type_name. Returns false if the type_url does not have a "/" in the
// type url separating the full type name.
bool ParseAnyTypeUrl(StringPiece type_url, std::string* url_prefix,
std::string* full_type_name);
// See if message is of type google.protobuf.Any, if so, return the descriptors
// for "type_url" and "value" fields.
bool GetAnyFieldDescriptors(const Message& message,
const FieldDescriptor** type_url_field,
const FieldDescriptor** value_field);
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_ANY_H__
| 6,215 | 40.165563 | 79 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/arena_impl.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file defines an Arena allocator for better allocation performance.
#ifndef GOOGLE_PROTOBUF_ARENA_IMPL_H__
#define GOOGLE_PROTOBUF_ARENA_IMPL_H__
#include <atomic>
#include <limits>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#ifdef ADDRESS_SANITIZER
#include <sanitizer/asan_interface.h>
#endif // ADDRESS_SANITIZER
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
struct ArenaOptions;
namespace internal {
inline size_t AlignUpTo8(size_t n) {
// Align n to next multiple of 8 (from Hacker's Delight, Chapter 3.)
return (n + 7) & static_cast<size_t>(-8);
}
using LifecycleIdAtomic = uint64_t;
void PROTOBUF_EXPORT ArenaFree(void* object, size_t size);
// MetricsCollector collects stats for a particular arena.
class PROTOBUF_EXPORT ArenaMetricsCollector {
public:
virtual ~ArenaMetricsCollector();
// Invoked when the arena is about to be destroyed. This method will
// typically finalize any metric collection and delete the collector.
// space_allocated is the space used by the arena.
virtual void OnDestroy(uint64 space_allocated) = 0;
// OnReset() is called when the associated arena is reset.
// space_allocated is the space used by the arena just before the reset.
virtual void OnReset(uint64 space_allocated) = 0;
// Does OnAlloc() need to be called? If false, metric collection overhead
// will be reduced since we will not do extra work per allocation.
virtual bool RecordAllocs() = 0;
// OnAlloc is called when an allocation happens.
// type_info is promised to be static - its lifetime extends to
// match program's lifetime (It is given by typeid operator).
// Note: typeid(void) will be passed as allocated_type every time we
// intentionally want to avoid monitoring an allocation. (i.e. internal
// allocations for managing the arena)
virtual void OnAlloc(const std::type_info* allocated_type,
uint64 alloc_size) = 0;
};
class ArenaImpl;
// A thread-unsafe Arena that can only be used within its owning thread.
class PROTOBUF_EXPORT SerialArena {
public:
// Blocks are variable length malloc-ed objects. The following structure
// describes the common header for all blocks.
class PROTOBUF_EXPORT Block {
public:
Block(size_t size, Block* next, bool special, bool user_owned)
: next_and_bits_(reinterpret_cast<uintptr_t>(next) | (special ? 1 : 0) |
(user_owned ? 2 : 0)),
pos_(kBlockHeaderSize),
size_(size) {
GOOGLE_DCHECK_EQ(reinterpret_cast<uintptr_t>(next) & 3, 0u);
}
char* Pointer(size_t n) {
GOOGLE_DCHECK(n <= size_);
return reinterpret_cast<char*>(this) + n;
}
// One of the blocks may be special. This is either a user-supplied
// initial block, or a block we created at startup to hold Options info.
// A special block is not deleted by Reset.
bool special() const { return (next_and_bits_ & 1) != 0; }
// Whether or not this current block is owned by the user.
// Only special blocks can be user_owned.
bool user_owned() const { return (next_and_bits_ & 2) != 0; }
Block* next() const {
const uintptr_t bottom_bits = 3;
return reinterpret_cast<Block*>(next_and_bits_ & ~bottom_bits);
}
void clear_next() {
next_and_bits_ &= 3; // Set next to nullptr, preserve bottom bits.
}
size_t pos() const { return pos_; }
size_t size() const { return size_; }
void set_pos(size_t pos) { pos_ = pos; }
private:
// Holds pointer to next block for this thread + special/user_owned bits.
uintptr_t next_and_bits_;
size_t pos_;
size_t size_;
// data follows
};
// The allocate/free methods here are a little strange, since SerialArena is
// allocated inside a Block which it also manages. This is to avoid doing
// an extra allocation for the SerialArena itself.
// Creates a new SerialArena inside Block* and returns it.
static SerialArena* New(Block* b, void* owner, ArenaImpl* arena);
void CleanupList();
uint64 SpaceUsed() const;
bool HasSpace(size_t n) { return n <= static_cast<size_t>(limit_ - ptr_); }
void* AllocateAligned(size_t n) {
GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
GOOGLE_DCHECK_GE(limit_, ptr_);
if (PROTOBUF_PREDICT_FALSE(!HasSpace(n))) {
return AllocateAlignedFallback(n);
}
void* ret = ptr_;
ptr_ += n;
#ifdef ADDRESS_SANITIZER
ASAN_UNPOISON_MEMORY_REGION(ret, n);
#endif // ADDRESS_SANITIZER
return ret;
}
// Allocate space if the current region provides enough space.
bool MaybeAllocateAligned(size_t n, void** out) {
GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
GOOGLE_DCHECK_GE(limit_, ptr_);
if (PROTOBUF_PREDICT_FALSE(!HasSpace(n))) return false;
void* ret = ptr_;
ptr_ += n;
#ifdef ADDRESS_SANITIZER
ASAN_UNPOISON_MEMORY_REGION(ret, n);
#endif // ADDRESS_SANITIZER
*out = ret;
return true;
}
void AddCleanup(void* elem, void (*cleanup)(void*)) {
if (PROTOBUF_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) {
AddCleanupFallback(elem, cleanup);
return;
}
cleanup_ptr_->elem = elem;
cleanup_ptr_->cleanup = cleanup;
cleanup_ptr_++;
}
void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*)) {
void* ret = AllocateAligned(n);
AddCleanup(ret, cleanup);
return ret;
}
Block* head() const { return head_; }
void* owner() const { return owner_; }
SerialArena* next() const { return next_; }
void set_next(SerialArena* next) { next_ = next; }
static Block* NewBlock(Block* last_block, size_t min_bytes, ArenaImpl* arena);
private:
// Node contains the ptr of the object to be cleaned up and the associated
// cleanup function ptr.
struct CleanupNode {
void* elem; // Pointer to the object to be cleaned up.
void (*cleanup)(void*); // Function pointer to the destructor or deleter.
};
// Cleanup uses a chunked linked list, to reduce pointer chasing.
struct CleanupChunk {
static size_t SizeOf(size_t i) {
return sizeof(CleanupChunk) + (sizeof(CleanupNode) * (i - 1));
}
size_t size; // Total elements in the list.
CleanupChunk* next; // Next node in the list.
CleanupNode nodes[1]; // True length is |size|.
};
ArenaImpl* arena_; // Containing arena.
void* owner_; // &ThreadCache of this thread;
Block* head_; // Head of linked list of blocks.
CleanupChunk* cleanup_; // Head of cleanup list.
SerialArena* next_; // Next SerialArena in this linked list.
// Next pointer to allocate from. Always 8-byte aligned. Points inside
// head_ (and head_->pos will always be non-canonical). We keep these
// here to reduce indirection.
char* ptr_;
char* limit_;
// Next CleanupList members to append to. These point inside cleanup_.
CleanupNode* cleanup_ptr_;
CleanupNode* cleanup_limit_;
void* AllocateAlignedFallback(size_t n);
void AddCleanupFallback(void* elem, void (*cleanup)(void*));
void CleanupListFallback();
public:
static constexpr size_t kBlockHeaderSize =
(sizeof(Block) + 7) & static_cast<size_t>(-8);
};
// This class provides the core Arena memory allocation library. Different
// implementations only need to implement the public interface below.
// Arena is not a template type as that would only be useful if all protos
// in turn would be templates, which will/cannot happen. However separating
// the memory allocation part from the cruft of the API users expect we can
// use #ifdef the select the best implementation based on hardware / OS.
class PROTOBUF_EXPORT ArenaImpl {
public:
static const size_t kDefaultStartBlockSize = 256;
static const size_t kDefaultMaxBlockSize = 8192;
ArenaImpl() { Init(false); }
ArenaImpl(char* mem, size_t size) {
GOOGLE_DCHECK_EQ(reinterpret_cast<uintptr_t>(mem) & 7, 0u);
Init(false);
// Ignore initial block if it is too small.
if (mem != nullptr && size >= kBlockHeaderSize + kSerialArenaSize) {
SetInitialBlock(new (mem) SerialArena::Block(size, nullptr, true, true));
}
}
explicit ArenaImpl(const ArenaOptions& options);
// Destructor deletes all owned heap allocated objects, and destructs objects
// that have non-trivial destructors, except for proto2 message objects whose
// destructors can be skipped. Also, frees all blocks except the initial block
// if it was passed in.
~ArenaImpl();
uint64 Reset();
uint64 SpaceAllocated() const;
uint64 SpaceUsed() const;
void* AllocateAligned(size_t n) {
SerialArena* arena;
if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
return arena->AllocateAligned(n);
} else {
return AllocateAlignedFallback(n);
}
}
// This function allocates n bytes if the common happy case is true and
// returns true. Otherwise does nothing and returns false. This strange
// semantics is necessary to allow callers to program functions that only
// have fallback function calls in tail position. This substantially improves
// code for the happy path.
PROTOBUF_ALWAYS_INLINE bool MaybeAllocateAligned(size_t n, void** out) {
SerialArena* a;
if (PROTOBUF_PREDICT_TRUE(GetSerialArenaFromThreadCache(&a))) {
return a->MaybeAllocateAligned(n, out);
}
return false;
}
void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*));
// Add object pointer and cleanup function pointer to the list.
void AddCleanup(void* elem, void (*cleanup)(void*));
inline void RecordAlloc(const std::type_info* allocated_type,
size_t n) const {
if (PROTOBUF_PREDICT_FALSE(record_allocs())) {
options_->metrics_collector->OnAlloc(allocated_type, n);
}
}
std::pair<void*, size_t> NewBuffer(size_t last_size, size_t min_bytes);
private:
// Pointer to a linked list of SerialArena.
std::atomic<SerialArena*> threads_;
std::atomic<SerialArena*> hint_; // Fast thread-local block access
std::atomic<size_t> space_allocated_; // Total size of all allocated blocks.
// Unique for each arena. Changes on Reset().
// Least-significant-bit is 1 iff allocations should be recorded.
uint64 lifecycle_id_;
struct Options {
size_t start_block_size;
size_t max_block_size;
void* (*block_alloc)(size_t);
void (*block_dealloc)(void*, size_t);
ArenaMetricsCollector* metrics_collector;
};
Options* options_ = nullptr;
void* AllocateAlignedFallback(size_t n);
void* AllocateAlignedAndAddCleanupFallback(size_t n, void (*cleanup)(void*));
void AddCleanupFallback(void* elem, void (*cleanup)(void*));
void Init(bool record_allocs);
void SetInitialBlock(
SerialArena::Block* block); // Can be called right after Init()
// Return true iff allocations should be recorded in a metrics collector.
inline bool record_allocs() const { return lifecycle_id_ & 1; }
// Invoke fn(b) for every Block* b.
template <typename Functor>
void PerBlock(Functor fn) {
// By omitting an Acquire barrier we ensure that any user code that doesn't
// properly synchronize Reset() or the destructor will throw a TSAN warning.
SerialArena* serial = threads_.load(std::memory_order_relaxed);
while (serial) {
// fn() may delete blocks and arenas, so fetch next pointers before fn();
SerialArena* cur = serial;
serial = serial->next();
for (auto* block = cur->head(); block != nullptr;) {
auto* b = block;
block = b->next();
fn(b);
}
}
}
// Delete or Destruct all objects owned by the arena.
void CleanupList();
inline void CacheSerialArena(SerialArena* serial) {
thread_cache().last_serial_arena = serial;
thread_cache().last_lifecycle_id_seen = lifecycle_id_;
// TODO(haberman): evaluate whether we would gain efficiency by getting rid
// of hint_. It's the only write we do to ArenaImpl in the allocation path,
// which will dirty the cache line.
hint_.store(serial, std::memory_order_release);
}
PROTOBUF_ALWAYS_INLINE bool GetSerialArenaFast(SerialArena** arena) {
if (GetSerialArenaFromThreadCache(arena)) return true;
// Check whether we own the last accessed SerialArena on this arena. This
// fast path optimizes the case where a single thread uses multiple arenas.
ThreadCache* tc = &thread_cache();
SerialArena* serial = hint_.load(std::memory_order_acquire);
if (PROTOBUF_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) {
*arena = serial;
return true;
}
return false;
}
PROTOBUF_ALWAYS_INLINE bool GetSerialArenaFromThreadCache(
SerialArena** arena) {
// If this thread already owns a block in this arena then try to use that.
// This fast path optimizes the case where multiple threads allocate from
// the same arena.
ThreadCache* tc = &thread_cache();
if (PROTOBUF_PREDICT_TRUE(tc->last_lifecycle_id_seen == lifecycle_id_)) {
*arena = tc->last_serial_arena;
return true;
}
return false;
}
SerialArena* GetSerialArenaFallback(void* me);
#ifdef _MSC_VER
#pragma warning(disable : 4324)
#endif
struct alignas(64) ThreadCache {
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
// If we are using the ThreadLocalStorage class to store the ThreadCache,
// then the ThreadCache's default constructor has to be responsible for
// initializing it.
ThreadCache()
: next_lifecycle_id(0),
last_lifecycle_id_seen(-1),
last_serial_arena(NULL) {}
#endif
// Number of per-thread lifecycle IDs to reserve. Must be power of two.
// To reduce contention on a global atomic, each thread reserves a batch of
// IDs. The following number is calculated based on a stress test with
// ~6500 threads all frequently allocating a new arena.
static constexpr size_t kPerThreadIds = 256;
// Next lifecycle ID available to this thread. We need to reserve a new
// batch, if `next_lifecycle_id & (kPerThreadIds - 1) == 0`.
uint64 next_lifecycle_id;
// The ThreadCache is considered valid as long as this matches the
// lifecycle_id of the arena being used.
uint64 last_lifecycle_id_seen;
SerialArena* last_serial_arena;
};
// Lifecycle_id can be highly contended variable in a situation of lots of
// arena creation. Make sure that other global variables are not sharing the
// cacheline.
#ifdef _MSC_VER
#pragma warning(disable : 4324)
#endif
struct alignas(64) CacheAlignedLifecycleIdGenerator {
std::atomic<LifecycleIdAtomic> id;
};
static CacheAlignedLifecycleIdGenerator lifecycle_id_generator_;
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
// Android ndk does not support __thread keyword so we use a custom thread
// local storage class we implemented.
// iOS also does not support the __thread keyword.
static ThreadCache& thread_cache();
#elif defined(PROTOBUF_USE_DLLS)
// Thread local variables cannot be exposed through DLL interface but we can
// wrap them in static functions.
static ThreadCache& thread_cache();
#else
static PROTOBUF_THREAD_LOCAL ThreadCache thread_cache_;
static ThreadCache& thread_cache() { return thread_cache_; }
#endif
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArenaImpl);
// All protos have pointers back to the arena hence Arena must have
// pointer stability.
ArenaImpl(ArenaImpl&&) = delete;
ArenaImpl& operator=(ArenaImpl&&) = delete;
public:
// kBlockHeaderSize is sizeof(Block), aligned up to the nearest multiple of 8
// to protect the invariant that pos is always at a multiple of 8.
static constexpr size_t kBlockHeaderSize = SerialArena::kBlockHeaderSize;
static constexpr size_t kSerialArenaSize =
(sizeof(SerialArena) + 7) & static_cast<size_t>(-8);
static constexpr size_t kOptionsSize =
(sizeof(Options) + 7) & static_cast<size_t>(-8);
static_assert(kBlockHeaderSize % 8 == 0,
"kBlockHeaderSize must be a multiple of 8.");
static_assert(kSerialArenaSize % 8 == 0,
"kSerialArenaSize must be a multiple of 8.");
};
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_ARENA_IMPL_H__
| 18,092 | 35.77439 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/arenastring.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_ARENASTRING_H__
#define GOOGLE_PROTOBUF_ARENASTRING_H__
#include <string>
#include <type_traits>
#include <utility>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/port.h>
#include <google/protobuf/port_def.inc>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
namespace internal {
// Lazy string instance to support string fields with non-empty default.
// These are initialized on the first call to .get().
class PROTOBUF_EXPORT LazyString {
public:
// We explicitly make LazyString an aggregate so that MSVC can do constant
// initialization on it without marking it `constexpr`.
// We do not want to use `constexpr` because it makes it harder to have extern
// storage for it and causes library bloat.
struct InitValue {
const char* ptr;
size_t size;
};
// We keep a union of the initialization value and the std::string to save on
// space. We don't need the string array after Init() is done.
union {
mutable InitValue init_value_;
alignas(std::string) mutable char string_buf_[sizeof(std::string)];
};
mutable std::atomic<const std::string*> inited_;
const std::string& get() const {
// This check generates less code than a call-once invocation.
auto* res = inited_.load(std::memory_order_acquire);
if (PROTOBUF_PREDICT_FALSE(res == nullptr)) return Init();
return *res;
}
private:
// Initialize the string in `string_buf_`, update `inited_` and return it.
// We return it here to avoid having to read it again in the inlined code.
const std::string& Init() const;
};
template <typename T>
class TaggedPtr {
public:
TaggedPtr() = default;
explicit constexpr TaggedPtr(const std::string* ptr)
: ptr_(const_cast<std::string*>(ptr)) {}
void SetTagged(T* p) {
Set(p);
ptr_ = reinterpret_cast<void*>(as_int() | 1);
}
void Set(T* p) { ptr_ = p; }
T* Get() const { return reinterpret_cast<T*>(as_int() & -2); }
bool IsTagged() const { return as_int() & 1; }
// Returned value is only safe to dereference if IsTagged() == false.
// It is safe to compare.
T* UnsafeGet() const { return static_cast<T*>(ptr_); }
bool IsNull() { return ptr_ == nullptr; }
private:
uintptr_t as_int() const { return reinterpret_cast<uintptr_t>(ptr_); }
void* ptr_;
};
static_assert(std::is_trivial<TaggedPtr<std::string>>::value,
"TaggedPtr must be trivial");
// This class encapsulates a pointer to a std::string with or without a donated
// buffer, tagged by bottom bit. It is a high-level wrapper that almost directly
// corresponds to the interface required by string fields in generated
// code. It replaces the old std::string* pointer in such cases.
//
// The object has different but similar code paths for when the default value is
// the empty string and when it is a non-empty string.
// The empty string is handled different throughout the library and there is a
// single global instance of it we can share.
//
// For fields with an empty string default value, there are three distinct
// states:
//
// - Pointer set to 'String' tag (LSB is 0), equal to
// &GetEmptyStringAlreadyInited(): field is set to its default value. Points
// to a true std::string*, but we do not own that std::string* (it's a
// globally shared instance).
//
// - Pointer set to 'String' tag (LSB is 0), but not equal to the global empty
// string: field points to a true std::string* instance that we own. This
// instance is either on the heap or on the arena (i.e. registered on
// free()/destructor-call list) as appropriate.
//
// - Pointer set to 'DonatedString' tag (LSB is 1): points to a std::string
// instance with a buffer on the arena (arena != NULL, always, in this case).
//
// For fields with a non-empty string default value, there are three distinct
// states:
//
// - Pointer set to 'String' tag (LSB is 0), equal to `nullptr`:
// Field is in "default" mode and does not point to any actual instance.
// Methods that might need to create an instance of the object will pass a
// `const LazyString&` for it.
//
// - Pointer set to 'String' tag (LSB is 0), but not equal to `nullptr`:
// field points to a true std::string* instance that we own. This instance is
// either on the heap or on the arena (i.e. registered on
// free()/destructor-call list) as appropriate.
//
// - Pointer set to 'DonatedString' tag (LSB is 1): points to a std::string
// instance with a buffer on the arena (arena != NULL, always, in this case).
//
// Generated code and reflection code both ensure that ptr_ is never null for
// fields with an empty default.
// Because ArenaStringPtr is used in oneof unions, its constructor is a NOP and
// so the field is always manually initialized via method calls.
//
// Side-note: why pass information about the default on every API call? Because
// we don't want to hold it in a member variable, or else this would go into
// every proto message instance. This would be a huge waste of space, since the
// default instance pointer is typically a global (static class field). We want
// the generated code to be as efficient as possible, and if we take
// the default value information as a parameter that's in practice taken from a
// static class field, and compare ptr_ to the default value, we end up with a
// single "cmp %reg, GLOBAL" in the resulting machine code. (Note that this also
// requires the String tag to be 0 so we can avoid the mask before comparing.)
struct PROTOBUF_EXPORT ArenaStringPtr {
ArenaStringPtr() = default;
explicit constexpr ArenaStringPtr(const std::string* default_value)
: tagged_ptr_(default_value) {}
// Some methods below are overloaded on a `default_value` and on tags.
// The tagged overloads help reduce code size in the callers in generated
// code, while the `default_value` overloads are useful from reflection.
// By-value empty struct arguments are elided in the ABI.
struct EmptyDefault {};
struct NonEmptyDefault {};
void Set(const std::string* default_value, ConstStringParam value,
::google::protobuf::Arena* arena);
void Set(const std::string* default_value, std::string&& value,
::google::protobuf::Arena* arena);
void Set(EmptyDefault, ConstStringParam value, ::google::protobuf::Arena* arena);
void Set(EmptyDefault, std::string&& value, ::google::protobuf::Arena* arena);
void Set(NonEmptyDefault, ConstStringParam value, ::google::protobuf::Arena* arena);
void Set(NonEmptyDefault, std::string&& value, ::google::protobuf::Arena* arena);
// Basic accessors.
const std::string& Get() const PROTOBUF_ALWAYS_INLINE {
// Unconditionally mask away the tag.
return *tagged_ptr_.Get();
}
const std::string* GetPointer() const PROTOBUF_ALWAYS_INLINE {
// Unconditionally mask away the tag.
return tagged_ptr_.Get();
}
// For fields with an empty default value.
std::string* Mutable(EmptyDefault, ::google::protobuf::Arena* arena);
// For fields with a non-empty default value.
std::string* Mutable(const LazyString& default_value, ::google::protobuf::Arena* arena);
// Release returns a std::string* instance that is heap-allocated and is not
// Own()'d by any arena. If the field is not set, this returns NULL. The
// caller retains ownership. Clears this field back to NULL state. Used to
// implement release_<field>() methods on generated classes.
std::string* Release(const std::string* default_value,
::google::protobuf::Arena* arena);
std::string* ReleaseNonDefault(const std::string* default_value,
::google::protobuf::Arena* arena);
// Takes a std::string that is heap-allocated, and takes ownership. The
// std::string's destructor is registered with the arena. Used to implement
// set_allocated_<field> in generated classes.
void SetAllocated(const std::string* default_value, std::string* value,
::google::protobuf::Arena* arena);
// Swaps internal pointers. Arena-safety semantics: this is guarded by the
// logic in Swap()/UnsafeArenaSwap() at the message level, so this method is
// 'unsafe' if called directly.
inline void Swap(ArenaStringPtr* other, const std::string* default_value,
Arena* arena) PROTOBUF_ALWAYS_INLINE;
// Frees storage (if not on an arena).
void Destroy(const std::string* default_value, ::google::protobuf::Arena* arena);
void Destroy(EmptyDefault, ::google::protobuf::Arena* arena);
void Destroy(NonEmptyDefault, ::google::protobuf::Arena* arena);
// Clears content, but keeps allocated std::string, to avoid the overhead of
// heap operations. After this returns, the content (as seen by the user) will
// always be the empty std::string. Assumes that |default_value| is an empty
// std::string.
void ClearToEmpty();
// Clears content, assuming that the current value is not the empty
// string default.
void ClearNonDefaultToEmpty();
// Clears content, but keeps allocated std::string if arena != NULL, to avoid
// the overhead of heap operations. After this returns, the content (as seen
// by the user) will always be equal to |default_value|.
void ClearToDefault(const LazyString& default_value, ::google::protobuf::Arena* arena);
// Called from generated code / reflection runtime only. Resets value to point
// to a default string pointer, with the semantics that this
// ArenaStringPtr does not own the pointed-to memory. Disregards initial value
// of ptr_ (so this is the *ONLY* safe method to call after construction or
// when reinitializing after becoming the active field in a oneof union).
inline void UnsafeSetDefault(const std::string* default_value);
// Returns a mutable pointer, but doesn't initialize the string to the
// default value.
std::string* MutableNoArenaNoDefault(const std::string* default_value);
// Get a mutable pointer with unspecified contents.
// Similar to `MutableNoArenaNoDefault`, but also handles the arena case.
// If the value was donated, the contents are discarded.
std::string* MutableNoCopy(const std::string* default_value,
::google::protobuf::Arena* arena);
// Destroy the string. Assumes `arena == nullptr`.
void DestroyNoArena(const std::string* default_value);
// Internal setter used only at parse time to directly set a donated string
// value.
void UnsafeSetTaggedPointer(TaggedPtr<std::string> value) {
tagged_ptr_ = value;
}
// Generated code only! An optimization, in certain cases the generated
// code is certain we can obtain a std::string with no default checks and
// tag tests.
std::string* UnsafeMutablePointer() PROTOBUF_RETURNS_NONNULL;
inline bool IsDefault(const std::string* default_value) const {
// Relies on the fact that kPtrTagString == 0, so if IsString(), ptr_ is the
// actual std::string pointer (and if !IsString(), ptr_ will never be equal
// to any aligned |default_value| pointer). The key is that we want to avoid
// masking in the fastpath const-pointer Get() case for non-arena code.
return tagged_ptr_.UnsafeGet() == default_value;
}
private:
TaggedPtr<std::string> tagged_ptr_;
bool IsDonatedString() const { return false; }
// Slow paths.
// MutableSlow requires that !IsString() || IsDefault
// Variadic to support 0 args for EmptyDefault and 1 arg for LazyString.
template <typename... Lazy>
std::string* MutableSlow(::google::protobuf::Arena* arena, const Lazy&... lazy_default);
};
inline void ArenaStringPtr::UnsafeSetDefault(const std::string* value) {
tagged_ptr_.Set(const_cast<std::string*>(value));
}
inline void ArenaStringPtr::Swap(ArenaStringPtr* other,
const std::string* default_value,
Arena* arena) {
#ifndef NDEBUG
// For debug builds, we swap the contents of the string, rather than the
// std::string instances themselves. This invalidates previously taken const
// references that are (per our documentation) invalidated by calling Swap()
// on the message.
//
// If both strings are the default_value, swapping is uninteresting.
// Otherwise, we use ArenaStringPtr::Mutable() to access the std::string, to
// ensure that we do not try to mutate default_value itself.
if (IsDefault(default_value) && other->IsDefault(default_value)) {
return;
}
if (default_value == nullptr) {
// If we have non-empty default, then `default_value` is null and we can't
// call Mutable the same way. Just do the regular swap.
std::swap(tagged_ptr_, other->tagged_ptr_);
} else {
std::string* this_ptr = Mutable(EmptyDefault{}, arena);
std::string* other_ptr = other->Mutable(EmptyDefault{}, arena);
this_ptr->swap(*other_ptr);
}
#else
std::swap(tagged_ptr_, other->tagged_ptr_);
#endif
}
inline void ArenaStringPtr::ClearNonDefaultToEmpty() {
// Unconditionally mask away the tag.
tagged_ptr_.Get()->clear();
}
inline std::string* ArenaStringPtr::MutableNoArenaNoDefault(
const std::string* default_value) {
// VERY IMPORTANT for performance and code size: this will reduce to a member
// variable load, a pointer check (against |default_value|, in practice a
// static global) and a branch to the slowpath (which calls operator new and
// the ctor). DO NOT add any tagged-pointer operations here.
if (IsDefault(default_value)) {
std::string* new_string = new std::string();
tagged_ptr_.Set(new_string);
return new_string;
} else {
return UnsafeMutablePointer();
}
}
inline void ArenaStringPtr::DestroyNoArena(const std::string* default_value) {
if (!IsDefault(default_value)) {
delete UnsafeMutablePointer();
}
}
inline std::string* ArenaStringPtr::UnsafeMutablePointer() {
GOOGLE_DCHECK(!tagged_ptr_.IsTagged());
GOOGLE_DCHECK(tagged_ptr_.UnsafeGet() != nullptr);
return tagged_ptr_.UnsafeGet();
}
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_ARENASTRING_H__
| 15,918 | 41.337766 | 90 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/extension_set_inl.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_EXTENSION_SET_INL_H__
#define GOOGLE_PROTOBUF_EXTENSION_SET_INL_H__
#include <google/protobuf/parse_context.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/metadata_lite.h>
namespace google {
namespace protobuf {
namespace internal {
template <typename T>
const char* ExtensionSet::ParseFieldWithExtensionInfo(
int number, bool was_packed_on_wire, const ExtensionInfo& extension,
InternalMetadata* metadata, const char* ptr, internal::ParseContext* ctx) {
if (was_packed_on_wire) {
switch (extension.type) {
#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE) \
case WireFormatLite::TYPE_##UPPERCASE: \
return internal::Packed##CPP_CAMELCASE##Parser( \
MutableRawRepeatedField(number, extension.type, extension.is_packed, \
extension.descriptor), \
ptr, ctx);
HANDLE_TYPE(INT32, Int32);
HANDLE_TYPE(INT64, Int64);
HANDLE_TYPE(UINT32, UInt32);
HANDLE_TYPE(UINT64, UInt64);
HANDLE_TYPE(SINT32, SInt32);
HANDLE_TYPE(SINT64, SInt64);
HANDLE_TYPE(FIXED32, Fixed32);
HANDLE_TYPE(FIXED64, Fixed64);
HANDLE_TYPE(SFIXED32, SFixed32);
HANDLE_TYPE(SFIXED64, SFixed64);
HANDLE_TYPE(FLOAT, Float);
HANDLE_TYPE(DOUBLE, Double);
HANDLE_TYPE(BOOL, Bool);
#undef HANDLE_TYPE
case WireFormatLite::TYPE_ENUM:
return internal::PackedEnumParserArg<T>(
MutableRawRepeatedField(number, extension.type, extension.is_packed,
extension.descriptor),
ptr, ctx, extension.enum_validity_check.func,
extension.enum_validity_check.arg, metadata, number);
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 (extension.type) {
#define HANDLE_VARINT_TYPE(UPPERCASE, CPP_CAMELCASE) \
case WireFormatLite::TYPE_##UPPERCASE: { \
uint64 value; \
ptr = VarintParse(ptr, &value); \
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); \
if (extension.is_repeated) { \
Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \
extension.is_packed, value, extension.descriptor); \
} else { \
Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \
extension.descriptor); \
} \
} break
HANDLE_VARINT_TYPE(INT32, Int32);
HANDLE_VARINT_TYPE(INT64, Int64);
HANDLE_VARINT_TYPE(UINT32, UInt32);
HANDLE_VARINT_TYPE(UINT64, UInt64);
HANDLE_VARINT_TYPE(BOOL, Bool);
#undef HANDLE_VARINT_TYPE
#define HANDLE_SVARINT_TYPE(UPPERCASE, CPP_CAMELCASE, SIZE) \
case WireFormatLite::TYPE_##UPPERCASE: { \
uint64 val; \
ptr = VarintParse(ptr, &val); \
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); \
auto value = WireFormatLite::ZigZagDecode##SIZE(val); \
if (extension.is_repeated) { \
Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \
extension.is_packed, value, extension.descriptor); \
} else { \
Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \
extension.descriptor); \
} \
} break
HANDLE_SVARINT_TYPE(SINT32, Int32, 32);
HANDLE_SVARINT_TYPE(SINT64, Int64, 64);
#undef HANDLE_SVARINT_TYPE
#define HANDLE_FIXED_TYPE(UPPERCASE, CPP_CAMELCASE, CPPTYPE) \
case WireFormatLite::TYPE_##UPPERCASE: { \
auto value = UnalignedLoad<CPPTYPE>(ptr); \
ptr += sizeof(CPPTYPE); \
if (extension.is_repeated) { \
Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \
extension.is_packed, value, extension.descriptor); \
} else { \
Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \
extension.descriptor); \
} \
} break
HANDLE_FIXED_TYPE(FIXED32, UInt32, uint32);
HANDLE_FIXED_TYPE(FIXED64, UInt64, uint64);
HANDLE_FIXED_TYPE(SFIXED32, Int32, int32);
HANDLE_FIXED_TYPE(SFIXED64, Int64, int64);
HANDLE_FIXED_TYPE(FLOAT, Float, float);
HANDLE_FIXED_TYPE(DOUBLE, Double, double);
#undef HANDLE_FIXED_TYPE
case WireFormatLite::TYPE_ENUM: {
uint64 val;
ptr = VarintParse(ptr, &val);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
int value = val;
if (!extension.enum_validity_check.func(
extension.enum_validity_check.arg, value)) {
WriteVarint(number, val, metadata->mutable_unknown_fields<T>());
} else if (extension.is_repeated) {
AddEnum(number, WireFormatLite::TYPE_ENUM, extension.is_packed, value,
extension.descriptor);
} else {
SetEnum(number, WireFormatLite::TYPE_ENUM, value,
extension.descriptor);
}
break;
}
case WireFormatLite::TYPE_BYTES:
case WireFormatLite::TYPE_STRING: {
std::string* value =
extension.is_repeated
? AddString(number, WireFormatLite::TYPE_STRING,
extension.descriptor)
: MutableString(number, WireFormatLite::TYPE_STRING,
extension.descriptor);
int size = ReadSize(&ptr);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
return ctx->ReadString(ptr, size, value);
}
case WireFormatLite::TYPE_GROUP: {
MessageLite* value =
extension.is_repeated
? AddMessage(number, WireFormatLite::TYPE_GROUP,
*extension.message_info.prototype,
extension.descriptor)
: MutableMessage(number, WireFormatLite::TYPE_GROUP,
*extension.message_info.prototype,
extension.descriptor);
uint32 tag = (number << 3) + WireFormatLite::WIRETYPE_START_GROUP;
return ctx->ParseGroup(value, ptr, tag);
}
case WireFormatLite::TYPE_MESSAGE: {
MessageLite* value =
extension.is_repeated
? AddMessage(number, WireFormatLite::TYPE_MESSAGE,
*extension.message_info.prototype,
extension.descriptor)
: MutableMessage(number, WireFormatLite::TYPE_MESSAGE,
*extension.message_info.prototype,
extension.descriptor);
return ctx->ParseMessage(value, ptr);
}
}
}
return ptr;
}
template <typename Msg, typename T>
const char* ExtensionSet::ParseMessageSetItemTmpl(
const char* ptr, const Msg* containing_type,
internal::InternalMetadata* metadata, internal::ParseContext* ctx) {
std::string payload;
uint32 type_id = 0;
bool payload_read = false;
while (!ctx->Done(&ptr)) {
uint32 tag = static_cast<uint8>(*ptr++);
if (tag == WireFormatLite::kMessageSetTypeIdTag) {
uint64 tmp;
ptr = ParseBigVarint(ptr, &tmp);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
type_id = tmp;
if (payload_read) {
ExtensionInfo extension;
bool was_packed_on_wire;
if (!FindExtension(2, type_id, containing_type, ctx, &extension,
&was_packed_on_wire)) {
WriteLengthDelimited(type_id, payload,
metadata->mutable_unknown_fields<T>());
} else {
MessageLite* value =
extension.is_repeated
? AddMessage(type_id, WireFormatLite::TYPE_MESSAGE,
*extension.message_info.prototype,
extension.descriptor)
: MutableMessage(type_id, WireFormatLite::TYPE_MESSAGE,
*extension.message_info.prototype,
extension.descriptor);
const char* p;
// We can't use regular parse from string as we have to track
// proper recursion depth and descriptor pools.
ParseContext tmp_ctx(ctx->depth(), false, &p, payload);
tmp_ctx.data().pool = ctx->data().pool;
tmp_ctx.data().factory = ctx->data().factory;
GOOGLE_PROTOBUF_PARSER_ASSERT(value->_InternalParse(p, &tmp_ctx) &&
tmp_ctx.EndedAtLimit());
}
type_id = 0;
}
} else if (tag == WireFormatLite::kMessageSetMessageTag) {
if (type_id != 0) {
ptr = ParseFieldMaybeLazily(static_cast<uint64>(type_id) * 8 + 2, ptr,
containing_type, metadata, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
type_id = 0;
} else {
int32 size = ReadSize(&ptr);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
ptr = ctx->ReadString(ptr, size, &payload);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
payload_read = true;
}
} else {
ptr = ReadTag(ptr - 1, &tag);
if (tag == 0 || (tag & 7) == 4) {
ctx->SetLastTag(tag);
return ptr;
}
ptr = ParseField(tag, ptr, containing_type, metadata, ctx);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
}
}
return ptr;
}
} // namespace internal
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_EXTENSION_SET_INL_H__
| 12,437 | 43.902527 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/generated_enum_reflection.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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: [email protected] (Jason Hsueh)
//
// This header is logically internal, but is made public because it is used
// from protocol-compiler-generated code, which may reside in other components.
// It provides reflection support for generated enums, and is included in
// generated .pb.h files and should have minimal dependencies. The methods are
// implemented in generated_message_reflection.cc.
#ifndef GOOGLE_PROTOBUF_GENERATED_ENUM_REFLECTION_H__
#define GOOGLE_PROTOBUF_GENERATED_ENUM_REFLECTION_H__
#include <string>
#include <google/protobuf/generated_enum_util.h>
#include <google/protobuf/port.h>
#include <google/protobuf/stubs/strutil.h>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class EnumDescriptor;
} // namespace protobuf
} // namespace google
namespace google {
namespace protobuf {
// Returns the EnumDescriptor for enum type E, which must be a
// proto-declared enum type. Code generated by the protocol compiler
// will include specializations of this template for each enum type declared.
template <typename E>
const EnumDescriptor* GetEnumDescriptor();
namespace internal {
// Helper for EnumType_Parse functions: try to parse the string 'name' as
// an enum name of the given type, returning true and filling in value on
// success, or returning false and leaving value unchanged on failure.
PROTOBUF_EXPORT bool ParseNamedEnum(const EnumDescriptor* descriptor,
ConstStringParam name, int* value);
template <typename EnumType>
bool ParseNamedEnum(const EnumDescriptor* descriptor, ConstStringParam name,
EnumType* value) {
int tmp;
if (!ParseNamedEnum(descriptor, name, &tmp)) return false;
*value = static_cast<EnumType>(tmp);
return true;
}
// Just a wrapper around printing the name of a value. The main point of this
// function is not to be inlined, so that you can do this without including
// descriptor.h.
PROTOBUF_EXPORT const std::string& NameOfEnum(const EnumDescriptor* descriptor,
int value);
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_GENERATED_ENUM_REFLECTION_H__
| 3,993 | 39.343434 | 79 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/generated_enum_util.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__
#define GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__
#include <type_traits>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/port_def.inc>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
// This type trait can be used to cause templates to only match proto2 enum
// types.
template <typename T>
struct is_proto_enum : ::std::false_type {};
namespace internal {
// The table entry format for storing enum name-to-value mapping used with lite
// protos. This struct and the following related functions should only be used
// by protobuf generated code.
struct EnumEntry {
StringPiece name;
int value;
};
// Looks up a numeric enum value given the string name.
PROTOBUF_EXPORT bool LookUpEnumValue(const EnumEntry* enums, size_t size,
StringPiece name, int* value);
// Looks up an enum name given the numeric value.
PROTOBUF_EXPORT int LookUpEnumName(const EnumEntry* enums,
const int* sorted_indices, size_t size,
int value);
// Initializes the list of enum names in std::string form.
PROTOBUF_EXPORT bool InitializeEnumStrings(
const EnumEntry* enums, const int* sorted_indices, size_t size,
internal::ExplicitlyConstructed<std::string>* enum_strings);
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_GENERATED_ENUM_UTIL_H__
| 3,266 | 37.892857 | 79 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/generated_message_table_driven.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_H__
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_H__
#include <google/protobuf/map.h>
#include <google/protobuf/map_entry_lite.h>
#include <google/protobuf/map_field_lite.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/wire_format_lite.h>
// We require C++11 and Clang to use constexpr for variables, as GCC 4.8
// requires constexpr to be consistent between declarations of variables
// unnecessarily (see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58541).
// VS 2017 Update 3 also supports this usage of constexpr.
#if defined(__clang__) || (defined(_MSC_VER) && _MSC_VER >= 1911)
#define PROTOBUF_CONSTEXPR_VAR constexpr
#else // !__clang__
#define PROTOBUF_CONSTEXPR_VAR
#endif // !_clang
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
namespace internal {
// Processing-type masks.
static constexpr const unsigned char kOneofMask = 0x40;
static constexpr const unsigned char kRepeatedMask = 0x20;
// Mask for the raw type: either a WireFormatLite::FieldType or one of the
// ProcessingTypes below, without the oneof or repeated flag.
static constexpr const unsigned char kTypeMask = 0x1f;
// Wire type masks.
static constexpr const unsigned char kNotPackedMask = 0x10;
static constexpr const unsigned char kInvalidMask = 0x20;
enum ProcessingTypes {
TYPE_STRING_CORD = 19,
TYPE_STRING_STRING_PIECE = 20,
TYPE_BYTES_CORD = 21,
TYPE_BYTES_STRING_PIECE = 22,
TYPE_MAP = 23,
};
static_assert(TYPE_MAP < kRepeatedMask, "Invalid enum");
struct PROTOBUF_EXPORT FieldMetadata {
uint32 offset; // offset of this field in the struct
uint32 tag; // field * 8 + wire_type
// byte offset * 8 + bit_offset;
// if the high bit is set then this is the byte offset of the oneof_case
// for this field.
uint32 has_offset;
uint32 type; // the type of this field.
const void* ptr; // auxiliary data
// From the serializer point of view each fundamental type can occur in
// 4 different ways. For simplicity we treat all combinations as a cartesion
// product although not all combinations are allowed.
enum FieldTypeClass {
kPresence,
kNoPresence,
kRepeated,
kPacked,
kOneOf,
kNumTypeClasses // must be last enum
};
// C++ protobuf has 20 fundamental types, were we added Cord and StringPiece
// and also distinguish the same types if they have different wire format.
enum {
kCordType = 19,
kStringPieceType = 20,
kNumTypes = 20,
kSpecial = kNumTypes * kNumTypeClasses,
};
static int CalculateType(int fundamental_type, FieldTypeClass type_class);
};
// TODO(ckennelly): Add a static assertion to ensure that these masks do not
// conflict with wiretypes.
// ParseTableField is kept small to help simplify instructions for computing
// offsets, as we will always need this information to parse a field.
// Additional data, needed for some types, is stored in
// AuxiliaryParseTableField.
struct ParseTableField {
uint32 offset;
// The presence_index ordinarily represents a has_bit index, but for fields
// inside a oneof it represents the index in _oneof_case_.
uint32 presence_index;
unsigned char normal_wiretype;
unsigned char packed_wiretype;
// processing_type is given by:
// (FieldDescriptor->type() << 1) | FieldDescriptor->is_packed()
unsigned char processing_type;
unsigned char tag_size;
};
struct ParseTable;
union AuxiliaryParseTableField {
typedef bool (*EnumValidator)(int);
// Enums
struct enum_aux {
EnumValidator validator;
};
enum_aux enums;
// Group, messages
struct message_aux {
// ExplicitlyInitialized<T> -> T requires a reinterpret_cast, which prevents
// the tables from being constructed as a constexpr. We use void to avoid
// the cast.
const void* default_message_void;
const MessageLite* default_message() const {
return static_cast<const MessageLite*>(default_message_void);
}
};
message_aux messages;
// Strings
struct string_aux {
const void* default_ptr;
const char* field_name;
};
string_aux strings;
struct map_aux {
bool (*parse_map)(io::CodedInputStream*, void*);
};
map_aux maps;
AuxiliaryParseTableField() = default;
constexpr AuxiliaryParseTableField(AuxiliaryParseTableField::enum_aux e)
: enums(e) {}
constexpr AuxiliaryParseTableField(AuxiliaryParseTableField::message_aux m)
: messages(m) {}
constexpr AuxiliaryParseTableField(AuxiliaryParseTableField::string_aux s)
: strings(s) {}
constexpr AuxiliaryParseTableField(AuxiliaryParseTableField::map_aux m)
: maps(m) {}
};
struct ParseTable {
const ParseTableField* fields;
const AuxiliaryParseTableField* aux;
int max_field_number;
// TODO(ckennelly): Do something with this padding.
// TODO(ckennelly): Vet these for sign extension.
int64 has_bits_offset;
int64 oneof_case_offset;
int64 extension_offset;
int64 arena_offset;
// ExplicitlyInitialized<T> -> T requires a reinterpret_cast, which prevents
// the tables from being constructed as a constexpr. We use void to avoid
// the cast.
const void* default_instance_void;
const MessageLite* default_instance() const {
return static_cast<const MessageLite*>(default_instance_void);
}
bool unknown_field_set;
};
static_assert(sizeof(ParseTableField) <= 16, "ParseTableField is too large");
// The tables must be composed of POD components to ensure link-time
// initialization.
static_assert(std::is_pod<ParseTableField>::value, "");
static_assert(std::is_pod<AuxiliaryParseTableField>::value, "");
static_assert(std::is_pod<AuxiliaryParseTableField::enum_aux>::value, "");
static_assert(std::is_pod<AuxiliaryParseTableField::message_aux>::value, "");
static_assert(std::is_pod<AuxiliaryParseTableField::string_aux>::value, "");
static_assert(std::is_pod<ParseTable>::value, "");
// TODO(ckennelly): Consolidate these implementations into a single one, using
// dynamic dispatch to the appropriate unknown field handler.
bool MergePartialFromCodedStream(MessageLite* msg, const ParseTable& table,
io::CodedInputStream* input);
bool MergePartialFromCodedStreamLite(MessageLite* msg, const ParseTable& table,
io::CodedInputStream* input);
template <typename Entry>
bool ParseMap(io::CodedInputStream* input, void* map_field) {
typedef typename MapEntryToMapField<Entry>::MapFieldType MapFieldType;
typedef Map<typename Entry::EntryKeyType, typename Entry::EntryValueType>
MapType;
typedef typename Entry::template Parser<MapFieldType, MapType> ParserType;
ParserType parser(static_cast<MapFieldType*>(map_field));
return WireFormatLite::ReadMessageNoVirtual(input, &parser);
}
struct SerializationTable {
int num_fields;
const FieldMetadata* field_table;
};
PROTOBUF_EXPORT void SerializeInternal(const uint8* base,
const FieldMetadata* table,
int32 num_fields,
io::CodedOutputStream* output);
inline void TableSerialize(const MessageLite& msg,
const SerializationTable* table,
io::CodedOutputStream* output) {
const FieldMetadata* field_table = table->field_table;
int num_fields = table->num_fields - 1;
const uint8* base = reinterpret_cast<const uint8*>(&msg);
// TODO(gerbens) This skips the first test if we could use the fast
// array serialization path, we should make this
// int cached_size =
// *reinterpret_cast<const int32*>(base + field_table->offset);
// SerializeWithCachedSize(msg, field_table + 1, num_fields, cached_size, ...)
// But we keep conformance with the old way for now.
SerializeInternal(base, field_table + 1, num_fields, output);
}
uint8* SerializeInternalToArray(const uint8* base, const FieldMetadata* table,
int32 num_fields, bool is_deterministic,
uint8* buffer);
inline uint8* TableSerializeToArray(const MessageLite& msg,
const SerializationTable* table,
bool is_deterministic, uint8* buffer) {
const uint8* base = reinterpret_cast<const uint8*>(&msg);
const FieldMetadata* field_table = table->field_table + 1;
int num_fields = table->num_fields - 1;
return SerializeInternalToArray(base, field_table, num_fields,
is_deterministic, buffer);
}
template <typename T>
struct CompareHelper {
bool operator()(const T& a, const T& b) const { return a < b; }
};
template <>
struct CompareHelper<ArenaStringPtr> {
bool operator()(const ArenaStringPtr& a, const ArenaStringPtr& b) const {
return a.Get() < b.Get();
}
};
struct CompareMapKey {
template <typename T>
bool operator()(const MapEntryHelper<T>& a,
const MapEntryHelper<T>& b) const {
return Compare(a.key_, b.key_);
}
template <typename T>
bool Compare(const T& a, const T& b) const {
return CompareHelper<T>()(a, b);
}
};
template <typename MapFieldType, const SerializationTable* table>
void MapFieldSerializer(const uint8* base, uint32 offset, uint32 tag,
uint32 has_offset, io::CodedOutputStream* output) {
typedef MapEntryHelper<typename MapFieldType::EntryTypeTrait> Entry;
typedef typename MapFieldType::MapType::const_iterator Iter;
const MapFieldType& map_field =
*reinterpret_cast<const MapFieldType*>(base + offset);
const SerializationTable* t =
table +
has_offset; // has_offset is overloaded for maps to mean table offset
if (!output->IsSerializationDeterministic()) {
for (Iter it = map_field.GetMap().begin(); it != map_field.GetMap().end();
++it) {
Entry map_entry(*it);
output->WriteVarint32(tag);
output->WriteVarint32(map_entry._cached_size_);
SerializeInternal(reinterpret_cast<const uint8*>(&map_entry),
t->field_table, t->num_fields, output);
}
} else {
std::vector<Entry> v;
for (Iter it = map_field.GetMap().begin(); it != map_field.GetMap().end();
++it) {
v.push_back(Entry(*it));
}
std::sort(v.begin(), v.end(), CompareMapKey());
for (int i = 0; i < v.size(); i++) {
output->WriteVarint32(tag);
output->WriteVarint32(v[i]._cached_size_);
SerializeInternal(reinterpret_cast<const uint8*>(&v[i]), t->field_table,
t->num_fields, output);
}
}
}
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_TABLE_DRIVEN_H__
| 12,532 | 36.189911 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/generated_message_util.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains miscellaneous helper code used by generated code --
// including lite types -- but which should not be used directly by users.
#ifndef GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__
#include <assert.h>
#include <atomic>
#include <climits>
#include <string>
#include <vector>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/any.h>
#include <google/protobuf/has_bits.h>
#include <google/protobuf/implicit_weak_message.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/stubs/once.h> // Add direct dep on port for pb.cc
#include <google/protobuf/port.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/port_def.inc>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
class Arena;
class Message;
namespace io {
class CodedInputStream;
}
namespace internal {
template <typename To, typename From>
inline To DownCast(From* f) {
return PROTOBUF_NAMESPACE_ID::internal::down_cast<To>(f);
}
template <typename To, typename From>
inline To DownCast(From& f) {
return PROTOBUF_NAMESPACE_ID::internal::down_cast<To>(f);
}
// This fastpath inlines a single branch instead of having to make the
// InitProtobufDefaults function call.
// It also generates less inlined code than a function-scope static initializer.
PROTOBUF_EXPORT extern std::atomic<bool> init_protobuf_defaults_state;
PROTOBUF_EXPORT void InitProtobufDefaultsSlow();
PROTOBUF_EXPORT inline void InitProtobufDefaults() {
if (PROTOBUF_PREDICT_FALSE(
!init_protobuf_defaults_state.load(std::memory_order_acquire))) {
InitProtobufDefaultsSlow();
}
}
// This used by proto1
PROTOBUF_EXPORT inline const std::string& GetEmptyString() {
InitProtobufDefaults();
return GetEmptyStringAlreadyInited();
}
// True if IsInitialized() is true for all elements of t. Type is expected
// to be a RepeatedPtrField<some message type>. It's useful to have this
// helper here to keep the protobuf compiler from ever having to emit loops in
// IsInitialized() methods. We want the C++ compiler to inline this or not
// as it sees fit.
template <typename Msg>
bool AllAreInitialized(const RepeatedPtrField<Msg>& t) {
for (int i = t.size(); --i >= 0;) {
if (!t.Get(i).IsInitialized()) return false;
}
return true;
}
// "Weak" variant of AllAreInitialized, used to implement implicit weak fields.
// This version operates on MessageLite to avoid introducing a dependency on the
// concrete message type.
template <class T>
bool AllAreInitializedWeak(const RepeatedPtrField<T>& t) {
for (int i = t.size(); --i >= 0;) {
if (!reinterpret_cast<const RepeatedPtrFieldBase&>(t)
.Get<ImplicitWeakTypeHandler<T> >(i)
.IsInitialized()) {
return false;
}
}
return true;
}
inline bool IsPresent(const void* base, uint32 hasbit) {
const uint32* has_bits_array = static_cast<const uint32*>(base);
return (has_bits_array[hasbit / 32] & (1u << (hasbit & 31))) != 0;
}
inline bool IsOneofPresent(const void* base, uint32 offset, uint32 tag) {
const uint32* oneof =
reinterpret_cast<const uint32*>(static_cast<const uint8*>(base) + offset);
return *oneof == tag >> 3;
}
typedef void (*SpecialSerializer)(const uint8* base, uint32 offset, uint32 tag,
uint32 has_offset,
io::CodedOutputStream* output);
PROTOBUF_EXPORT void ExtensionSerializer(const uint8* base, uint32 offset,
uint32 tag, uint32 has_offset,
io::CodedOutputStream* output);
PROTOBUF_EXPORT void UnknownFieldSerializerLite(const uint8* base,
uint32 offset, uint32 tag,
uint32 has_offset,
io::CodedOutputStream* output);
PROTOBUF_EXPORT MessageLite* DuplicateIfNonNullInternal(MessageLite* message);
PROTOBUF_EXPORT MessageLite* GetOwnedMessageInternal(Arena* message_arena,
MessageLite* submessage,
Arena* submessage_arena);
PROTOBUF_EXPORT void GenericSwap(MessageLite* m1, MessageLite* m2);
// We specialize GenericSwap for non-lite messages to benefit from reflection.
PROTOBUF_EXPORT void GenericSwap(Message* m1, Message* m2);
template <typename T>
T* DuplicateIfNonNull(T* message) {
// The casts must be reinterpret_cast<> because T might be a forward-declared
// type that the compiler doesn't know is related to MessageLite.
return reinterpret_cast<T*>(
DuplicateIfNonNullInternal(reinterpret_cast<MessageLite*>(message)));
}
template <typename T>
T* GetOwnedMessage(Arena* message_arena, T* submessage,
Arena* submessage_arena) {
// The casts must be reinterpret_cast<> because T might be a forward-declared
// type that the compiler doesn't know is related to MessageLite.
return reinterpret_cast<T*>(GetOwnedMessageInternal(
message_arena, reinterpret_cast<MessageLite*>(submessage),
submessage_arena));
}
// Hide atomic from the public header and allow easy change to regular int
// on platforms where the atomic might have a perf impact.
class PROTOBUF_EXPORT CachedSize {
public:
int Get() const { return size_.load(std::memory_order_relaxed); }
void Set(int size) { size_.store(size, std::memory_order_relaxed); }
private:
std::atomic<int> size_{0};
};
// SCCInfo represents information of a strongly connected component of
// mutual dependent messages.
struct PROTOBUF_EXPORT SCCInfoBase {
// We use 0 for the Initialized state, because test eax,eax, jnz is smaller
// and is subject to macro fusion.
enum {
kInitialized = 0, // final state
kRunning = 1,
kUninitialized = -1, // initial state
};
#if defined(_MSC_VER) && !defined(__clang__)
// MSVC doesn't make std::atomic constant initialized. This union trick
// makes it so.
union {
int visit_status_to_make_linker_init;
std::atomic<int> visit_status;
};
#else
std::atomic<int> visit_status;
#endif
int num_deps;
int num_implicit_weak_deps;
void (*init_func)();
// This is followed by an array of num_deps
// const SCCInfoBase* deps[];
};
// Zero-length arrays are a language extension available in GCC and Clang but
// not MSVC.
#ifdef __GNUC__
#define PROTOBUF_ARRAY_SIZE(n) (n)
#else
#define PROTOBUF_ARRAY_SIZE(n) ((n) ? (n) : 1)
#endif
template <int N>
struct SCCInfo {
SCCInfoBase base;
// Semantically this is const SCCInfo<T>* which is is a templated type.
// The obvious inheriting from SCCInfoBase mucks with struct initialization.
// Attempts showed the compiler was generating dynamic initialization code.
// This deps array consists of base.num_deps pointers to SCCInfoBase followed
// by base.num_implicit_weak_deps pointers to SCCInfoBase*. We need the extra
// pointer indirection for implicit weak fields. We cannot use a union type
// here, since that would prevent the array from being linker-initialized.
void* deps[PROTOBUF_ARRAY_SIZE(N)];
};
#undef PROTOBUF_ARRAY_SIZE
PROTOBUF_EXPORT void InitSCCImpl(SCCInfoBase* scc);
inline void InitSCC(SCCInfoBase* scc) {
auto status = scc->visit_status.load(std::memory_order_acquire);
if (PROTOBUF_PREDICT_FALSE(status != SCCInfoBase::kInitialized))
InitSCCImpl(scc);
}
PROTOBUF_EXPORT void DestroyMessage(const void* message);
PROTOBUF_EXPORT void DestroyString(const void* s);
// Destroy (not delete) the message
inline void OnShutdownDestroyMessage(const void* ptr) {
OnShutdownRun(DestroyMessage, ptr);
}
// Destroy the string (call std::string destructor)
inline void OnShutdownDestroyString(const std::string* ptr) {
OnShutdownRun(DestroyString, ptr);
}
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__
| 10,023 | 35.98893 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/has_bits.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_HAS_BITS_H__
#define GOOGLE_PROTOBUF_HAS_BITS_H__
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/port.h>
#include <google/protobuf/port_def.inc>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
namespace internal {
template <size_t doublewords>
class HasBits {
public:
constexpr HasBits() PROTOBUF_ALWAYS_INLINE : has_bits_{} {}
void Clear() PROTOBUF_ALWAYS_INLINE {
memset(has_bits_, 0, sizeof(has_bits_));
}
uint32& operator[](int index) PROTOBUF_ALWAYS_INLINE {
return has_bits_[index];
}
const uint32& operator[](int index) const PROTOBUF_ALWAYS_INLINE {
return has_bits_[index];
}
bool operator==(const HasBits<doublewords>& rhs) const {
return memcmp(has_bits_, rhs.has_bits_, sizeof(has_bits_)) == 0;
}
bool operator!=(const HasBits<doublewords>& rhs) const {
return !(*this == rhs);
}
void Or(const HasBits<doublewords>& rhs) {
for (size_t i = 0; i < doublewords; i++) has_bits_[i] |= rhs[i];
}
bool empty() const;
private:
uint32 has_bits_[doublewords];
};
template <>
inline bool HasBits<1>::empty() const {
return !has_bits_[0];
}
template <>
inline bool HasBits<2>::empty() const {
return !(has_bits_[0] | has_bits_[1]);
}
template <>
inline bool HasBits<3>::empty() const {
return !(has_bits_[0] | has_bits_[1] | has_bits_[2]);
}
template <>
inline bool HasBits<4>::empty() const {
return !(has_bits_[0] | has_bits_[1] | has_bits_[2] | has_bits_[3]);
}
template <size_t doublewords>
inline bool HasBits<doublewords>::empty() const {
for (size_t i = 0; i < doublewords; ++i) {
if (has_bits_[i]) return false;
}
return true;
}
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_HAS_BITS_H__
| 3,542 | 29.282051 | 73 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/implicit_weak_message.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__
#define GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__
#include <string>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
#include <google/protobuf/port_def.inc>
// This file is logically internal-only and should only be used by protobuf
// generated code.
namespace google {
namespace protobuf {
namespace internal {
// An implementation of MessageLite that treats all data as unknown. This type
// acts as a placeholder for an implicit weak field in the case where the true
// message type does not get linked into the binary.
class PROTOBUF_EXPORT ImplicitWeakMessage : public MessageLite {
public:
ImplicitWeakMessage() {}
explicit ImplicitWeakMessage(Arena* arena) : MessageLite(arena) {}
static const ImplicitWeakMessage* default_instance();
std::string GetTypeName() const override { return ""; }
MessageLite* New() const override { return new ImplicitWeakMessage; }
MessageLite* New(Arena* arena) const override {
return Arena::CreateMessage<ImplicitWeakMessage>(arena);
}
void Clear() override { data_.clear(); }
bool IsInitialized() const override { return true; }
void CheckTypeAndMergeFrom(const MessageLite& other) override {
data_.append(static_cast<const ImplicitWeakMessage&>(other).data_);
}
const char* _InternalParse(const char* ptr, ParseContext* ctx) final;
size_t ByteSizeLong() const override { return data_.size(); }
uint8* _InternalSerialize(uint8* target,
io::EpsCopyOutputStream* stream) const final {
return stream->WriteRaw(data_.data(), static_cast<int>(data_.size()),
target);
}
int GetCachedSize() const override { return static_cast<int>(data_.size()); }
typedef void InternalArenaConstructable_;
private:
std::string data_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImplicitWeakMessage);
};
// A type handler for use with implicit weak repeated message fields.
template <typename ImplicitWeakType>
class ImplicitWeakTypeHandler {
public:
typedef MessageLite Type;
static constexpr bool Moveable = false;
static inline MessageLite* NewFromPrototype(const MessageLite* prototype,
Arena* arena = NULL) {
return prototype->New(arena);
}
static inline void Delete(MessageLite* value, Arena* arena) {
if (arena == NULL) {
delete value;
}
}
static inline Arena* GetArena(MessageLite* value) {
return value->GetArena();
}
static inline void* GetMaybeArenaPointer(MessageLite* value) {
return value->GetArena();
}
static inline void Clear(MessageLite* value) { value->Clear(); }
static void Merge(const MessageLite& from, MessageLite* to) {
to->CheckTypeAndMergeFrom(from);
}
};
} // namespace internal
template <typename T>
struct WeakRepeatedPtrField {
using TypeHandler = internal::ImplicitWeakTypeHandler<T>;
constexpr WeakRepeatedPtrField() : weak() {}
explicit WeakRepeatedPtrField(Arena* arena) : weak(arena) {}
~WeakRepeatedPtrField() { weak.template Destroy<TypeHandler>(); }
typedef internal::RepeatedPtrIterator<MessageLite> iterator;
typedef internal::RepeatedPtrIterator<const MessageLite> const_iterator;
typedef internal::RepeatedPtrOverPtrsIterator<MessageLite*, void*>
pointer_iterator;
typedef internal::RepeatedPtrOverPtrsIterator<const MessageLite* const,
const void* const>
const_pointer_iterator;
iterator begin() { return iterator(base().raw_data()); }
const_iterator begin() const { return iterator(base().raw_data()); }
const_iterator cbegin() const { return begin(); }
iterator end() { return begin() + base().size(); }
const_iterator end() const { return begin() + base().size(); }
const_iterator cend() const { return end(); }
pointer_iterator pointer_begin() {
return pointer_iterator(base().raw_mutable_data());
}
const_pointer_iterator pointer_begin() const {
return const_pointer_iterator(base().raw_mutable_data());
}
pointer_iterator pointer_end() {
return pointer_iterator(base().raw_mutable_data() + base().size());
}
const_pointer_iterator pointer_end() const {
return const_pointer_iterator(base().raw_mutable_data() + base().size());
}
MessageLite* AddWeak(const MessageLite* prototype) {
return base().AddWeak(prototype);
}
T* Add() { return weak.Add(); }
void Clear() { base().template Clear<TypeHandler>(); }
void MergeFrom(const WeakRepeatedPtrField& other) {
base().template MergeFrom<TypeHandler>(other.base());
}
void InternalSwap(WeakRepeatedPtrField* other) {
base().InternalSwap(&other->base());
}
const internal::RepeatedPtrFieldBase& base() const { return weak; }
internal::RepeatedPtrFieldBase& base() { return weak; }
// Union disables running the destructor. Which would create a strong link.
// Instead we explicitly destroy the underlying base through the virtual
// destructor.
union {
RepeatedPtrField<T> weak;
};
};
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_IMPLICIT_WEAK_MESSAGE_H__
| 7,024 | 35.780105 | 79 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/map_entry_lite.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_MAP_ENTRY_LITE_H__
#define GOOGLE_PROTOBUF_MAP_ENTRY_LITE_H__
#include <assert.h>
#include <string>
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/parse_context.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/map.h>
#include <google/protobuf/map_type_handler.h>
#include <google/protobuf/port.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/port_def.inc>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
namespace internal {
template <typename Derived, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
WireFormatLite::FieldType kValueFieldType>
class MapEntry;
template <typename Derived, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
WireFormatLite::FieldType kValueFieldType>
class MapFieldLite;
} // namespace internal
} // namespace protobuf
} // namespace google
namespace google {
namespace protobuf {
namespace internal {
// MoveHelper::Move is used to set *dest. It copies *src, or moves it (in
// the C++11 sense), or swaps it. *src is left in a sane state for
// subsequent destruction, but shouldn't be used for anything.
template <bool is_enum, bool is_message, bool is_stringlike, typename T>
struct MoveHelper { // primitives
static void Move(T* src, T* dest) { *dest = *src; }
};
template <bool is_message, bool is_stringlike, typename T>
struct MoveHelper<true, is_message, is_stringlike, T> { // enums
static void Move(T* src, T* dest) { *dest = *src; }
// T is an enum here, so allow conversions to and from int.
static void Move(T* src, int* dest) { *dest = static_cast<int>(*src); }
static void Move(int* src, T* dest) { *dest = static_cast<T>(*src); }
};
template <bool is_stringlike, typename T>
struct MoveHelper<false, true, is_stringlike, T> { // messages
static void Move(T* src, T* dest) { dest->Swap(src); }
};
template <typename T>
struct MoveHelper<false, false, true, T> { // strings and similar
static void Move(T* src, T* dest) {
*dest = std::move(*src);
}
};
// Functions for operating on a map entry. Does not contain any representation
// (this class is not intended to be instantiated).
template <typename Key, typename Value, WireFormatLite::FieldType kKeyFieldType,
WireFormatLite::FieldType kValueFieldType>
struct MapEntryFuncs {
typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler;
typedef MapTypeHandler<kValueFieldType, Value> ValueTypeHandler;
static const int kKeyFieldNumber = 1;
static const int kValueFieldNumber = 2;
static uint8* InternalSerialize(int field_number, const Key& key,
const Value& value, uint8* ptr,
io::EpsCopyOutputStream* stream) {
ptr = stream->EnsureSpace(ptr);
ptr = WireFormatLite::WriteTagToArray(
field_number, WireFormatLite::WIRETYPE_LENGTH_DELIMITED, ptr);
ptr = io::CodedOutputStream::WriteVarint32ToArray(GetCachedSize(key, value),
ptr);
ptr = KeyTypeHandler::Write(kKeyFieldNumber, key, ptr, stream);
return ValueTypeHandler::Write(kValueFieldNumber, value, ptr, stream);
}
static size_t ByteSizeLong(const Key& key, const Value& value) {
// Tags for key and value will both be one byte (field numbers 1 and 2).
size_t inner_length =
2 + KeyTypeHandler::ByteSize(key) + ValueTypeHandler::ByteSize(value);
return inner_length + io::CodedOutputStream::VarintSize32(
static_cast<uint32>(inner_length));
}
static int GetCachedSize(const Key& key, const Value& value) {
// Tags for key and value will both be one byte (field numbers 1 and 2).
return 2 + KeyTypeHandler::GetCachedSize(key) +
ValueTypeHandler::GetCachedSize(value);
}
};
// MapEntryImpl is used to implement parsing and serialization of map entries.
// It uses Curious Recursive Template Pattern (CRTP) to provide the type of
// the eventual code to the template code.
template <typename Derived, typename Base, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
WireFormatLite::FieldType kValueFieldType>
class MapEntryImpl : public Base {
public:
typedef MapEntryFuncs<Key, Value, kKeyFieldType, kValueFieldType> Funcs;
protected:
// Provide utilities to parse/serialize key/value. Provide utilities to
// manipulate internal stored type.
typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler;
typedef MapTypeHandler<kValueFieldType, Value> ValueTypeHandler;
// Define internal memory layout. Strings and messages are stored as
// pointers, while other types are stored as values.
typedef typename KeyTypeHandler::TypeOnMemory KeyOnMemory;
typedef typename ValueTypeHandler::TypeOnMemory ValueOnMemory;
// Enum type cannot be used for MapTypeHandler::Read. Define a type
// which will replace Enum with int.
typedef typename KeyTypeHandler::MapEntryAccessorType KeyMapEntryAccessorType;
typedef
typename ValueTypeHandler::MapEntryAccessorType ValueMapEntryAccessorType;
// Constants for field number.
static const int kKeyFieldNumber = 1;
static const int kValueFieldNumber = 2;
// Constants for field tag.
static const uint8 kKeyTag =
GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(kKeyFieldNumber, KeyTypeHandler::kWireType);
static const uint8 kValueTag = GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(
kValueFieldNumber, ValueTypeHandler::kWireType);
static const size_t kTagSize = 1;
public:
// Work-around for a compiler bug (see repeated_field.h).
typedef void MapEntryHasMergeTypeTrait;
typedef Derived EntryType;
typedef Key EntryKeyType;
typedef Value EntryValueType;
static const WireFormatLite::FieldType kEntryKeyFieldType = kKeyFieldType;
static const WireFormatLite::FieldType kEntryValueFieldType = kValueFieldType;
constexpr MapEntryImpl()
: key_(KeyTypeHandler::Constinit()),
value_(ValueTypeHandler::Constinit()),
_has_bits_{} {}
explicit MapEntryImpl(Arena* arena)
: Base(arena),
key_(KeyTypeHandler::Constinit()),
value_(ValueTypeHandler::Constinit()),
_has_bits_{} {}
~MapEntryImpl() {
if (Base::GetArena() != NULL) return;
KeyTypeHandler::DeleteNoArena(key_);
ValueTypeHandler::DeleteNoArena(value_);
}
// accessors ======================================================
virtual inline const KeyMapEntryAccessorType& key() const {
return KeyTypeHandler::GetExternalReference(key_);
}
virtual inline const ValueMapEntryAccessorType& value() const {
return ValueTypeHandler::DefaultIfNotInitialized(value_);
}
inline KeyMapEntryAccessorType* mutable_key() {
set_has_key();
return KeyTypeHandler::EnsureMutable(&key_, Base::GetArena());
}
inline ValueMapEntryAccessorType* mutable_value() {
set_has_value();
return ValueTypeHandler::EnsureMutable(&value_, Base::GetArena());
}
// implements MessageLite =========================================
// MapEntryImpl is for implementation only and this function isn't called
// anywhere. Just provide a fake implementation here for MessageLite.
std::string GetTypeName() const override { return ""; }
void CheckTypeAndMergeFrom(const MessageLite& other) override {
MergeFromInternal(*::google::protobuf::internal::DownCast<const Derived*>(&other));
}
const char* _InternalParse(const char* ptr, ParseContext* ctx) final {
while (!ctx->Done(&ptr)) {
uint32 tag;
ptr = ReadTag(ptr, &tag);
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
if (tag == kKeyTag) {
set_has_key();
KeyMapEntryAccessorType* key = mutable_key();
ptr = KeyTypeHandler::Read(ptr, ctx, key);
if (!Derived::ValidateKey(key)) return nullptr;
} else if (tag == kValueTag) {
set_has_value();
ValueMapEntryAccessorType* value = mutable_value();
ptr = ValueTypeHandler::Read(ptr, ctx, value);
if (!Derived::ValidateValue(value)) return nullptr;
} else {
if (tag == 0 || WireFormatLite::GetTagWireType(tag) ==
WireFormatLite::WIRETYPE_END_GROUP) {
ctx->SetLastTag(tag);
return ptr;
}
ptr = UnknownFieldParse(tag, static_cast<std::string*>(nullptr), ptr,
ctx);
}
GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
}
return ptr;
}
size_t ByteSizeLong() const override {
size_t size = 0;
size += kTagSize + static_cast<size_t>(KeyTypeHandler::ByteSize(key()));
size += kTagSize + static_cast<size_t>(ValueTypeHandler::ByteSize(value()));
return size;
}
::google::protobuf::uint8* _InternalSerialize(::google::protobuf::uint8* ptr,
io::EpsCopyOutputStream* stream) const override {
ptr = KeyTypeHandler::Write(kKeyFieldNumber, key(), ptr, stream);
return ValueTypeHandler::Write(kValueFieldNumber, value(), ptr, stream);
}
// Don't override SerializeWithCachedSizesToArray. Use MessageLite's.
int GetCachedSize() const override {
int size = 0;
size += has_key() ? static_cast<int>(kTagSize) +
KeyTypeHandler::GetCachedSize(key())
: 0;
size += has_value() ? static_cast<int>(kTagSize) +
ValueTypeHandler::GetCachedSize(value())
: 0;
return size;
}
bool IsInitialized() const override {
return ValueTypeHandler::IsInitialized(value_);
}
Base* New() const override {
Derived* entry = new Derived;
return entry;
}
Base* New(Arena* arena) const override {
Derived* entry = Arena::CreateMessage<Derived>(arena);
return entry;
}
protected:
// We can't declare this function directly here as it would hide the other
// overload (const Message&).
void MergeFromInternal(const MapEntryImpl& from) {
if (from._has_bits_[0]) {
if (from.has_key()) {
KeyTypeHandler::EnsureMutable(&key_, Base::GetArena());
KeyTypeHandler::Merge(from.key(), &key_, Base::GetArena());
set_has_key();
}
if (from.has_value()) {
ValueTypeHandler::EnsureMutable(&value_, Base::GetArena());
ValueTypeHandler::Merge(from.value(), &value_, Base::GetArena());
set_has_value();
}
}
}
public:
void Clear() override {
KeyTypeHandler::Clear(&key_, Base::GetArena());
ValueTypeHandler::Clear(&value_, Base::GetArena());
clear_has_key();
clear_has_value();
}
// Parsing using MergePartialFromCodedStream, above, is not as
// efficient as it could be. This helper class provides a speedier way.
template <typename MapField, typename Map>
class Parser {
public:
explicit Parser(MapField* mf) : mf_(mf), map_(mf->MutableMap()) {}
~Parser() {
if (entry_ != nullptr && entry_->GetArena() == nullptr) delete entry_;
}
// This does what the typical MergePartialFromCodedStream() is expected to
// do, with the additional side-effect that if successful (i.e., if true is
// going to be its return value) it inserts the key-value pair into map_.
bool MergePartialFromCodedStream(io::CodedInputStream* input) {
// Look for the expected thing: a key and then a value. If it fails,
// invoke the enclosing class's MergePartialFromCodedStream, or return
// false if that would be pointless.
if (input->ExpectTag(kKeyTag)) {
if (!KeyTypeHandler::Read(input, &key_)) {
return false;
}
// Peek at the next byte to see if it is kValueTag. If not, bail out.
const void* data;
int size;
input->GetDirectBufferPointerInline(&data, &size);
// We could use memcmp here, but we don't bother. The tag is one byte.
static_assert(kTagSize == 1, "tag size must be 1");
if (size > 0 && *reinterpret_cast<const char*>(data) == kValueTag) {
typename Map::size_type map_size = map_->size();
value_ptr_ = &(*map_)[key_];
if (PROTOBUF_PREDICT_TRUE(map_size != map_->size())) {
// We created a new key-value pair. Fill in the value.
typedef
typename MapIf<ValueTypeHandler::kIsEnum, int*, Value*>::type T;
input->Skip(kTagSize); // Skip kValueTag.
if (!ValueTypeHandler::Read(input,
reinterpret_cast<T>(value_ptr_))) {
map_->erase(key_); // Failure! Undo insertion.
return false;
}
if (input->ExpectAtEnd()) return true;
return ReadBeyondKeyValuePair(input);
}
}
} else {
key_ = Key();
}
NewEntry();
*entry_->mutable_key() = key_;
const bool result = entry_->MergePartialFromCodedStream(input);
if (result) UseKeyAndValueFromEntry();
return result;
}
const char* _InternalParse(const char* ptr, ParseContext* ctx) {
if (PROTOBUF_PREDICT_TRUE(!ctx->Done(&ptr) && *ptr == kKeyTag)) {
ptr = KeyTypeHandler::Read(ptr + 1, ctx, &key_);
if (PROTOBUF_PREDICT_FALSE(!ptr || !Derived::ValidateKey(&key_))) {
return nullptr;
}
if (PROTOBUF_PREDICT_TRUE(!ctx->Done(&ptr) && *ptr == kValueTag)) {
typename Map::size_type map_size = map_->size();
value_ptr_ = &(*map_)[key_];
if (PROTOBUF_PREDICT_TRUE(map_size != map_->size())) {
using T =
typename MapIf<ValueTypeHandler::kIsEnum, int*, Value*>::type;
ptr = ValueTypeHandler::Read(ptr + 1, ctx,
reinterpret_cast<T>(value_ptr_));
if (PROTOBUF_PREDICT_FALSE(!ptr ||
!Derived::ValidateValue(value_ptr_))) {
map_->erase(key_); // Failure! Undo insertion.
return nullptr;
}
if (PROTOBUF_PREDICT_TRUE(ctx->Done(&ptr))) return ptr;
if (!ptr) return nullptr;
NewEntry();
ValueMover::Move(value_ptr_, entry_->mutable_value());
map_->erase(key_);
goto move_key;
}
} else {
if (!ptr) return nullptr;
}
NewEntry();
move_key:
KeyMover::Move(&key_, entry_->mutable_key());
} else {
if (!ptr) return nullptr;
NewEntry();
}
ptr = entry_->_InternalParse(ptr, ctx);
if (ptr) UseKeyAndValueFromEntry();
return ptr;
}
template <typename UnknownType>
const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx,
bool (*is_valid)(int), uint32 field_num,
InternalMetadata* metadata) {
auto entry = NewEntry();
ptr = entry->_InternalParse(ptr, ctx);
if (!ptr) return nullptr;
if (is_valid(entry->value())) {
UseKeyAndValueFromEntry();
} else {
WriteLengthDelimited(field_num, entry->SerializeAsString(),
metadata->mutable_unknown_fields<UnknownType>());
}
return ptr;
}
MapEntryImpl* NewEntry() { return entry_ = mf_->NewEntry(); }
const Key& key() const { return key_; }
const Value& value() const { return *value_ptr_; }
const Key& entry_key() const { return entry_->key(); }
const Value& entry_value() const { return entry_->value(); }
private:
void UseKeyAndValueFromEntry() {
// Update key_ in case we need it later (because key() is called).
// This is potentially inefficient, especially if the key is
// expensive to copy (e.g., a long string), but this is a cold
// path, so it's not a big deal.
key_ = entry_->key();
value_ptr_ = &(*map_)[key_];
ValueMover::Move(entry_->mutable_value(), value_ptr_);
}
// After reading a key and value successfully, and inserting that data
// into map_, we are not at the end of the input. This is unusual, but
// allowed by the spec.
bool ReadBeyondKeyValuePair(io::CodedInputStream* input) PROTOBUF_COLD {
NewEntry();
ValueMover::Move(value_ptr_, entry_->mutable_value());
map_->erase(key_);
KeyMover::Move(&key_, entry_->mutable_key());
const bool result = entry_->MergePartialFromCodedStream(input);
if (result) UseKeyAndValueFromEntry();
return result;
}
typedef MoveHelper<KeyTypeHandler::kIsEnum, KeyTypeHandler::kIsMessage,
KeyTypeHandler::kWireType ==
WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
Key>
KeyMover;
typedef MoveHelper<ValueTypeHandler::kIsEnum, ValueTypeHandler::kIsMessage,
ValueTypeHandler::kWireType ==
WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
Value>
ValueMover;
MapField* const mf_;
Map* const map_;
Key key_;
Value* value_ptr_;
MapEntryImpl* entry_ = nullptr;
};
protected:
void set_has_key() { _has_bits_[0] |= 0x00000001u; }
bool has_key() const { return (_has_bits_[0] & 0x00000001u) != 0; }
void clear_has_key() { _has_bits_[0] &= ~0x00000001u; }
void set_has_value() { _has_bits_[0] |= 0x00000002u; }
bool has_value() const { return (_has_bits_[0] & 0x00000002u) != 0; }
void clear_has_value() { _has_bits_[0] &= ~0x00000002u; }
public:
inline Arena* GetArena() const { return Base::GetArena(); }
public: // Needed for constructing tables
KeyOnMemory key_;
ValueOnMemory value_;
uint32 _has_bits_[1];
private:
friend class ::PROTOBUF_NAMESPACE_ID::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
template <typename C, typename K, typename V, WireFormatLite::FieldType,
WireFormatLite::FieldType>
friend class internal::MapEntry;
template <typename C, typename K, typename V, WireFormatLite::FieldType,
WireFormatLite::FieldType>
friend class internal::MapFieldLite;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapEntryImpl);
};
template <typename T, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
WireFormatLite::FieldType kValueFieldType>
class MapEntryLite : public MapEntryImpl<T, MessageLite, Key, Value,
kKeyFieldType, kValueFieldType> {
public:
typedef MapEntryImpl<T, MessageLite, Key, Value, kKeyFieldType,
kValueFieldType>
SuperType;
constexpr MapEntryLite() {}
explicit MapEntryLite(Arena* arena) : SuperType(arena) {}
~MapEntryLite() { MessageLite::_internal_metadata_.Delete<std::string>(); }
void MergeFrom(const MapEntryLite& other) { MergeFromInternal(other); }
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapEntryLite);
};
// The completely unprincipled and unwieldy use of template parameters in
// the map code necessitates wrappers to make the code a little bit more
// manageable.
template <typename Derived>
struct DeconstructMapEntry;
template <typename T, typename K, typename V, WireFormatLite::FieldType key,
WireFormatLite::FieldType value>
struct DeconstructMapEntry<MapEntryLite<T, K, V, key, value> > {
typedef K Key;
typedef V Value;
static const WireFormatLite::FieldType kKeyFieldType = key;
static const WireFormatLite::FieldType kValueFieldType = value;
};
// Helpers for deterministic serialization =============================
// This struct can be used with any generic sorting algorithm. If the Key
// type is relatively small and easy to copy then copying Keys into an
// array of SortItems can be beneficial. Then all the data the sorting
// algorithm needs to touch is in that one array.
template <typename Key, typename PtrToKeyValuePair>
struct SortItem {
SortItem() {}
explicit SortItem(PtrToKeyValuePair p) : first(p->first), second(p) {}
Key first;
PtrToKeyValuePair second;
};
template <typename T>
struct CompareByFirstField {
bool operator()(const T& a, const T& b) const { return a.first < b.first; }
};
template <typename T>
struct CompareByDerefFirst {
bool operator()(const T& a, const T& b) const { return a->first < b->first; }
};
// Helper for table driven serialization
template <WireFormatLite::FieldType FieldType>
struct FromHelper {
template <typename T>
static const T& From(const T& x) {
return x;
}
};
template <>
struct FromHelper<WireFormatLite::TYPE_STRING> {
static ArenaStringPtr From(const std::string& x) {
ArenaStringPtr res;
TaggedPtr<std::string> ptr;
ptr.Set(const_cast<std::string*>(&x));
res.UnsafeSetTaggedPointer(ptr);
return res;
}
};
template <>
struct FromHelper<WireFormatLite::TYPE_BYTES> {
static ArenaStringPtr From(const std::string& x) {
ArenaStringPtr res;
TaggedPtr<std::string> ptr;
ptr.Set(const_cast<std::string*>(&x));
res.UnsafeSetTaggedPointer(ptr);
return res;
}
};
template <>
struct FromHelper<WireFormatLite::TYPE_MESSAGE> {
template <typename T>
static T* From(const T& x) {
return const_cast<T*>(&x);
}
};
template <typename MapEntryType>
struct MapEntryHelper;
template <typename T, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
WireFormatLite::FieldType kValueFieldType>
struct MapEntryHelper<
MapEntryLite<T, Key, Value, kKeyFieldType, kValueFieldType> > {
// Provide utilities to parse/serialize key/value. Provide utilities to
// manipulate internal stored type.
typedef MapTypeHandler<kKeyFieldType, Key> KeyTypeHandler;
typedef MapTypeHandler<kValueFieldType, Value> ValueTypeHandler;
// Define internal memory layout. Strings and messages are stored as
// pointers, while other types are stored as values.
typedef typename KeyTypeHandler::TypeOnMemory KeyOnMemory;
typedef typename ValueTypeHandler::TypeOnMemory ValueOnMemory;
explicit MapEntryHelper(const MapPair<Key, Value>& map_pair)
: _has_bits_(3),
_cached_size_(2 + KeyTypeHandler::GetCachedSize(map_pair.first) +
ValueTypeHandler::GetCachedSize(map_pair.second)),
key_(FromHelper<kKeyFieldType>::From(map_pair.first)),
value_(FromHelper<kValueFieldType>::From(map_pair.second)) {}
// Purposely not following the style guide naming. These are the names
// the proto compiler would generate given the map entry descriptor.
// The proto compiler generates the offsets in this struct as if this was
// a regular message. This way the table driven code barely notices it's
// dealing with a map field.
uint32 _has_bits_; // NOLINT
uint32 _cached_size_; // NOLINT
KeyOnMemory key_; // NOLINT
ValueOnMemory value_; // NOLINT
};
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_MAP_ENTRY_LITE_H__
| 24,921 | 37.107034 | 87 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/map_field_lite.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__
#define GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__
#include <type_traits>
#include <google/protobuf/parse_context.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/map.h>
#include <google/protobuf/map_entry_lite.h>
#include <google/protobuf/port.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/port_def.inc>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
namespace internal {
// This class provides access to map field using generated api. It is used for
// internal generated message implementation only. Users should never use this
// directly.
template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType key_wire_type,
WireFormatLite::FieldType value_wire_type>
class MapFieldLite {
// Define message type for internal repeated field.
typedef Derived EntryType;
public:
typedef Map<Key, T> MapType;
typedef EntryType EntryTypeTrait;
constexpr MapFieldLite() {}
explicit MapFieldLite(Arena* arena) : map_(arena) {}
// Accessors
const Map<Key, T>& GetMap() const { return map_; }
Map<Key, T>* MutableMap() { return &map_; }
// Convenient methods for generated message implementation.
int size() const { return static_cast<int>(map_.size()); }
void Clear() { return map_.clear(); }
void MergeFrom(const MapFieldLite& other) {
for (typename Map<Key, T>::const_iterator it = other.map_.begin();
it != other.map_.end(); ++it) {
map_[it->first] = it->second;
}
}
void Swap(MapFieldLite* other) { map_.swap(other->map_); }
// Used in the implementation of parsing. Caller should take the ownership iff
// arena_ is NULL.
EntryType* NewEntry() const {
return Arena::CreateMessage<EntryType>(map_.arena());
}
// Used in the implementation of serializing enum value type. Caller should
// take the ownership iff arena_ is NULL.
EntryType* NewEnumEntryWrapper(const Key& key, const T t) const {
return EntryType::EnumWrap(key, t, map_.arena_);
}
// Used in the implementation of serializing other value types. Caller should
// take the ownership iff arena_ is NULL.
EntryType* NewEntryWrapper(const Key& key, const T& t) const {
return EntryType::Wrap(key, t, map_.arena_);
}
const char* _InternalParse(const char* ptr, ParseContext* ctx) {
typename Derived::template Parser<MapFieldLite, Map<Key, T>> parser(this);
return parser._InternalParse(ptr, ctx);
}
template <typename UnknownType>
const char* ParseWithEnumValidation(const char* ptr, ParseContext* ctx,
bool (*is_valid)(int), uint32 field_num,
InternalMetadata* metadata) {
typename Derived::template Parser<MapFieldLite, Map<Key, T>> parser(this);
return parser.template ParseWithEnumValidation<UnknownType>(
ptr, ctx, is_valid, field_num, metadata);
}
private:
typedef void DestructorSkippable_;
Map<Key, T> map_;
friend class ::PROTOBUF_NAMESPACE_ID::Arena;
};
template <typename UnknownType, typename T>
struct EnumParseWrapper {
const char* _InternalParse(const char* ptr, ParseContext* ctx) {
return map_field->template ParseWithEnumValidation<UnknownType>(
ptr, ctx, is_valid, field_num, metadata);
}
T* map_field;
bool (*is_valid)(int);
uint32 field_num;
InternalMetadata* metadata;
};
// Helper function because the typenames of maps are horrendous to print. This
// leverages compiler type deduction, to keep all type data out of the
// generated code
template <typename UnknownType, typename T>
EnumParseWrapper<UnknownType, T> InitEnumParseWrapper(
T* map_field, bool (*is_valid)(int), uint32 field_num,
InternalMetadata* metadata) {
return EnumParseWrapper<UnknownType, T>{map_field, is_valid, field_num,
metadata};
}
// True if IsInitialized() is true for value field in all elements of t. T is
// expected to be message. It's useful to have this helper here to keep the
// protobuf compiler from ever having to emit loops in IsInitialized() methods.
// We want the C++ compiler to inline this or not as it sees fit.
template <typename Derived, typename Key, typename T,
WireFormatLite::FieldType key_wire_type,
WireFormatLite::FieldType value_wire_type>
bool AllAreInitialized(const MapFieldLite<Derived, Key, T, key_wire_type,
value_wire_type>& field) {
const auto& t = field.GetMap();
for (typename Map<Key, T>::const_iterator it = t.begin(); it != t.end();
++it) {
if (!it->second.IsInitialized()) return false;
}
return true;
}
template <typename MEntry>
struct MapEntryToMapField : MapEntryToMapField<typename MEntry::SuperType> {};
template <typename T, typename Key, typename Value,
WireFormatLite::FieldType kKeyFieldType,
WireFormatLite::FieldType kValueFieldType>
struct MapEntryToMapField<
MapEntryLite<T, Key, Value, kKeyFieldType, kValueFieldType>> {
typedef MapFieldLite<
MapEntryLite<T, Key, Value, kKeyFieldType, kValueFieldType>, Key, Value,
kKeyFieldType, kValueFieldType>
MapFieldType;
};
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_MAP_FIELD_LITE_H__
| 7,104 | 37.61413 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/metadata_lite.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_METADATA_LITE_H__
#define GOOGLE_PROTOBUF_METADATA_LITE_H__
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/port.h>
#include <google/protobuf/port_def.inc>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
namespace internal {
// This is the representation for messages that support arena allocation. It
// uses a tagged pointer to either store the Arena pointer, if there are no
// unknown fields, or a pointer to a block of memory with both the Arena pointer
// and the UnknownFieldSet, if there are unknown fields. This optimization
// allows for "zero-overhead" storage of the Arena pointer, relative to the
// above baseline implementation.
//
// The tagged pointer uses the LSB to disambiguate cases, and uses bit 0 == 0 to
// indicate an arena pointer and bit 0 == 1 to indicate a UFS+Arena-container
// pointer.
class InternalMetadata {
public:
constexpr InternalMetadata() : ptr_(nullptr) {}
explicit InternalMetadata(Arena* arena) : ptr_(arena) {}
template <typename T>
void Delete() {
// Note that Delete<> should be called not more than once.
if (have_unknown_fields() && arena() == NULL) {
delete PtrValue<Container<T>>();
}
}
PROTOBUF_ALWAYS_INLINE Arena* arena() const {
if (PROTOBUF_PREDICT_FALSE(have_unknown_fields())) {
return PtrValue<ContainerBase>()->arena;
} else {
return PtrValue<Arena>();
}
}
PROTOBUF_ALWAYS_INLINE bool have_unknown_fields() const {
return PtrTag() == kTagContainer;
}
PROTOBUF_ALWAYS_INLINE void* raw_arena_ptr() const { return ptr_; }
template <typename T>
PROTOBUF_ALWAYS_INLINE const T& unknown_fields(
const T& (*default_instance)()) const {
if (PROTOBUF_PREDICT_FALSE(have_unknown_fields())) {
return PtrValue<Container<T>>()->unknown_fields;
} else {
return default_instance();
}
}
template <typename T>
PROTOBUF_ALWAYS_INLINE T* mutable_unknown_fields() {
if (PROTOBUF_PREDICT_TRUE(have_unknown_fields())) {
return &PtrValue<Container<T>>()->unknown_fields;
} else {
return mutable_unknown_fields_slow<T>();
}
}
template <typename T>
PROTOBUF_ALWAYS_INLINE void Swap(InternalMetadata* other) {
// Semantics here are that we swap only the unknown fields, not the arena
// pointer. We cannot simply swap ptr_ with other->ptr_ because we need to
// maintain our own arena ptr. Also, our ptr_ and other's ptr_ may be in
// different states (direct arena pointer vs. container with UFS) so we
// cannot simply swap ptr_ and then restore the arena pointers. We reuse
// UFS's swap implementation instead.
if (have_unknown_fields() || other->have_unknown_fields()) {
DoSwap<T>(other->mutable_unknown_fields<T>());
}
}
template <typename T>
PROTOBUF_ALWAYS_INLINE void MergeFrom(const InternalMetadata& other) {
if (other.have_unknown_fields()) {
DoMergeFrom<T>(other.unknown_fields<T>(nullptr));
}
}
template <typename T>
PROTOBUF_ALWAYS_INLINE void Clear() {
if (have_unknown_fields()) {
DoClear<T>();
}
}
private:
void* ptr_;
// Tagged pointer implementation.
enum {
// ptr_ is an Arena*.
kTagArena = 0,
// ptr_ is a Container*.
kTagContainer = 1,
};
static constexpr intptr_t kPtrTagMask = 1;
static constexpr intptr_t kPtrValueMask = ~kPtrTagMask;
// Accessors for pointer tag and pointer value.
PROTOBUF_ALWAYS_INLINE int PtrTag() const {
return reinterpret_cast<intptr_t>(ptr_) & kPtrTagMask;
}
template <typename U>
U* PtrValue() const {
return reinterpret_cast<U*>(reinterpret_cast<intptr_t>(ptr_) &
kPtrValueMask);
}
// If ptr_'s tag is kTagContainer, it points to an instance of this struct.
struct ContainerBase {
Arena* arena;
};
template <typename T>
struct Container : public ContainerBase {
T unknown_fields;
};
template <typename T>
PROTOBUF_NOINLINE T* mutable_unknown_fields_slow() {
Arena* my_arena = arena();
Container<T>* container = Arena::Create<Container<T>>(my_arena);
// Two-step assignment works around a bug in clang's static analyzer:
// https://bugs.llvm.org/show_bug.cgi?id=34198.
ptr_ = container;
ptr_ = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(ptr_) |
kTagContainer);
container->arena = my_arena;
return &(container->unknown_fields);
}
// Templated functions.
template <typename T>
void DoClear() {
mutable_unknown_fields<T>()->Clear();
}
template <typename T>
void DoMergeFrom(const T& other) {
mutable_unknown_fields<T>()->MergeFrom(other);
}
template <typename T>
void DoSwap(T* other) {
mutable_unknown_fields<T>()->Swap(other);
}
};
// String Template specializations.
template <>
inline void InternalMetadata::DoClear<std::string>() {
mutable_unknown_fields<std::string>()->clear();
}
template <>
inline void InternalMetadata::DoMergeFrom<std::string>(
const std::string& other) {
mutable_unknown_fields<std::string>()->append(other);
}
template <>
inline void InternalMetadata::DoSwap<std::string>(std::string* other) {
mutable_unknown_fields<std::string>()->swap(*other);
}
// This helper RAII class is needed to efficiently parse unknown fields. We
// should only call mutable_unknown_fields if there are actual unknown fields.
// The obvious thing to just use a stack string and swap it at the end of
// the parse won't work, because the destructor of StringOutputStream needs to
// be called before we can modify the string (it check-fails). Using
// LiteUnknownFieldSetter setter(&_internal_metadata_);
// StringOutputStream stream(setter.buffer());
// guarantees that the string is only swapped after stream is destroyed.
class PROTOBUF_EXPORT LiteUnknownFieldSetter {
public:
explicit LiteUnknownFieldSetter(InternalMetadata* metadata)
: metadata_(metadata) {
if (metadata->have_unknown_fields()) {
buffer_.swap(*metadata->mutable_unknown_fields<std::string>());
}
}
~LiteUnknownFieldSetter() {
if (!buffer_.empty())
metadata_->mutable_unknown_fields<std::string>()->swap(buffer_);
}
std::string* buffer() { return &buffer_; }
private:
InternalMetadata* metadata_;
std::string buffer_;
};
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_METADATA_LITE_H__
| 8,270 | 32.216867 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/port.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
// A common header that is included across all protobuf headers. We do our best
// to avoid #defining any macros here; instead we generally put macros in
// port_def.inc and port_undef.inc so they are not visible from outside of
// protobuf.
#ifndef GOOGLE_PROTOBUF_PORT_H__
#define GOOGLE_PROTOBUF_PORT_H__
#include <google/protobuf/stubs/port.h>
#endif // GOOGLE_PROTOBUF_PORT_H__
| 2,050 | 45.613636 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/unknown_field_set.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// Contains classes used to keep track of unrecognized fields seen while
// parsing a protocol message.
#ifndef GOOGLE_PROTOBUF_UNKNOWN_FIELD_SET_H__
#define GOOGLE_PROTOBUF_UNKNOWN_FIELD_SET_H__
#include <assert.h>
#include <string>
#include <vector>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/parse_context.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/port.h>
#include <google/protobuf/port_def.inc>
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
namespace internal {
class InternalMetadata; // metadata_lite.h
class WireFormat; // wire_format.h
class MessageSetFieldSkipperUsingCord;
// extension_set_heavy.cc
} // namespace internal
class Message; // message.h
class UnknownField; // below
// An UnknownFieldSet contains fields that were encountered while parsing a
// message but were not defined by its type. Keeping track of these can be
// useful, especially in that they may be written if the message is serialized
// again without being cleared in between. This means that software which
// simply receives messages and forwards them to other servers does not need
// to be updated every time a new field is added to the message definition.
//
// To get the UnknownFieldSet attached to any message, call
// Reflection::GetUnknownFields().
//
// This class is necessarily tied to the protocol buffer wire format, unlike
// the Reflection interface which is independent of any serialization scheme.
class PROTOBUF_EXPORT UnknownFieldSet {
public:
UnknownFieldSet();
~UnknownFieldSet();
// Remove all fields.
inline void Clear();
// Remove all fields and deallocate internal data objects
void ClearAndFreeMemory();
// Is this set empty?
inline bool empty() const;
// Merge the contents of some other UnknownFieldSet with this one.
void MergeFrom(const UnknownFieldSet& other);
// Similar to above, but this function will destroy the contents of other.
void MergeFromAndDestroy(UnknownFieldSet* other);
// Merge the contents an UnknownFieldSet with the UnknownFieldSet in
// *metadata, if there is one. If *metadata doesn't have an UnknownFieldSet
// then add one to it and make it be a copy of the first arg.
static void MergeToInternalMetadata(const UnknownFieldSet& other,
internal::InternalMetadata* metadata);
// Swaps the contents of some other UnknownFieldSet with this one.
inline void Swap(UnknownFieldSet* x);
// Computes (an estimate of) the total number of bytes currently used for
// storing the unknown fields in memory. Does NOT include
// sizeof(*this) in the calculation.
size_t SpaceUsedExcludingSelfLong() const;
int SpaceUsedExcludingSelf() const {
return internal::ToIntSize(SpaceUsedExcludingSelfLong());
}
// Version of SpaceUsed() including sizeof(*this).
size_t SpaceUsedLong() const;
int SpaceUsed() const { return internal::ToIntSize(SpaceUsedLong()); }
// Returns the number of fields present in the UnknownFieldSet.
inline int field_count() const;
// Get a field in the set, where 0 <= index < field_count(). The fields
// appear in the order in which they were added.
inline const UnknownField& field(int index) const;
// Get a mutable pointer to a field in the set, where
// 0 <= index < field_count(). The fields appear in the order in which
// they were added.
inline UnknownField* mutable_field(int index);
// Adding fields ---------------------------------------------------
void AddVarint(int number, uint64 value);
void AddFixed32(int number, uint32 value);
void AddFixed64(int number, uint64 value);
void AddLengthDelimited(int number, const std::string& value);
std::string* AddLengthDelimited(int number);
UnknownFieldSet* AddGroup(int number);
// Adds an unknown field from another set.
void AddField(const UnknownField& field);
// Delete fields with indices in the range [start .. start+num-1].
// Caution: implementation moves all fields with indices [start+num .. ].
void DeleteSubrange(int start, int num);
// Delete all fields with a specific field number. The order of left fields
// is preserved.
// Caution: implementation moves all fields after the first deleted field.
void DeleteByNumber(int number);
// Parsing helpers -------------------------------------------------
// These work exactly like the similarly-named methods of Message.
bool MergeFromCodedStream(io::CodedInputStream* input);
bool ParseFromCodedStream(io::CodedInputStream* input);
bool ParseFromZeroCopyStream(io::ZeroCopyInputStream* input);
bool ParseFromArray(const void* data, int size);
inline bool ParseFromString(const std::string& data) {
return ParseFromArray(data.data(), static_cast<int>(data.size()));
}
// Merges this message's unknown field data (if any). This works whether
// the message is a lite or full proto (for legacy reasons, lite and full
// return different types for MessageType::unknown_fields()).
template <typename MessageType>
bool MergeFromMessage(const MessageType& message);
static const UnknownFieldSet& default_instance();
private:
// For InternalMergeFrom
friend class UnknownField;
// Merges from other UnknownFieldSet. This method assumes, that this object
// is newly created and has no fields.
void InternalMergeFrom(const UnknownFieldSet& other);
void ClearFallback();
template <typename MessageType,
typename std::enable_if<
std::is_base_of<Message, MessageType>::value, int>::type = 0>
bool InternalMergeFromMessage(const MessageType& message) {
MergeFrom(message.GetReflection()->GetUnknownFields(message));
return true;
}
template <typename MessageType,
typename std::enable_if<
std::is_base_of<MessageLite, MessageType>::value &&
!std::is_base_of<Message, MessageType>::value,
int>::type = 0>
bool InternalMergeFromMessage(const MessageType& message) {
const auto& unknown_fields = message.unknown_fields();
io::ArrayInputStream array_stream(unknown_fields.data(),
unknown_fields.size());
io::CodedInputStream coded_stream(&array_stream);
return MergeFromCodedStream(&coded_stream);
}
std::vector<UnknownField> fields_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(UnknownFieldSet);
};
namespace internal {
inline void WriteVarint(uint32 num, uint64 val, UnknownFieldSet* unknown) {
unknown->AddVarint(num, val);
}
inline void WriteLengthDelimited(uint32 num, StringPiece val,
UnknownFieldSet* unknown) {
unknown->AddLengthDelimited(num)->assign(val.data(), val.size());
}
PROTOBUF_EXPORT
const char* UnknownGroupParse(UnknownFieldSet* unknown, const char* ptr,
ParseContext* ctx);
PROTOBUF_EXPORT
const char* UnknownFieldParse(uint64 tag, UnknownFieldSet* unknown,
const char* ptr, ParseContext* ctx);
} // namespace internal
// Represents one field in an UnknownFieldSet.
class PROTOBUF_EXPORT UnknownField {
public:
enum Type {
TYPE_VARINT,
TYPE_FIXED32,
TYPE_FIXED64,
TYPE_LENGTH_DELIMITED,
TYPE_GROUP
};
// The field's field number, as seen on the wire.
inline int number() const;
// The field type.
inline Type type() const;
// Accessors -------------------------------------------------------
// Each method works only for UnknownFields of the corresponding type.
inline uint64 varint() const;
inline uint32 fixed32() const;
inline uint64 fixed64() const;
inline const std::string& length_delimited() const;
inline const UnknownFieldSet& group() const;
inline void set_varint(uint64 value);
inline void set_fixed32(uint32 value);
inline void set_fixed64(uint64 value);
inline void set_length_delimited(const std::string& value);
inline std::string* mutable_length_delimited();
inline UnknownFieldSet* mutable_group();
// Serialization API.
// These methods can take advantage of the underlying implementation and may
// archieve a better performance than using getters to retrieve the data and
// do the serialization yourself.
void SerializeLengthDelimitedNoTag(io::CodedOutputStream* output) const {
output->SetCur(InternalSerializeLengthDelimitedNoTag(output->Cur(),
output->EpsCopy()));
}
inline size_t GetLengthDelimitedSize() const;
uint8* InternalSerializeLengthDelimitedNoTag(
uint8* target, io::EpsCopyOutputStream* stream) const;
// If this UnknownField contains a pointer, delete it.
void Delete();
// Make a deep copy of any pointers in this UnknownField.
void DeepCopy(const UnknownField& other);
// Set the wire type of this UnknownField. Should only be used when this
// UnknownField is being created.
inline void SetType(Type type);
union LengthDelimited {
std::string* string_value;
};
uint32 number_;
uint32 type_;
union {
uint64 varint_;
uint32 fixed32_;
uint64 fixed64_;
mutable union LengthDelimited length_delimited_;
UnknownFieldSet* group_;
} data_;
};
// ===================================================================
// inline implementations
inline UnknownFieldSet::UnknownFieldSet() {}
inline UnknownFieldSet::~UnknownFieldSet() { Clear(); }
inline void UnknownFieldSet::ClearAndFreeMemory() { Clear(); }
inline void UnknownFieldSet::Clear() {
if (!fields_.empty()) {
ClearFallback();
}
}
inline bool UnknownFieldSet::empty() const { return fields_.empty(); }
inline void UnknownFieldSet::Swap(UnknownFieldSet* x) {
fields_.swap(x->fields_);
}
inline int UnknownFieldSet::field_count() const {
return static_cast<int>(fields_.size());
}
inline const UnknownField& UnknownFieldSet::field(int index) const {
return (fields_)[static_cast<size_t>(index)];
}
inline UnknownField* UnknownFieldSet::mutable_field(int index) {
return &(fields_)[static_cast<size_t>(index)];
}
inline void UnknownFieldSet::AddLengthDelimited(int number,
const std::string& value) {
AddLengthDelimited(number)->assign(value);
}
inline int UnknownField::number() const { return static_cast<int>(number_); }
inline UnknownField::Type UnknownField::type() const {
return static_cast<Type>(type_);
}
inline uint64 UnknownField::varint() const {
assert(type() == TYPE_VARINT);
return data_.varint_;
}
inline uint32 UnknownField::fixed32() const {
assert(type() == TYPE_FIXED32);
return data_.fixed32_;
}
inline uint64 UnknownField::fixed64() const {
assert(type() == TYPE_FIXED64);
return data_.fixed64_;
}
inline const std::string& UnknownField::length_delimited() const {
assert(type() == TYPE_LENGTH_DELIMITED);
return *data_.length_delimited_.string_value;
}
inline const UnknownFieldSet& UnknownField::group() const {
assert(type() == TYPE_GROUP);
return *data_.group_;
}
inline void UnknownField::set_varint(uint64 value) {
assert(type() == TYPE_VARINT);
data_.varint_ = value;
}
inline void UnknownField::set_fixed32(uint32 value) {
assert(type() == TYPE_FIXED32);
data_.fixed32_ = value;
}
inline void UnknownField::set_fixed64(uint64 value) {
assert(type() == TYPE_FIXED64);
data_.fixed64_ = value;
}
inline void UnknownField::set_length_delimited(const std::string& value) {
assert(type() == TYPE_LENGTH_DELIMITED);
data_.length_delimited_.string_value->assign(value);
}
inline std::string* UnknownField::mutable_length_delimited() {
assert(type() == TYPE_LENGTH_DELIMITED);
return data_.length_delimited_.string_value;
}
inline UnknownFieldSet* UnknownField::mutable_group() {
assert(type() == TYPE_GROUP);
return data_.group_;
}
template <typename MessageType>
bool UnknownFieldSet::MergeFromMessage(const MessageType& message) {
// SFINAE will route to the right version.
return InternalMergeFromMessage(message);
}
inline size_t UnknownField::GetLengthDelimitedSize() const {
GOOGLE_DCHECK_EQ(TYPE_LENGTH_DELIMITED, type());
return data_.length_delimited_.string_value->size();
}
inline void UnknownField::SetType(Type type) {
type_ = type;
}
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_UNKNOWN_FIELD_SET_H__
| 14,401 | 33.956311 | 78 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/io/io_win32.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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: [email protected] (Laszlo Csomor)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
// This file contains the declarations for Windows implementations of
// commonly used POSIX functions such as open(2) and access(2), as well
// as macro definitions for flags of these functions.
//
// By including this file you'll redefine open/access/etc. to
// ::google::protobuf::io::win32::{open/access/etc.}.
// Make sure you don't include a header that attempts to redeclare or
// redefine these functions, that'll lead to confusing compilation
// errors. It's best to #include this file as the last one to ensure that.
//
// This file is only used on Windows, it's empty on other platforms.
#ifndef GOOGLE_PROTOBUF_IO_IO_WIN32_H__
#define GOOGLE_PROTOBUF_IO_IO_WIN32_H__
#if defined(_WIN32)
#include <functional>
#include <string>
#include <google/protobuf/port.h>
#include <google/protobuf/port_def.inc>
// Compilers on Windows other than MSVC (e.g. Cygwin, MinGW32) define the
// following functions already, except for mkdir.
namespace google {
namespace protobuf {
namespace io {
namespace win32 {
PROTOBUF_EXPORT FILE* fopen(const char* path, const char* mode);
PROTOBUF_EXPORT int access(const char* path, int mode);
PROTOBUF_EXPORT int chdir(const char* path);
PROTOBUF_EXPORT int close(int fd);
PROTOBUF_EXPORT int dup(int fd);
PROTOBUF_EXPORT int dup2(int fd1, int fd2);
PROTOBUF_EXPORT int mkdir(const char* path, int _mode);
PROTOBUF_EXPORT int open(const char* path, int flags, int mode = 0);
PROTOBUF_EXPORT int read(int fd, void* buffer, size_t size);
PROTOBUF_EXPORT int setmode(int fd, int mode);
PROTOBUF_EXPORT int stat(const char* path, struct _stat* buffer);
PROTOBUF_EXPORT int write(int fd, const void* buffer, size_t size);
PROTOBUF_EXPORT std::wstring testonly_utf8_to_winpath(const char* path);
enum class ExpandWildcardsResult {
kSuccess = 0,
kErrorNoMatchingFile = 1,
kErrorInputPathConversion = 2,
kErrorOutputPathConversion = 3,
};
// Expand wildcards in a path pattern, feed the result to a consumer function.
//
// `path` must be a valid, Windows-style path. It may be absolute, or relative
// to the current working directory, and it may contain wildcards ("*" and "?")
// in the last path segment. This function passes all matching file names to
// `consume`. The resulting paths may not be absolute nor normalized.
//
// The function returns a value from `ExpandWildcardsResult`.
PROTOBUF_EXPORT ExpandWildcardsResult ExpandWildcards(
const std::string& path, std::function<void(const std::string&)> consume);
namespace strings {
// Convert from UTF-16 to Active-Code-Page-encoded or to UTF-8-encoded text.
PROTOBUF_EXPORT bool wcs_to_mbs(const wchar_t* s, std::string* out,
bool outUtf8);
// Convert from Active-Code-Page-encoded or UTF-8-encoded text to UTF-16.
PROTOBUF_EXPORT bool mbs_to_wcs(const char* s, std::wstring* out, bool inUtf8);
// Convert from UTF-8-encoded text to UTF-16.
PROTOBUF_EXPORT bool utf8_to_wcs(const char* input, std::wstring* out);
// Convert from UTF-16-encoded text to UTF-8.
PROTOBUF_EXPORT bool wcs_to_utf8(const wchar_t* input, std::string* out);
} // namespace strings
} // namespace win32
} // namespace io
} // namespace protobuf
} // namespace google
#ifndef W_OK
#define W_OK 02 // not defined by MSVC for whatever reason
#endif
#ifndef F_OK
#define F_OK 00 // not defined by MSVC for whatever reason
#endif
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#include <google/protobuf/port_undef.inc>
#endif // defined(_WIN32)
#endif // GOOGLE_PROTOBUF_IO_IO_WIN32_H__
| 5,384 | 37.464286 | 79 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/io/zero_copy_stream.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains the ZeroCopyInputStream and ZeroCopyOutputStream
// interfaces, which represent abstract I/O streams to and from which
// protocol buffers can be read and written. For a few simple
// implementations of these interfaces, see zero_copy_stream_impl.h.
//
// These interfaces are different from classic I/O streams in that they
// try to minimize the amount of data copying that needs to be done.
// To accomplish this, responsibility for allocating buffers is moved to
// the stream object, rather than being the responsibility of the caller.
// So, the stream can return a buffer which actually points directly into
// the final data structure where the bytes are to be stored, and the caller
// can interact directly with that buffer, eliminating an intermediate copy
// operation.
//
// As an example, consider the common case in which you are reading bytes
// from an array that is already in memory (or perhaps an mmap()ed file).
// With classic I/O streams, you would do something like:
// char buffer[BUFFER_SIZE];
// input->Read(buffer, BUFFER_SIZE);
// DoSomething(buffer, BUFFER_SIZE);
// Then, the stream basically just calls memcpy() to copy the data from
// the array into your buffer. With a ZeroCopyInputStream, you would do
// this instead:
// const void* buffer;
// int size;
// input->Next(&buffer, &size);
// DoSomething(buffer, size);
// Here, no copy is performed. The input stream returns a pointer directly
// into the backing array, and the caller ends up reading directly from it.
//
// If you want to be able to read the old-fashion way, you can create
// a CodedInputStream or CodedOutputStream wrapping these objects and use
// their ReadRaw()/WriteRaw() methods. These will, of course, add a copy
// step, but Coded*Stream will handle buffering so at least it will be
// reasonably efficient.
//
// ZeroCopyInputStream example:
// // Read in a file and print its contents to stdout.
// int fd = open("myfile", O_RDONLY);
// ZeroCopyInputStream* input = new FileInputStream(fd);
//
// const void* buffer;
// int size;
// while (input->Next(&buffer, &size)) {
// cout.write(buffer, size);
// }
//
// delete input;
// close(fd);
//
// ZeroCopyOutputStream example:
// // Copy the contents of "infile" to "outfile", using plain read() for
// // "infile" but a ZeroCopyOutputStream for "outfile".
// int infd = open("infile", O_RDONLY);
// int outfd = open("outfile", O_WRONLY);
// ZeroCopyOutputStream* output = new FileOutputStream(outfd);
//
// void* buffer;
// int size;
// while (output->Next(&buffer, &size)) {
// int bytes = read(infd, buffer, size);
// if (bytes < size) {
// // Reached EOF.
// output->BackUp(size - bytes);
// break;
// }
// }
//
// delete output;
// close(infd);
// close(outfd);
#ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__
#define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
namespace io {
// Defined in this file.
class ZeroCopyInputStream;
class ZeroCopyOutputStream;
// Abstract interface similar to an input stream but designed to minimize
// copying.
class PROTOBUF_EXPORT ZeroCopyInputStream {
public:
ZeroCopyInputStream() {}
virtual ~ZeroCopyInputStream() {}
// Obtains a chunk of data from the stream.
//
// Preconditions:
// * "size" and "data" are not NULL.
//
// Postconditions:
// * If the returned value is false, there is no more data to return or
// an error occurred. All errors are permanent.
// * Otherwise, "size" points to the actual number of bytes read and "data"
// points to a pointer to a buffer containing these bytes.
// * Ownership of this buffer remains with the stream, and the buffer
// remains valid only until some other method of the stream is called
// or the stream is destroyed.
// * It is legal for the returned buffer to have zero size, as long
// as repeatedly calling Next() eventually yields a buffer with non-zero
// size.
virtual bool Next(const void** data, int* size) = 0;
// Backs up a number of bytes, so that the next call to Next() returns
// data again that was already returned by the last call to Next(). This
// is useful when writing procedures that are only supposed to read up
// to a certain point in the input, then return. If Next() returns a
// buffer that goes beyond what you wanted to read, you can use BackUp()
// to return to the point where you intended to finish.
//
// Preconditions:
// * The last method called must have been Next().
// * count must be less than or equal to the size of the last buffer
// returned by Next().
//
// Postconditions:
// * The last "count" bytes of the last buffer returned by Next() will be
// pushed back into the stream. Subsequent calls to Next() will return
// the same data again before producing new data.
virtual void BackUp(int count) = 0;
// Skips a number of bytes. Returns false if the end of the stream is
// reached or some input error occurred. In the end-of-stream case, the
// stream is advanced to the end of the stream (so ByteCount() will return
// the total size of the stream).
virtual bool Skip(int count) = 0;
// Returns the total number of bytes read since this object was created.
virtual int64_t ByteCount() const = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyInputStream);
};
// Abstract interface similar to an output stream but designed to minimize
// copying.
class PROTOBUF_EXPORT ZeroCopyOutputStream {
public:
ZeroCopyOutputStream() {}
virtual ~ZeroCopyOutputStream() {}
// Obtains a buffer into which data can be written. Any data written
// into this buffer will eventually (maybe instantly, maybe later on)
// be written to the output.
//
// Preconditions:
// * "size" and "data" are not NULL.
//
// Postconditions:
// * If the returned value is false, an error occurred. All errors are
// permanent.
// * Otherwise, "size" points to the actual number of bytes in the buffer
// and "data" points to the buffer.
// * Ownership of this buffer remains with the stream, and the buffer
// remains valid only until some other method of the stream is called
// or the stream is destroyed.
// * Any data which the caller stores in this buffer will eventually be
// written to the output (unless BackUp() is called).
// * It is legal for the returned buffer to have zero size, as long
// as repeatedly calling Next() eventually yields a buffer with non-zero
// size.
virtual bool Next(void** data, int* size) = 0;
// Backs up a number of bytes, so that the end of the last buffer returned
// by Next() is not actually written. This is needed when you finish
// writing all the data you want to write, but the last buffer was bigger
// than you needed. You don't want to write a bunch of garbage after the
// end of your data, so you use BackUp() to back up.
//
// Preconditions:
// * The last method called must have been Next().
// * count must be less than or equal to the size of the last buffer
// returned by Next().
// * The caller must not have written anything to the last "count" bytes
// of that buffer.
//
// Postconditions:
// * The last "count" bytes of the last buffer returned by Next() will be
// ignored.
virtual void BackUp(int count) = 0;
// Returns the total number of bytes written since this object was created.
virtual int64_t ByteCount() const = 0;
// Write a given chunk of data to the output. Some output streams may
// implement this in a way that avoids copying. Check AllowsAliasing() before
// calling WriteAliasedRaw(). It will GOOGLE_CHECK fail if WriteAliasedRaw() is
// called on a stream that does not allow aliasing.
//
// NOTE: It is caller's responsibility to ensure that the chunk of memory
// remains live until all of the data has been consumed from the stream.
virtual bool WriteAliasedRaw(const void* data, int size);
virtual bool AllowsAliasing() const { return false; }
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyOutputStream);
};
} // namespace io
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__
| 10,258 | 39.389764 | 81 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/io/zero_copy_stream_impl.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains common implementations of the interfaces defined in
// zero_copy_stream.h which are only included in the full (non-lite)
// protobuf library. These implementations include Unix file descriptors
// and C++ iostreams. See also: zero_copy_stream_impl_lite.h
#ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__
#define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__
#include <iosfwd>
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
namespace io {
// ===================================================================
// A ZeroCopyInputStream which reads from a file descriptor.
//
// FileInputStream is preferred over using an ifstream with IstreamInputStream.
// The latter will introduce an extra layer of buffering, harming performance.
// Also, it's conceivable that FileInputStream could someday be enhanced
// to use zero-copy file descriptors on OSs which support them.
class PROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream {
public:
// Creates a stream that reads from the given Unix file descriptor.
// If a block_size is given, it specifies the number of bytes that
// should be read and returned with each call to Next(). Otherwise,
// a reasonable default is used.
explicit FileInputStream(int file_descriptor, int block_size = -1);
// Flushes any buffers and closes the underlying file. Returns false if
// an error occurs during the process; use GetErrno() to examine the error.
// Even if an error occurs, the file descriptor is closed when this returns.
bool Close();
// By default, the file descriptor is not closed when the stream is
// destroyed. Call SetCloseOnDelete(true) to change that. WARNING:
// This leaves no way for the caller to detect if close() fails. If
// detecting close() errors is important to you, you should arrange
// to close the descriptor yourself.
void SetCloseOnDelete(bool value) { copying_input_.SetCloseOnDelete(value); }
// If an I/O error has occurred on this file descriptor, this is the
// errno from that error. Otherwise, this is zero. Once an error
// occurs, the stream is broken and all subsequent operations will
// fail.
int GetErrno() const { return copying_input_.GetErrno(); }
// implements ZeroCopyInputStream ----------------------------------
bool Next(const void** data, int* size) override;
void BackUp(int count) override;
bool Skip(int count) override;
int64_t ByteCount() const override;
private:
class PROTOBUF_EXPORT CopyingFileInputStream : public CopyingInputStream {
public:
CopyingFileInputStream(int file_descriptor);
~CopyingFileInputStream() override;
bool Close();
void SetCloseOnDelete(bool value) { close_on_delete_ = value; }
int GetErrno() const { return errno_; }
// implements CopyingInputStream ---------------------------------
int Read(void* buffer, int size) override;
int Skip(int count) override;
private:
// The file descriptor.
const int file_;
bool close_on_delete_;
bool is_closed_;
// The errno of the I/O error, if one has occurred. Otherwise, zero.
int errno_;
// Did we try to seek once and fail? If so, we assume this file descriptor
// doesn't support seeking and won't try again.
bool previous_seek_failed_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingFileInputStream);
};
CopyingFileInputStream copying_input_;
CopyingInputStreamAdaptor impl_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileInputStream);
};
// ===================================================================
// A ZeroCopyOutputStream which writes to a file descriptor.
//
// FileOutputStream is preferred over using an ofstream with
// OstreamOutputStream. The latter will introduce an extra layer of buffering,
// harming performance. Also, it's conceivable that FileOutputStream could
// someday be enhanced to use zero-copy file descriptors on OSs which
// support them.
class PROTOBUF_EXPORT FileOutputStream : public CopyingOutputStreamAdaptor {
public:
// Creates a stream that writes to the given Unix file descriptor.
// If a block_size is given, it specifies the size of the buffers
// that should be returned by Next(). Otherwise, a reasonable default
// is used.
explicit FileOutputStream(int file_descriptor, int block_size = -1);
~FileOutputStream() override;
// Flushes any buffers and closes the underlying file. Returns false if
// an error occurs during the process; use GetErrno() to examine the error.
// Even if an error occurs, the file descriptor is closed when this returns.
bool Close();
// By default, the file descriptor is not closed when the stream is
// destroyed. Call SetCloseOnDelete(true) to change that. WARNING:
// This leaves no way for the caller to detect if close() fails. If
// detecting close() errors is important to you, you should arrange
// to close the descriptor yourself.
void SetCloseOnDelete(bool value) { copying_output_.SetCloseOnDelete(value); }
// If an I/O error has occurred on this file descriptor, this is the
// errno from that error. Otherwise, this is zero. Once an error
// occurs, the stream is broken and all subsequent operations will
// fail.
int GetErrno() const { return copying_output_.GetErrno(); }
private:
class PROTOBUF_EXPORT CopyingFileOutputStream : public CopyingOutputStream {
public:
CopyingFileOutputStream(int file_descriptor);
~CopyingFileOutputStream() override;
bool Close();
void SetCloseOnDelete(bool value) { close_on_delete_ = value; }
int GetErrno() const { return errno_; }
// implements CopyingOutputStream --------------------------------
bool Write(const void* buffer, int size) override;
private:
// The file descriptor.
const int file_;
bool close_on_delete_;
bool is_closed_;
// The errno of the I/O error, if one has occurred. Otherwise, zero.
int errno_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingFileOutputStream);
};
CopyingFileOutputStream copying_output_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileOutputStream);
};
// ===================================================================
// A ZeroCopyInputStream which reads from a C++ istream.
//
// Note that for reading files (or anything represented by a file descriptor),
// FileInputStream is more efficient.
class PROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream {
public:
// Creates a stream that reads from the given C++ istream.
// If a block_size is given, it specifies the number of bytes that
// should be read and returned with each call to Next(). Otherwise,
// a reasonable default is used.
explicit IstreamInputStream(std::istream* stream, int block_size = -1);
// implements ZeroCopyInputStream ----------------------------------
bool Next(const void** data, int* size) override;
void BackUp(int count) override;
bool Skip(int count) override;
int64_t ByteCount() const override;
private:
class PROTOBUF_EXPORT CopyingIstreamInputStream : public CopyingInputStream {
public:
CopyingIstreamInputStream(std::istream* input);
~CopyingIstreamInputStream() override;
// implements CopyingInputStream ---------------------------------
int Read(void* buffer, int size) override;
// (We use the default implementation of Skip().)
private:
// The stream.
std::istream* input_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingIstreamInputStream);
};
CopyingIstreamInputStream copying_input_;
CopyingInputStreamAdaptor impl_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(IstreamInputStream);
};
// ===================================================================
// A ZeroCopyOutputStream which writes to a C++ ostream.
//
// Note that for writing files (or anything represented by a file descriptor),
// FileOutputStream is more efficient.
class PROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream {
public:
// Creates a stream that writes to the given C++ ostream.
// If a block_size is given, it specifies the size of the buffers
// that should be returned by Next(). Otherwise, a reasonable default
// is used.
explicit OstreamOutputStream(std::ostream* stream, int block_size = -1);
~OstreamOutputStream() override;
// implements ZeroCopyOutputStream ---------------------------------
bool Next(void** data, int* size) override;
void BackUp(int count) override;
int64_t ByteCount() const override;
private:
class PROTOBUF_EXPORT CopyingOstreamOutputStream
: public CopyingOutputStream {
public:
CopyingOstreamOutputStream(std::ostream* output);
~CopyingOstreamOutputStream() override;
// implements CopyingOutputStream --------------------------------
bool Write(const void* buffer, int size) override;
private:
// The stream.
std::ostream* output_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingOstreamOutputStream);
};
CopyingOstreamOutputStream copying_output_;
CopyingOutputStreamAdaptor impl_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OstreamOutputStream);
};
// ===================================================================
// A ZeroCopyInputStream which reads from several other streams in sequence.
// ConcatenatingInputStream is unable to distinguish between end-of-stream
// and read errors in the underlying streams, so it assumes any errors mean
// end-of-stream. So, if the underlying streams fail for any other reason,
// ConcatenatingInputStream may do odd things. It is suggested that you do
// not use ConcatenatingInputStream on streams that might produce read errors
// other than end-of-stream.
class PROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream {
public:
// All streams passed in as well as the array itself must remain valid
// until the ConcatenatingInputStream is destroyed.
ConcatenatingInputStream(ZeroCopyInputStream* const streams[], int count);
~ConcatenatingInputStream() override = default;
// implements ZeroCopyInputStream ----------------------------------
bool Next(const void** data, int* size) override;
void BackUp(int count) override;
bool Skip(int count) override;
int64_t ByteCount() const override;
private:
// As streams are retired, streams_ is incremented and count_ is
// decremented.
ZeroCopyInputStream* const* streams_;
int stream_count_;
int64 bytes_retired_; // Bytes read from previous streams.
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ConcatenatingInputStream);
};
// ===================================================================
} // namespace io
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__
| 12,750 | 37.875 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/io/zero_copy_stream_impl_lite.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains common implementations of the interfaces defined in
// zero_copy_stream.h which are included in the "lite" protobuf library.
// These implementations cover I/O on raw arrays and strings, as well as
// adaptors which make it easy to implement streams based on traditional
// streams. Of course, many users will probably want to write their own
// implementations of these interfaces specific to the particular I/O
// abstractions they prefer to use, but these should cover the most common
// cases.
#ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
#define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
#include <iosfwd>
#include <memory>
#include <string>
#include <google/protobuf/stubs/callback.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/stubs/stl_util.h>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
namespace io {
// ===================================================================
// A ZeroCopyInputStream backed by an in-memory array of bytes.
class PROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream {
public:
// Create an InputStream that returns the bytes pointed to by "data".
// "data" remains the property of the caller but must remain valid until
// the stream is destroyed. If a block_size is given, calls to Next()
// will return data blocks no larger than the given size. Otherwise, the
// first call to Next() returns the entire array. block_size is mainly
// useful for testing; in production you would probably never want to set
// it.
ArrayInputStream(const void* data, int size, int block_size = -1);
~ArrayInputStream() override = default;
// implements ZeroCopyInputStream ----------------------------------
bool Next(const void** data, int* size) override;
void BackUp(int count) override;
bool Skip(int count) override;
int64_t ByteCount() const override;
private:
const uint8* const data_; // The byte array.
const int size_; // Total size of the array.
const int block_size_; // How many bytes to return at a time.
int position_;
int last_returned_size_; // How many bytes we returned last time Next()
// was called (used for error checking only).
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayInputStream);
};
// ===================================================================
// A ZeroCopyOutputStream backed by an in-memory array of bytes.
class PROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream {
public:
// Create an OutputStream that writes to the bytes pointed to by "data".
// "data" remains the property of the caller but must remain valid until
// the stream is destroyed. If a block_size is given, calls to Next()
// will return data blocks no larger than the given size. Otherwise, the
// first call to Next() returns the entire array. block_size is mainly
// useful for testing; in production you would probably never want to set
// it.
ArrayOutputStream(void* data, int size, int block_size = -1);
~ArrayOutputStream() override = default;
// implements ZeroCopyOutputStream ---------------------------------
bool Next(void** data, int* size) override;
void BackUp(int count) override;
int64_t ByteCount() const override;
private:
uint8* const data_; // The byte array.
const int size_; // Total size of the array.
const int block_size_; // How many bytes to return at a time.
int position_;
int last_returned_size_; // How many bytes we returned last time Next()
// was called (used for error checking only).
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayOutputStream);
};
// ===================================================================
// A ZeroCopyOutputStream which appends bytes to a string.
class PROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream {
public:
// Create a StringOutputStream which appends bytes to the given string.
// The string remains property of the caller, but it is mutated in arbitrary
// ways and MUST NOT be accessed in any way until you're done with the
// stream. Either be sure there's no further usage, or (safest) destroy the
// stream before using the contents.
//
// Hint: If you call target->reserve(n) before creating the stream,
// the first call to Next() will return at least n bytes of buffer
// space.
explicit StringOutputStream(std::string* target);
~StringOutputStream() override = default;
// implements ZeroCopyOutputStream ---------------------------------
bool Next(void** data, int* size) override;
void BackUp(int count) override;
int64_t ByteCount() const override;
private:
static constexpr size_t kMinimumSize = 16;
std::string* target_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOutputStream);
};
// Note: There is no StringInputStream. Instead, just create an
// ArrayInputStream as follows:
// ArrayInputStream input(str.data(), str.size());
// ===================================================================
// A generic traditional input stream interface.
//
// Lots of traditional input streams (e.g. file descriptors, C stdio
// streams, and C++ iostreams) expose an interface where every read
// involves copying bytes into a buffer. If you want to take such an
// interface and make a ZeroCopyInputStream based on it, simply implement
// CopyingInputStream and then use CopyingInputStreamAdaptor.
//
// CopyingInputStream implementations should avoid buffering if possible.
// CopyingInputStreamAdaptor does its own buffering and will read data
// in large blocks.
class PROTOBUF_EXPORT CopyingInputStream {
public:
virtual ~CopyingInputStream() {}
// Reads up to "size" bytes into the given buffer. Returns the number of
// bytes read. Read() waits until at least one byte is available, or
// returns zero if no bytes will ever become available (EOF), or -1 if a
// permanent read error occurred.
virtual int Read(void* buffer, int size) = 0;
// Skips the next "count" bytes of input. Returns the number of bytes
// actually skipped. This will always be exactly equal to "count" unless
// EOF was reached or a permanent read error occurred.
//
// The default implementation just repeatedly calls Read() into a scratch
// buffer.
virtual int Skip(int count);
};
// A ZeroCopyInputStream which reads from a CopyingInputStream. This is
// useful for implementing ZeroCopyInputStreams that read from traditional
// streams. Note that this class is not really zero-copy.
//
// If you want to read from file descriptors or C++ istreams, this is
// already implemented for you: use FileInputStream or IstreamInputStream
// respectively.
class PROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream {
public:
// Creates a stream that reads from the given CopyingInputStream.
// If a block_size is given, it specifies the number of bytes that
// should be read and returned with each call to Next(). Otherwise,
// a reasonable default is used. The caller retains ownership of
// copying_stream unless SetOwnsCopyingStream(true) is called.
explicit CopyingInputStreamAdaptor(CopyingInputStream* copying_stream,
int block_size = -1);
~CopyingInputStreamAdaptor() override;
// Call SetOwnsCopyingStream(true) to tell the CopyingInputStreamAdaptor to
// delete the underlying CopyingInputStream when it is destroyed.
void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; }
// implements ZeroCopyInputStream ----------------------------------
bool Next(const void** data, int* size) override;
void BackUp(int count) override;
bool Skip(int count) override;
int64_t ByteCount() const override;
private:
// Insures that buffer_ is not NULL.
void AllocateBufferIfNeeded();
// Frees the buffer and resets buffer_used_.
void FreeBuffer();
// The underlying copying stream.
CopyingInputStream* copying_stream_;
bool owns_copying_stream_;
// True if we have seen a permanent error from the underlying stream.
bool failed_;
// The current position of copying_stream_, relative to the point where
// we started reading.
int64 position_;
// Data is read into this buffer. It may be NULL if no buffer is currently
// in use. Otherwise, it points to an array of size buffer_size_.
std::unique_ptr<uint8[]> buffer_;
const int buffer_size_;
// Number of valid bytes currently in the buffer (i.e. the size last
// returned by Next()). 0 <= buffer_used_ <= buffer_size_.
int buffer_used_;
// Number of bytes in the buffer which were backed up over by a call to
// BackUp(). These need to be returned again.
// 0 <= backup_bytes_ <= buffer_used_
int backup_bytes_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingInputStreamAdaptor);
};
// ===================================================================
// A generic traditional output stream interface.
//
// Lots of traditional output streams (e.g. file descriptors, C stdio
// streams, and C++ iostreams) expose an interface where every write
// involves copying bytes from a buffer. If you want to take such an
// interface and make a ZeroCopyOutputStream based on it, simply implement
// CopyingOutputStream and then use CopyingOutputStreamAdaptor.
//
// CopyingOutputStream implementations should avoid buffering if possible.
// CopyingOutputStreamAdaptor does its own buffering and will write data
// in large blocks.
class PROTOBUF_EXPORT CopyingOutputStream {
public:
virtual ~CopyingOutputStream() {}
// Writes "size" bytes from the given buffer to the output. Returns true
// if successful, false on a write error.
virtual bool Write(const void* buffer, int size) = 0;
};
// A ZeroCopyOutputStream which writes to a CopyingOutputStream. This is
// useful for implementing ZeroCopyOutputStreams that write to traditional
// streams. Note that this class is not really zero-copy.
//
// If you want to write to file descriptors or C++ ostreams, this is
// already implemented for you: use FileOutputStream or OstreamOutputStream
// respectively.
class PROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream {
public:
// Creates a stream that writes to the given Unix file descriptor.
// If a block_size is given, it specifies the size of the buffers
// that should be returned by Next(). Otherwise, a reasonable default
// is used.
explicit CopyingOutputStreamAdaptor(CopyingOutputStream* copying_stream,
int block_size = -1);
~CopyingOutputStreamAdaptor() override;
// Writes all pending data to the underlying stream. Returns false if a
// write error occurred on the underlying stream. (The underlying
// stream itself is not necessarily flushed.)
bool Flush();
// Call SetOwnsCopyingStream(true) to tell the CopyingOutputStreamAdaptor to
// delete the underlying CopyingOutputStream when it is destroyed.
void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; }
// implements ZeroCopyOutputStream ---------------------------------
bool Next(void** data, int* size) override;
void BackUp(int count) override;
int64_t ByteCount() const override;
bool WriteAliasedRaw(const void* data, int size) override;
bool AllowsAliasing() const override { return true; }
private:
// Write the current buffer, if it is present.
bool WriteBuffer();
// Insures that buffer_ is not NULL.
void AllocateBufferIfNeeded();
// Frees the buffer.
void FreeBuffer();
// The underlying copying stream.
CopyingOutputStream* copying_stream_;
bool owns_copying_stream_;
// True if we have seen a permanent error from the underlying stream.
bool failed_;
// The current position of copying_stream_, relative to the point where
// we started writing.
int64 position_;
// Data is written from this buffer. It may be NULL if no buffer is
// currently in use. Otherwise, it points to an array of size buffer_size_.
std::unique_ptr<uint8[]> buffer_;
const int buffer_size_;
// Number of valid bytes currently in the buffer (i.e. the size last
// returned by Next()). When BackUp() is called, we just reduce this.
// 0 <= buffer_used_ <= buffer_size_.
int buffer_used_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingOutputStreamAdaptor);
};
// ===================================================================
// A ZeroCopyInputStream which wraps some other stream and limits it to
// a particular byte count.
class PROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream {
public:
LimitingInputStream(ZeroCopyInputStream* input, int64 limit);
~LimitingInputStream() override;
// implements ZeroCopyInputStream ----------------------------------
bool Next(const void** data, int* size) override;
void BackUp(int count) override;
bool Skip(int count) override;
int64_t ByteCount() const override;
private:
ZeroCopyInputStream* input_;
int64 limit_; // Decreases as we go, becomes negative if we overshoot.
int64 prior_bytes_read_; // Bytes read on underlying stream at construction
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(LimitingInputStream);
};
// ===================================================================
// mutable_string_data() and as_string_data() are workarounds to improve
// the performance of writing new data to an existing string. Unfortunately
// the methods provided by the string class are suboptimal, and using memcpy()
// is mildly annoying because it requires its pointer args to be non-NULL even
// if we ask it to copy 0 bytes. Furthermore, string_as_array() has the
// property that it always returns NULL if its arg is the empty string, exactly
// what we want to avoid if we're using it in conjunction with memcpy()!
// With C++11, the desired memcpy() boils down to memcpy(..., &(*s)[0], size),
// where s is a string*. Without C++11, &(*s)[0] is not guaranteed to be safe,
// so we use string_as_array(), and live with the extra logic that tests whether
// *s is empty.
// Return a pointer to mutable characters underlying the given string. The
// return value is valid until the next time the string is resized. We
// trust the caller to treat the return value as an array of length s->size().
inline char* mutable_string_data(std::string* s) {
// This should be simpler & faster than string_as_array() because the latter
// is guaranteed to return NULL when *s is empty, so it has to check for that.
return &(*s)[0];
}
// as_string_data(s) is equivalent to
// ({ char* p = mutable_string_data(s); make_pair(p, p != NULL); })
// Sometimes it's faster: in some scenarios p cannot be NULL, and then the
// code can avoid that check.
inline std::pair<char*, bool> as_string_data(std::string* s) {
char* p = mutable_string_data(s);
return std::make_pair(p, true);
}
} // namespace io
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__
| 16,950 | 40.444988 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/bytestream.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file declares the ByteSink and ByteSource abstract interfaces. These
// interfaces represent objects that consume (ByteSink) or produce (ByteSource)
// a sequence of bytes. Using these abstract interfaces in your APIs can help
// make your code work with a variety of input and output types.
//
// This file also declares the following commonly used implementations of these
// interfaces.
//
// ByteSink:
// UncheckedArrayByteSink Writes to an array, without bounds checking
// CheckedArrayByteSink Writes to an array, with bounds checking
// GrowingArrayByteSink Allocates and writes to a growable buffer
// StringByteSink Writes to an STL string
// NullByteSink Consumes a never-ending stream of bytes
//
// ByteSource:
// ArrayByteSource Reads from an array or string/StringPiece
// LimitedByteSource Limits the number of bytes read from an
#ifndef GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_
#define GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_
#include <stddef.h>
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stringpiece.h>
#include <google/protobuf/port_def.inc>
class CordByteSink;
namespace google {
namespace protobuf {
namespace strings {
// An abstract interface for an object that consumes a sequence of bytes. This
// interface offers a way to append data as well as a Flush() function.
//
// Example:
//
// string my_data;
// ...
// ByteSink* sink = ...
// sink->Append(my_data.data(), my_data.size());
// sink->Flush();
//
class PROTOBUF_EXPORT ByteSink {
public:
ByteSink() {}
virtual ~ByteSink() {}
// Appends the "n" bytes starting at "bytes".
virtual void Append(const char* bytes, size_t n) = 0;
// Flushes internal buffers. The default implementation does nothing. ByteSink
// subclasses may use internal buffers that require calling Flush() at the end
// of the stream.
virtual void Flush();
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSink);
};
// An abstract interface for an object that produces a fixed-size sequence of
// bytes.
//
// Example:
//
// ByteSource* source = ...
// while (source->Available() > 0) {
// StringPiece data = source->Peek();
// ... do something with "data" ...
// source->Skip(data.length());
// }
//
class PROTOBUF_EXPORT ByteSource {
public:
ByteSource() {}
virtual ~ByteSource() {}
// Returns the number of bytes left to read from the source. Available()
// should decrease by N each time Skip(N) is called. Available() may not
// increase. Available() returning 0 indicates that the ByteSource is
// exhausted.
//
// Note: Size() may have been a more appropriate name as it's more
// indicative of the fixed-size nature of a ByteSource.
virtual size_t Available() const = 0;
// Returns a StringPiece of the next contiguous region of the source. Does not
// reposition the source. The returned region is empty iff Available() == 0.
//
// The returned region is valid until the next call to Skip() or until this
// object is destroyed, whichever occurs first.
//
// The length of the returned StringPiece will be <= Available().
virtual StringPiece Peek() = 0;
// Skips the next n bytes. Invalidates any StringPiece returned by a previous
// call to Peek().
//
// REQUIRES: Available() >= n
virtual void Skip(size_t n) = 0;
// Writes the next n bytes in this ByteSource to the given ByteSink, and
// advances this ByteSource past the copied bytes. The default implementation
// of this method just copies the bytes normally, but subclasses might
// override CopyTo to optimize certain cases.
//
// REQUIRES: Available() >= n
virtual void CopyTo(ByteSink* sink, size_t n);
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSource);
};
//
// Some commonly used implementations of ByteSink
//
// Implementation of ByteSink that writes to an unsized byte array. No
// bounds-checking is performed--it is the caller's responsibility to ensure
// that the destination array is large enough.
//
// Example:
//
// char buf[10];
// UncheckedArrayByteSink sink(buf);
// sink.Append("hi", 2); // OK
// sink.Append(data, 100); // WOOPS! Overflows buf[10].
//
class PROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink {
public:
explicit UncheckedArrayByteSink(char* dest) : dest_(dest) {}
virtual void Append(const char* data, size_t n) override;
// Returns the current output pointer so that a caller can see how many bytes
// were produced.
//
// Note: this method is not part of the ByteSink interface.
char* CurrentDestination() const { return dest_; }
private:
char* dest_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(UncheckedArrayByteSink);
};
// Implementation of ByteSink that writes to a sized byte array. This sink will
// not write more than "capacity" bytes to outbuf. Once "capacity" bytes are
// appended, subsequent bytes will be ignored and Overflowed() will return true.
// Overflowed() does not cause a runtime error (i.e., it does not CHECK fail).
//
// Example:
//
// char buf[10];
// CheckedArrayByteSink sink(buf, 10);
// sink.Append("hi", 2); // OK
// sink.Append(data, 100); // Will only write 8 more bytes
//
class PROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink {
public:
CheckedArrayByteSink(char* outbuf, size_t capacity);
virtual void Append(const char* bytes, size_t n) override;
// Returns the number of bytes actually written to the sink.
size_t NumberOfBytesWritten() const { return size_; }
// Returns true if any bytes were discarded, i.e., if there was an
// attempt to write more than 'capacity' bytes.
bool Overflowed() const { return overflowed_; }
private:
char* outbuf_;
const size_t capacity_;
size_t size_;
bool overflowed_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CheckedArrayByteSink);
};
// Implementation of ByteSink that allocates an internal buffer (a char array)
// and expands it as needed to accommodate appended data (similar to a string),
// and allows the caller to take ownership of the internal buffer via the
// GetBuffer() method. The buffer returned from GetBuffer() must be deleted by
// the caller with delete[]. GetBuffer() also sets the internal buffer to be
// empty, and subsequent appends to the sink will create a new buffer. The
// destructor will free the internal buffer if GetBuffer() was not called.
//
// Example:
//
// GrowingArrayByteSink sink(10);
// sink.Append("hi", 2);
// sink.Append(data, n);
// const char* buf = sink.GetBuffer(); // Ownership transferred
// delete[] buf;
//
class PROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink {
public:
explicit GrowingArrayByteSink(size_t estimated_size);
virtual ~GrowingArrayByteSink();
virtual void Append(const char* bytes, size_t n) override;
// Returns the allocated buffer, and sets nbytes to its size. The caller takes
// ownership of the buffer and must delete it with delete[].
char* GetBuffer(size_t* nbytes);
private:
void Expand(size_t amount);
void ShrinkToFit();
size_t capacity_;
char* buf_;
size_t size_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GrowingArrayByteSink);
};
// Implementation of ByteSink that appends to the given string.
// Existing contents of "dest" are not modified; new data is appended.
//
// Example:
//
// string dest = "Hello ";
// StringByteSink sink(&dest);
// sink.Append("World", 5);
// assert(dest == "Hello World");
//
class PROTOBUF_EXPORT StringByteSink : public ByteSink {
public:
explicit StringByteSink(std::string* dest) : dest_(dest) {}
virtual void Append(const char* data, size_t n) override;
private:
std::string* dest_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringByteSink);
};
// Implementation of ByteSink that discards all data.
//
// Example:
//
// NullByteSink sink;
// sink.Append(data, data.size()); // All data ignored.
//
class PROTOBUF_EXPORT NullByteSink : public ByteSink {
public:
NullByteSink() {}
void Append(const char* /*data*/, size_t /*n*/) override {}
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(NullByteSink);
};
//
// Some commonly used implementations of ByteSource
//
// Implementation of ByteSource that reads from a StringPiece.
//
// Example:
//
// string data = "Hello";
// ArrayByteSource source(data);
// assert(source.Available() == 5);
// assert(source.Peek() == "Hello");
//
class PROTOBUF_EXPORT ArrayByteSource : public ByteSource {
public:
explicit ArrayByteSource(StringPiece s) : input_(s) {}
virtual size_t Available() const override;
virtual StringPiece Peek() override;
virtual void Skip(size_t n) override;
private:
StringPiece input_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayByteSource);
};
// Implementation of ByteSource that wraps another ByteSource, limiting the
// number of bytes returned.
//
// The caller maintains ownership of the underlying source, and may not use the
// underlying source while using the LimitByteSource object. The underlying
// source's pointer is advanced by n bytes every time this LimitByteSource
// object is advanced by n.
//
// Example:
//
// string data = "Hello World";
// ArrayByteSource abs(data);
// assert(abs.Available() == data.size());
//
// LimitByteSource limit(abs, 5);
// assert(limit.Available() == 5);
// assert(limit.Peek() == "Hello");
//
class PROTOBUF_EXPORT LimitByteSource : public ByteSource {
public:
// Returns at most "limit" bytes from "source".
LimitByteSource(ByteSource* source, size_t limit);
virtual size_t Available() const override;
virtual StringPiece Peek() override;
virtual void Skip(size_t n) override;
// We override CopyTo so that we can forward to the underlying source, in
// case it has an efficient implementation of CopyTo.
virtual void CopyTo(ByteSink* sink, size_t n) override;
private:
ByteSource* source_;
size_t limit_;
};
} // namespace strings
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_
| 11,769 | 32.4375 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/callback.h | #ifndef GOOGLE_PROTOBUF_STUBS_CALLBACK_H_
#define GOOGLE_PROTOBUF_STUBS_CALLBACK_H_
#include <type_traits>
#include <google/protobuf/stubs/macros.h>
#include <google/protobuf/port_def.inc>
// ===================================================================
// emulates google3/base/callback.h
namespace google {
namespace protobuf {
// Abstract interface for a callback. When calling an RPC, you must provide
// a Closure to call when the procedure completes. See the Service interface
// in service.h.
//
// To automatically construct a Closure which calls a particular function or
// method with a particular set of parameters, use the NewCallback() function.
// Example:
// void FooDone(const FooResponse* response) {
// ...
// }
//
// void CallFoo() {
// ...
// // When done, call FooDone() and pass it a pointer to the response.
// Closure* callback = NewCallback(&FooDone, response);
// // Make the call.
// service->Foo(controller, request, response, callback);
// }
//
// Example that calls a method:
// class Handler {
// public:
// ...
//
// void FooDone(const FooResponse* response) {
// ...
// }
//
// void CallFoo() {
// ...
// // When done, call FooDone() and pass it a pointer to the response.
// Closure* callback = NewCallback(this, &Handler::FooDone, response);
// // Make the call.
// service->Foo(controller, request, response, callback);
// }
// };
//
// Currently NewCallback() supports binding zero, one, or two arguments.
//
// Callbacks created with NewCallback() automatically delete themselves when
// executed. They should be used when a callback is to be called exactly
// once (usually the case with RPC callbacks). If a callback may be called
// a different number of times (including zero), create it with
// NewPermanentCallback() instead. You are then responsible for deleting the
// callback (using the "delete" keyword as normal).
//
// Note that NewCallback() is a bit touchy regarding argument types. Generally,
// the values you provide for the parameter bindings must exactly match the
// types accepted by the callback function. For example:
// void Foo(std::string s);
// NewCallback(&Foo, "foo"); // WON'T WORK: const char* != string
// NewCallback(&Foo, std::string("foo")); // WORKS
// Also note that the arguments cannot be references:
// void Foo(const std::string& s);
// std::string my_str;
// NewCallback(&Foo, my_str); // WON'T WORK: Can't use references.
// However, correctly-typed pointers will work just fine.
class PROTOBUF_EXPORT Closure {
public:
Closure() {}
virtual ~Closure();
virtual void Run() = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Closure);
};
template<typename R>
class ResultCallback {
public:
ResultCallback() {}
virtual ~ResultCallback() {}
virtual R Run() = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ResultCallback);
};
template <typename R, typename A1>
class PROTOBUF_EXPORT ResultCallback1 {
public:
ResultCallback1() {}
virtual ~ResultCallback1() {}
virtual R Run(A1) = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ResultCallback1);
};
template <typename R, typename A1, typename A2>
class PROTOBUF_EXPORT ResultCallback2 {
public:
ResultCallback2() {}
virtual ~ResultCallback2() {}
virtual R Run(A1,A2) = 0;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ResultCallback2);
};
namespace internal {
class PROTOBUF_EXPORT FunctionClosure0 : public Closure {
public:
typedef void (*FunctionType)();
FunctionClosure0(FunctionType function, bool self_deleting)
: function_(function), self_deleting_(self_deleting) {}
~FunctionClosure0();
void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
function_();
if (needs_delete) delete this;
}
private:
FunctionType function_;
bool self_deleting_;
};
template <typename Class>
class MethodClosure0 : public Closure {
public:
typedef void (Class::*MethodType)();
MethodClosure0(Class* object, MethodType method, bool self_deleting)
: object_(object), method_(method), self_deleting_(self_deleting) {}
~MethodClosure0() {}
void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
(object_->*method_)();
if (needs_delete) delete this;
}
private:
Class* object_;
MethodType method_;
bool self_deleting_;
};
template <typename Arg1>
class FunctionClosure1 : public Closure {
public:
typedef void (*FunctionType)(Arg1 arg1);
FunctionClosure1(FunctionType function, bool self_deleting,
Arg1 arg1)
: function_(function), self_deleting_(self_deleting),
arg1_(arg1) {}
~FunctionClosure1() {}
void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
function_(arg1_);
if (needs_delete) delete this;
}
private:
FunctionType function_;
bool self_deleting_;
Arg1 arg1_;
};
template <typename Class, typename Arg1>
class MethodClosure1 : public Closure {
public:
typedef void (Class::*MethodType)(Arg1 arg1);
MethodClosure1(Class* object, MethodType method, bool self_deleting,
Arg1 arg1)
: object_(object), method_(method), self_deleting_(self_deleting),
arg1_(arg1) {}
~MethodClosure1() {}
void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
(object_->*method_)(arg1_);
if (needs_delete) delete this;
}
private:
Class* object_;
MethodType method_;
bool self_deleting_;
Arg1 arg1_;
};
template <typename Arg1, typename Arg2>
class FunctionClosure2 : public Closure {
public:
typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2);
FunctionClosure2(FunctionType function, bool self_deleting,
Arg1 arg1, Arg2 arg2)
: function_(function), self_deleting_(self_deleting),
arg1_(arg1), arg2_(arg2) {}
~FunctionClosure2() {}
void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
function_(arg1_, arg2_);
if (needs_delete) delete this;
}
private:
FunctionType function_;
bool self_deleting_;
Arg1 arg1_;
Arg2 arg2_;
};
template <typename Class, typename Arg1, typename Arg2>
class MethodClosure2 : public Closure {
public:
typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2);
MethodClosure2(Class* object, MethodType method, bool self_deleting,
Arg1 arg1, Arg2 arg2)
: object_(object), method_(method), self_deleting_(self_deleting),
arg1_(arg1), arg2_(arg2) {}
~MethodClosure2() {}
void Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
(object_->*method_)(arg1_, arg2_);
if (needs_delete) delete this;
}
private:
Class* object_;
MethodType method_;
bool self_deleting_;
Arg1 arg1_;
Arg2 arg2_;
};
template<typename R>
class FunctionResultCallback_0_0 : public ResultCallback<R> {
public:
typedef R (*FunctionType)();
FunctionResultCallback_0_0(FunctionType function, bool self_deleting)
: function_(function), self_deleting_(self_deleting) {}
~FunctionResultCallback_0_0() {}
R Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
R result = function_();
if (needs_delete) delete this;
return result;
}
private:
FunctionType function_;
bool self_deleting_;
};
template<typename R, typename P1>
class FunctionResultCallback_1_0 : public ResultCallback<R> {
public:
typedef R (*FunctionType)(P1);
FunctionResultCallback_1_0(FunctionType function, bool self_deleting,
P1 p1)
: function_(function), self_deleting_(self_deleting), p1_(p1) {}
~FunctionResultCallback_1_0() {}
R Run() override {
bool needs_delete = self_deleting_; // read in case callback deletes
R result = function_(p1_);
if (needs_delete) delete this;
return result;
}
private:
FunctionType function_;
bool self_deleting_;
P1 p1_;
};
template<typename R, typename Arg1>
class FunctionResultCallback_0_1 : public ResultCallback1<R, Arg1> {
public:
typedef R (*FunctionType)(Arg1 arg1);
FunctionResultCallback_0_1(FunctionType function, bool self_deleting)
: function_(function), self_deleting_(self_deleting) {}
~FunctionResultCallback_0_1() {}
R Run(Arg1 a1) override {
bool needs_delete = self_deleting_; // read in case callback deletes
R result = function_(a1);
if (needs_delete) delete this;
return result;
}
private:
FunctionType function_;
bool self_deleting_;
};
template<typename R, typename P1, typename A1>
class FunctionResultCallback_1_1 : public ResultCallback1<R, A1> {
public:
typedef R (*FunctionType)(P1, A1);
FunctionResultCallback_1_1(FunctionType function, bool self_deleting,
P1 p1)
: function_(function), self_deleting_(self_deleting), p1_(p1) {}
~FunctionResultCallback_1_1() {}
R Run(A1 a1) override {
bool needs_delete = self_deleting_; // read in case callback deletes
R result = function_(p1_, a1);
if (needs_delete) delete this;
return result;
}
private:
FunctionType function_;
bool self_deleting_;
P1 p1_;
};
template <typename T>
struct InternalConstRef {
typedef typename std::remove_reference<T>::type base_type;
typedef const base_type& type;
};
template<typename R, typename T>
class MethodResultCallback_0_0 : public ResultCallback<R> {
public:
typedef R (T::*MethodType)();
MethodResultCallback_0_0(T* object, MethodType method, bool self_deleting)
: object_(object),
method_(method),
self_deleting_(self_deleting) {}
~MethodResultCallback_0_0() {}
R Run() {
bool needs_delete = self_deleting_;
R result = (object_->*method_)();
if (needs_delete) delete this;
return result;
}
private:
T* object_;
MethodType method_;
bool self_deleting_;
};
template <typename R, typename T, typename P1, typename P2, typename P3,
typename P4, typename P5, typename P6, typename A1, typename A2>
class MethodResultCallback_6_2 : public ResultCallback2<R, A1, A2> {
public:
typedef R (T::*MethodType)(P1, P2, P3, P4, P5, P6, A1, A2);
MethodResultCallback_6_2(T* object, MethodType method, bool self_deleting,
P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6)
: object_(object),
method_(method),
self_deleting_(self_deleting),
p1_(p1),
p2_(p2),
p3_(p3),
p4_(p4),
p5_(p5),
p6_(p6) {}
~MethodResultCallback_6_2() {}
R Run(A1 a1, A2 a2) override {
bool needs_delete = self_deleting_;
R result = (object_->*method_)(p1_, p2_, p3_, p4_, p5_, p6_, a1, a2);
if (needs_delete) delete this;
return result;
}
private:
T* object_;
MethodType method_;
bool self_deleting_;
typename std::remove_reference<P1>::type p1_;
typename std::remove_reference<P2>::type p2_;
typename std::remove_reference<P3>::type p3_;
typename std::remove_reference<P4>::type p4_;
typename std::remove_reference<P5>::type p5_;
typename std::remove_reference<P6>::type p6_;
};
} // namespace internal
// See Closure.
inline Closure* NewCallback(void (*function)()) {
return new internal::FunctionClosure0(function, true);
}
// See Closure.
inline Closure* NewPermanentCallback(void (*function)()) {
return new internal::FunctionClosure0(function, false);
}
// See Closure.
template <typename Class>
inline Closure* NewCallback(Class* object, void (Class::*method)()) {
return new internal::MethodClosure0<Class>(object, method, true);
}
// See Closure.
template <typename Class>
inline Closure* NewPermanentCallback(Class* object, void (Class::*method)()) {
return new internal::MethodClosure0<Class>(object, method, false);
}
// See Closure.
template <typename Arg1>
inline Closure* NewCallback(void (*function)(Arg1),
Arg1 arg1) {
return new internal::FunctionClosure1<Arg1>(function, true, arg1);
}
// See Closure.
template <typename Arg1>
inline Closure* NewPermanentCallback(void (*function)(Arg1),
Arg1 arg1) {
return new internal::FunctionClosure1<Arg1>(function, false, arg1);
}
// See Closure.
template <typename Class, typename Arg1>
inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1),
Arg1 arg1) {
return new internal::MethodClosure1<Class, Arg1>(object, method, true, arg1);
}
// See Closure.
template <typename Class, typename Arg1>
inline Closure* NewPermanentCallback(Class* object, void (Class::*method)(Arg1),
Arg1 arg1) {
return new internal::MethodClosure1<Class, Arg1>(object, method, false, arg1);
}
// See Closure.
template <typename Arg1, typename Arg2>
inline Closure* NewCallback(void (*function)(Arg1, Arg2),
Arg1 arg1, Arg2 arg2) {
return new internal::FunctionClosure2<Arg1, Arg2>(
function, true, arg1, arg2);
}
// See Closure.
template <typename Arg1, typename Arg2>
inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2),
Arg1 arg1, Arg2 arg2) {
return new internal::FunctionClosure2<Arg1, Arg2>(
function, false, arg1, arg2);
}
// See Closure.
template <typename Class, typename Arg1, typename Arg2>
inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1, Arg2),
Arg1 arg1, Arg2 arg2) {
return new internal::MethodClosure2<Class, Arg1, Arg2>(
object, method, true, arg1, arg2);
}
// See Closure.
template <typename Class, typename Arg1, typename Arg2>
inline Closure* NewPermanentCallback(
Class* object, void (Class::*method)(Arg1, Arg2),
Arg1 arg1, Arg2 arg2) {
return new internal::MethodClosure2<Class, Arg1, Arg2>(
object, method, false, arg1, arg2);
}
// See ResultCallback
template<typename R>
inline ResultCallback<R>* NewCallback(R (*function)()) {
return new internal::FunctionResultCallback_0_0<R>(function, true);
}
// See ResultCallback
template<typename R>
inline ResultCallback<R>* NewPermanentCallback(R (*function)()) {
return new internal::FunctionResultCallback_0_0<R>(function, false);
}
// See ResultCallback
template<typename R, typename P1>
inline ResultCallback<R>* NewCallback(R (*function)(P1), P1 p1) {
return new internal::FunctionResultCallback_1_0<R, P1>(
function, true, p1);
}
// See ResultCallback
template<typename R, typename P1>
inline ResultCallback<R>* NewPermanentCallback(
R (*function)(P1), P1 p1) {
return new internal::FunctionResultCallback_1_0<R, P1>(
function, false, p1);
}
// See ResultCallback1
template<typename R, typename A1>
inline ResultCallback1<R, A1>* NewCallback(R (*function)(A1)) {
return new internal::FunctionResultCallback_0_1<R, A1>(function, true);
}
// See ResultCallback1
template<typename R, typename A1>
inline ResultCallback1<R, A1>* NewPermanentCallback(R (*function)(A1)) {
return new internal::FunctionResultCallback_0_1<R, A1>(function, false);
}
// See ResultCallback1
template<typename R, typename P1, typename A1>
inline ResultCallback1<R, A1>* NewCallback(R (*function)(P1, A1), P1 p1) {
return new internal::FunctionResultCallback_1_1<R, P1, A1>(
function, true, p1);
}
// See ResultCallback1
template<typename R, typename P1, typename A1>
inline ResultCallback1<R, A1>* NewPermanentCallback(
R (*function)(P1, A1), P1 p1) {
return new internal::FunctionResultCallback_1_1<R, P1, A1>(
function, false, p1);
}
// See MethodResultCallback_0_0
template <typename R, typename T1, typename T2>
inline ResultCallback<R>* NewPermanentCallback(
T1* object, R (T2::*function)()) {
return new internal::MethodResultCallback_0_0<R, T1>(object, function, false);
}
// See MethodResultCallback_6_2
template <typename R, typename T, typename P1, typename P2, typename P3,
typename P4, typename P5, typename P6, typename A1, typename A2>
inline ResultCallback2<R, A1, A2>* NewPermanentCallback(
T* object, R (T::*function)(P1, P2, P3, P4, P5, P6, A1, A2),
typename internal::InternalConstRef<P1>::type p1,
typename internal::InternalConstRef<P2>::type p2,
typename internal::InternalConstRef<P3>::type p3,
typename internal::InternalConstRef<P4>::type p4,
typename internal::InternalConstRef<P5>::type p5,
typename internal::InternalConstRef<P6>::type p6) {
return new internal::MethodResultCallback_6_2<R, T, P1, P2, P3, P4, P5, P6,
A1, A2>(object, function, false,
p1, p2, p3, p4, p5, p6);
}
// A function which does nothing. Useful for creating no-op callbacks, e.g.:
// Closure* nothing = NewCallback(&DoNothing);
void PROTOBUF_EXPORT DoNothing();
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_STUBS_CALLBACK_H_
| 17,098 | 28.27911 | 80 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/casts.h | // Protocol Buffers - Google's data interchange format
// Copyright 2014 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_CASTS_H__
#define GOOGLE_PROTOBUF_CASTS_H__
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/port_def.inc>
#include <type_traits>
namespace google {
namespace protobuf {
namespace internal {
// Use implicit_cast as a safe version of static_cast or const_cast
// for upcasting in the type hierarchy (i.e. casting a pointer to Foo
// to a pointer to SuperclassOfFoo or casting a pointer to Foo to
// a const pointer to Foo).
// When you use implicit_cast, the compiler checks that the cast is safe.
// Such explicit implicit_casts are necessary in surprisingly many
// situations where C++ demands an exact type match instead of an
// argument type convertible to a target type.
//
// The From type can be inferred, so the preferred syntax for using
// implicit_cast is the same as for static_cast etc.:
//
// implicit_cast<ToType>(expr)
//
// implicit_cast would have been part of the C++ standard library,
// but the proposal was submitted too late. It will probably make
// its way into the language in the future.
template<typename To, typename From>
inline To implicit_cast(From const &f) {
return f;
}
// When you upcast (that is, cast a pointer from type Foo to type
// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts
// always succeed. When you downcast (that is, cast a pointer from
// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
// how do you know the pointer is really of type SubclassOfFoo? It
// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
// when you downcast, you should use this macro. In debug mode, we
// use dynamic_cast<> to double-check the downcast is legal (we die
// if it's not). In normal mode, we do the efficient static_cast<>
// instead. Thus, it's important to test in debug mode to make sure
// the cast is legal!
// This is the only place in the code we should use dynamic_cast<>.
// In particular, you SHOULDN'T be using dynamic_cast<> in order to
// do RTTI (eg code like this:
// if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
// if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
// You should design the code some other way not to need this.
template<typename To, typename From> // use like this: down_cast<T*>(foo);
inline To down_cast(From* f) { // so we only accept pointers
// Ensures that To is a sub-type of From *. This test is here only
// for compile-time type checking, and has no overhead in an
// optimized build at run-time, as it will be optimized away
// completely.
if (false) {
implicit_cast<From*, To>(0);
}
#if !defined(NDEBUG) && PROTOBUF_RTTI
assert(f == nullptr || dynamic_cast<To>(f) != nullptr); // RTTI: debug mode only!
#endif
return static_cast<To>(f);
}
template<typename To, typename From> // use like this: down_cast<T&>(foo);
inline To down_cast(From& f) {
typedef typename std::remove_reference<To>::type* ToAsPointer;
// Ensures that To is a sub-type of From *. This test is here only
// for compile-time type checking, and has no overhead in an
// optimized build at run-time, as it will be optimized away
// completely.
if (false) {
implicit_cast<From*, ToAsPointer>(0);
}
#if !defined(NDEBUG) && PROTOBUF_RTTI
// RTTI: debug mode only!
assert(dynamic_cast<ToAsPointer>(&f) != nullptr);
#endif
return *static_cast<ToAsPointer>(&f);
}
template<typename To, typename From>
inline To bit_cast(const From& from) {
GOOGLE_COMPILE_ASSERT(sizeof(From) == sizeof(To),
bit_cast_with_different_sizes);
To dest;
memcpy(&dest, &from, sizeof(dest));
return dest;
}
} // namespace internal
// We made these internal so that they would show up as such in the docs,
// but we don't want to stick "internal::" in front of them everywhere.
using internal::implicit_cast;
using internal::down_cast;
using internal::bit_cast;
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_CASTS_H__
| 5,733 | 39.957143 | 84 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/hash.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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: [email protected] (Kenton Varda)
#ifndef GOOGLE_PROTOBUF_STUBS_HASH_H__
#define GOOGLE_PROTOBUF_STUBS_HASH_H__
#include <cstring>
#include <string>
#include <unordered_map>
#include <unordered_set>
# define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_START \
namespace google { \
namespace protobuf {
# define GOOGLE_PROTOBUF_HASH_NAMESPACE_DECLARATION_END }}
namespace google {
namespace protobuf {
template <typename Key>
struct hash : public std::hash<Key> {};
template <typename Key>
struct hash<const Key*> {
inline size_t operator()(const Key* key) const {
return reinterpret_cast<size_t>(key);
}
};
// Unlike the old SGI version, the TR1 "hash" does not special-case char*. So,
// we go ahead and provide our own implementation.
template <>
struct hash<const char*> {
inline size_t operator()(const char* str) const {
size_t result = 0;
for (; *str != '\0'; str++) {
result = 5 * result + static_cast<size_t>(*str);
}
return result;
}
};
template<>
struct hash<bool> {
size_t operator()(bool x) const {
return static_cast<size_t>(x);
}
};
template <>
struct hash<std::string> {
inline size_t operator()(const std::string& key) const {
return hash<const char*>()(key.c_str());
}
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
inline bool operator()(const std::string& a, const std::string& b) const {
return a < b;
}
};
template <typename First, typename Second>
struct hash<std::pair<First, Second> > {
inline size_t operator()(const std::pair<First, Second>& key) const {
size_t first_hash = hash<First>()(key.first);
size_t second_hash = hash<Second>()(key.second);
// FIXME(kenton): What is the best way to compute this hash? I have
// no idea! This seems a bit better than an XOR.
return first_hash * ((1 << 16) - 1) + second_hash;
}
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
inline bool operator()(const std::pair<First, Second>& a,
const std::pair<First, Second>& b) const {
return a < b;
}
};
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_STUBS_HASH_H__
| 3,911 | 33.017391 | 79 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/int128.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_STUBS_INT128_H_
#define GOOGLE_PROTOBUF_STUBS_INT128_H_
#include <google/protobuf/stubs/common.h>
#include <iosfwd>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
struct uint128_pod;
// TODO(xiaofeng): Define GOOGLE_PROTOBUF_HAS_CONSTEXPR when constexpr is
// available.
#ifdef GOOGLE_PROTOBUF_HAS_CONSTEXPR
# define UINT128_CONSTEXPR constexpr
#else
# define UINT128_CONSTEXPR
#endif
// An unsigned 128-bit integer type. Thread-compatible.
class PROTOBUF_EXPORT uint128 {
public:
UINT128_CONSTEXPR uint128(); // Sets to 0, but don't trust on this behavior.
UINT128_CONSTEXPR uint128(uint64 top, uint64 bottom);
#ifndef SWIG
UINT128_CONSTEXPR uint128(int bottom);
UINT128_CONSTEXPR uint128(uint32 bottom); // Top 96 bits = 0
#endif
UINT128_CONSTEXPR uint128(uint64 bottom); // hi_ = 0
UINT128_CONSTEXPR uint128(const uint128_pod &val);
// Trivial copy constructor, assignment operator and destructor.
void Initialize(uint64 top, uint64 bottom);
// Arithmetic operators.
uint128& operator+=(const uint128& b);
uint128& operator-=(const uint128& b);
uint128& operator*=(const uint128& b);
// Long division/modulo for uint128.
uint128& operator/=(const uint128& b);
uint128& operator%=(const uint128& b);
uint128 operator++(int);
uint128 operator--(int);
uint128& operator<<=(int);
uint128& operator>>=(int);
uint128& operator&=(const uint128& b);
uint128& operator|=(const uint128& b);
uint128& operator^=(const uint128& b);
uint128& operator++();
uint128& operator--();
friend uint64 Uint128Low64(const uint128& v);
friend uint64 Uint128High64(const uint128& v);
// We add "std::" to avoid including all of port.h.
PROTOBUF_EXPORT friend std::ostream& operator<<(std::ostream& o,
const uint128& b);
private:
static void DivModImpl(uint128 dividend, uint128 divisor,
uint128* quotient_ret, uint128* remainder_ret);
// Little-endian memory order optimizations can benefit from
// having lo_ first, hi_ last.
// See util/endian/endian.h and Load128/Store128 for storing a uint128.
uint64 lo_;
uint64 hi_;
// Not implemented, just declared for catching automatic type conversions.
uint128(uint8);
uint128(uint16);
uint128(float v);
uint128(double v);
};
// This is a POD form of uint128 which can be used for static variables which
// need to be operated on as uint128.
struct uint128_pod {
// Note: The ordering of fields is different than 'class uint128' but the
// same as its 2-arg constructor. This enables more obvious initialization
// of static instances, which is the primary reason for this struct in the
// first place. This does not seem to defeat any optimizations wrt
// operations involving this struct.
uint64 hi;
uint64 lo;
};
PROTOBUF_EXPORT extern const uint128_pod kuint128max;
// allow uint128 to be logged
PROTOBUF_EXPORT extern std::ostream& operator<<(std::ostream& o,
const uint128& b);
// Methods to access low and high pieces of 128-bit value.
// Defined externally from uint128 to facilitate conversion
// to native 128-bit types when compilers support them.
inline uint64 Uint128Low64(const uint128& v) { return v.lo_; }
inline uint64 Uint128High64(const uint128& v) { return v.hi_; }
// TODO: perhaps it would be nice to have int128, a signed 128-bit type?
// --------------------------------------------------------------------------
// Implementation details follow
// --------------------------------------------------------------------------
inline bool operator==(const uint128& lhs, const uint128& rhs) {
return (Uint128Low64(lhs) == Uint128Low64(rhs) &&
Uint128High64(lhs) == Uint128High64(rhs));
}
inline bool operator!=(const uint128& lhs, const uint128& rhs) {
return !(lhs == rhs);
}
inline UINT128_CONSTEXPR uint128::uint128() : lo_(0), hi_(0) {}
inline UINT128_CONSTEXPR uint128::uint128(uint64 top, uint64 bottom)
: lo_(bottom), hi_(top) {}
inline UINT128_CONSTEXPR uint128::uint128(const uint128_pod& v)
: lo_(v.lo), hi_(v.hi) {}
inline UINT128_CONSTEXPR uint128::uint128(uint64 bottom)
: lo_(bottom), hi_(0) {}
#ifndef SWIG
inline UINT128_CONSTEXPR uint128::uint128(uint32 bottom)
: lo_(bottom), hi_(0) {}
inline UINT128_CONSTEXPR uint128::uint128(int bottom)
: lo_(bottom), hi_(static_cast<int64>((bottom < 0) ? -1 : 0)) {}
#endif
#undef UINT128_CONSTEXPR
inline void uint128::Initialize(uint64 top, uint64 bottom) {
hi_ = top;
lo_ = bottom;
}
// Comparison operators.
#define CMP128(op) \
inline bool operator op(const uint128& lhs, const uint128& rhs) { \
return (Uint128High64(lhs) == Uint128High64(rhs)) ? \
(Uint128Low64(lhs) op Uint128Low64(rhs)) : \
(Uint128High64(lhs) op Uint128High64(rhs)); \
}
CMP128(<)
CMP128(>)
CMP128(>=)
CMP128(<=)
#undef CMP128
// Unary operators
inline uint128 operator-(const uint128& val) {
const uint64 hi_flip = ~Uint128High64(val);
const uint64 lo_flip = ~Uint128Low64(val);
const uint64 lo_add = lo_flip + 1;
if (lo_add < lo_flip) {
return uint128(hi_flip + 1, lo_add);
}
return uint128(hi_flip, lo_add);
}
inline bool operator!(const uint128& val) {
return !Uint128High64(val) && !Uint128Low64(val);
}
// Logical operators.
inline uint128 operator~(const uint128& val) {
return uint128(~Uint128High64(val), ~Uint128Low64(val));
}
#define LOGIC128(op) \
inline uint128 operator op(const uint128& lhs, const uint128& rhs) { \
return uint128(Uint128High64(lhs) op Uint128High64(rhs), \
Uint128Low64(lhs) op Uint128Low64(rhs)); \
}
LOGIC128(|)
LOGIC128(&)
LOGIC128(^)
#undef LOGIC128
#define LOGICASSIGN128(op) \
inline uint128& uint128::operator op(const uint128& other) { \
hi_ op other.hi_; \
lo_ op other.lo_; \
return *this; \
}
LOGICASSIGN128(|=)
LOGICASSIGN128(&=)
LOGICASSIGN128(^=)
#undef LOGICASSIGN128
// Shift operators.
inline uint128 operator<<(const uint128& val, int amount) {
// uint64 shifts of >= 64 are undefined, so we will need some special-casing.
if (amount < 64) {
if (amount == 0) {
return val;
}
uint64 new_hi = (Uint128High64(val) << amount) |
(Uint128Low64(val) >> (64 - amount));
uint64 new_lo = Uint128Low64(val) << amount;
return uint128(new_hi, new_lo);
} else if (amount < 128) {
return uint128(Uint128Low64(val) << (amount - 64), 0);
} else {
return uint128(0, 0);
}
}
inline uint128 operator>>(const uint128& val, int amount) {
// uint64 shifts of >= 64 are undefined, so we will need some special-casing.
if (amount < 64) {
if (amount == 0) {
return val;
}
uint64 new_hi = Uint128High64(val) >> amount;
uint64 new_lo = (Uint128Low64(val) >> amount) |
(Uint128High64(val) << (64 - amount));
return uint128(new_hi, new_lo);
} else if (amount < 128) {
return uint128(0, Uint128High64(val) >> (amount - 64));
} else {
return uint128(0, 0);
}
}
inline uint128& uint128::operator<<=(int amount) {
// uint64 shifts of >= 64 are undefined, so we will need some special-casing.
if (amount < 64) {
if (amount != 0) {
hi_ = (hi_ << amount) | (lo_ >> (64 - amount));
lo_ = lo_ << amount;
}
} else if (amount < 128) {
hi_ = lo_ << (amount - 64);
lo_ = 0;
} else {
hi_ = 0;
lo_ = 0;
}
return *this;
}
inline uint128& uint128::operator>>=(int amount) {
// uint64 shifts of >= 64 are undefined, so we will need some special-casing.
if (amount < 64) {
if (amount != 0) {
lo_ = (lo_ >> amount) | (hi_ << (64 - amount));
hi_ = hi_ >> amount;
}
} else if (amount < 128) {
lo_ = hi_ >> (amount - 64);
hi_ = 0;
} else {
lo_ = 0;
hi_ = 0;
}
return *this;
}
inline uint128 operator+(const uint128& lhs, const uint128& rhs) {
return uint128(lhs) += rhs;
}
inline uint128 operator-(const uint128& lhs, const uint128& rhs) {
return uint128(lhs) -= rhs;
}
inline uint128 operator*(const uint128& lhs, const uint128& rhs) {
return uint128(lhs) *= rhs;
}
inline uint128 operator/(const uint128& lhs, const uint128& rhs) {
return uint128(lhs) /= rhs;
}
inline uint128 operator%(const uint128& lhs, const uint128& rhs) {
return uint128(lhs) %= rhs;
}
inline uint128& uint128::operator+=(const uint128& b) {
hi_ += b.hi_;
uint64 lolo = lo_ + b.lo_;
if (lolo < lo_)
++hi_;
lo_ = lolo;
return *this;
}
inline uint128& uint128::operator-=(const uint128& b) {
hi_ -= b.hi_;
if (b.lo_ > lo_)
--hi_;
lo_ -= b.lo_;
return *this;
}
inline uint128& uint128::operator*=(const uint128& b) {
uint64 a96 = hi_ >> 32;
uint64 a64 = hi_ & 0xffffffffu;
uint64 a32 = lo_ >> 32;
uint64 a00 = lo_ & 0xffffffffu;
uint64 b96 = b.hi_ >> 32;
uint64 b64 = b.hi_ & 0xffffffffu;
uint64 b32 = b.lo_ >> 32;
uint64 b00 = b.lo_ & 0xffffffffu;
// multiply [a96 .. a00] x [b96 .. b00]
// terms higher than c96 disappear off the high side
// terms c96 and c64 are safe to ignore carry bit
uint64 c96 = a96 * b00 + a64 * b32 + a32 * b64 + a00 * b96;
uint64 c64 = a64 * b00 + a32 * b32 + a00 * b64;
this->hi_ = (c96 << 32) + c64;
this->lo_ = 0;
// add terms after this one at a time to capture carry
*this += uint128(a32 * b00) << 32;
*this += uint128(a00 * b32) << 32;
*this += a00 * b00;
return *this;
}
inline uint128 uint128::operator++(int) {
uint128 tmp(*this);
*this += 1;
return tmp;
}
inline uint128 uint128::operator--(int) {
uint128 tmp(*this);
*this -= 1;
return tmp;
}
inline uint128& uint128::operator++() {
*this += 1;
return *this;
}
inline uint128& uint128::operator--() {
*this -= 1;
return *this;
}
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_STUBS_INT128_H_
| 11,971 | 29.85567 | 79 | h |
sentencepiece | sentencepiece-master/third_party/protobuf-lite/google/protobuf/stubs/logging.h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#ifndef GOOGLE_PROTOBUF_STUBS_LOGGING_H_
#define GOOGLE_PROTOBUF_STUBS_LOGGING_H_
#include <google/protobuf/stubs/macros.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/port_def.inc>
// ===================================================================
// emulates google3/base/logging.h
namespace google {
namespace protobuf {
enum LogLevel {
LOGLEVEL_INFO, // Informational. This is never actually used by
// libprotobuf.
LOGLEVEL_WARNING, // Warns about issues that, although not technically a
// problem now, could cause problems in the future. For
// example, a // warning will be printed when parsing a
// message that is near the message size limit.
LOGLEVEL_ERROR, // An error occurred which should never happen during
// normal use.
LOGLEVEL_FATAL, // An error occurred from which the library cannot
// recover. This usually indicates a programming error
// in the code which calls the library, especially when
// compiled in debug mode.
#ifdef NDEBUG
LOGLEVEL_DFATAL = LOGLEVEL_ERROR
#else
LOGLEVEL_DFATAL = LOGLEVEL_FATAL
#endif
};
class StringPiece;
namespace util {
class Status;
}
class uint128;
namespace internal {
class LogFinisher;
class PROTOBUF_EXPORT LogMessage {
public:
LogMessage(LogLevel level, const char* filename, int line);
~LogMessage();
LogMessage& operator<<(const std::string& value);
LogMessage& operator<<(const char* value);
LogMessage& operator<<(char value);
LogMessage& operator<<(int value);
LogMessage& operator<<(uint value);
LogMessage& operator<<(long value);
LogMessage& operator<<(unsigned long value);
LogMessage& operator<<(long long value);
LogMessage& operator<<(unsigned long long value);
LogMessage& operator<<(double value);
LogMessage& operator<<(void* value);
LogMessage& operator<<(const StringPiece& value);
LogMessage& operator<<(const util::Status& status);
LogMessage& operator<<(const uint128& value);
private:
friend class LogFinisher;
void Finish();
LogLevel level_;
const char* filename_;
int line_;
std::string message_;
};
// Used to make the entire "LOG(BLAH) << etc." expression have a void return
// type and print a newline after each message.
class PROTOBUF_EXPORT LogFinisher {
public:
void operator=(LogMessage& other);
};
template<typename T>
bool IsOk(T status) { return status.ok(); }
template<>
inline bool IsOk(bool status) { return status; }
} // namespace internal
// Undef everything in case we're being mixed with some other Google library
// which already defined them itself. Presumably all Google libraries will
// support the same syntax for these so it should not be a big deal if they
// end up using our definitions instead.
#undef GOOGLE_LOG
#undef GOOGLE_LOG_IF
#undef GOOGLE_CHECK
#undef GOOGLE_CHECK_OK
#undef GOOGLE_CHECK_EQ
#undef GOOGLE_CHECK_NE
#undef GOOGLE_CHECK_LT
#undef GOOGLE_CHECK_LE
#undef GOOGLE_CHECK_GT
#undef GOOGLE_CHECK_GE
#undef GOOGLE_CHECK_NOTNULL
#undef GOOGLE_DLOG
#undef GOOGLE_DCHECK
#undef GOOGLE_DCHECK_OK
#undef GOOGLE_DCHECK_EQ
#undef GOOGLE_DCHECK_NE
#undef GOOGLE_DCHECK_LT
#undef GOOGLE_DCHECK_LE
#undef GOOGLE_DCHECK_GT
#undef GOOGLE_DCHECK_GE
#define GOOGLE_LOG(LEVEL) \
::google::protobuf::internal::LogFinisher() = \
::google::protobuf::internal::LogMessage( \
::google::protobuf::LOGLEVEL_##LEVEL, __FILE__, __LINE__)
#define GOOGLE_LOG_IF(LEVEL, CONDITION) \
!(CONDITION) ? (void)0 : GOOGLE_LOG(LEVEL)
#define GOOGLE_CHECK(EXPRESSION) \
GOOGLE_LOG_IF(FATAL, !(EXPRESSION)) << "CHECK failed: " #EXPRESSION ": "
#define GOOGLE_CHECK_OK(A) GOOGLE_CHECK(::google::protobuf::internal::IsOk(A))
#define GOOGLE_CHECK_EQ(A, B) GOOGLE_CHECK((A) == (B))
#define GOOGLE_CHECK_NE(A, B) GOOGLE_CHECK((A) != (B))
#define GOOGLE_CHECK_LT(A, B) GOOGLE_CHECK((A) < (B))
#define GOOGLE_CHECK_LE(A, B) GOOGLE_CHECK((A) <= (B))
#define GOOGLE_CHECK_GT(A, B) GOOGLE_CHECK((A) > (B))
#define GOOGLE_CHECK_GE(A, B) GOOGLE_CHECK((A) >= (B))
namespace internal {
template<typename T>
T* CheckNotNull(const char* /* file */, int /* line */,
const char* name, T* val) {
if (val == nullptr) {
GOOGLE_LOG(FATAL) << name;
}
return val;
}
} // namespace internal
#define GOOGLE_CHECK_NOTNULL(A) \
::google::protobuf::internal::CheckNotNull( \
__FILE__, __LINE__, "'" #A "' must not be nullptr", (A))
#ifdef NDEBUG
#define GOOGLE_DLOG(LEVEL) GOOGLE_LOG_IF(LEVEL, false)
#define GOOGLE_DCHECK(EXPRESSION) while(false) GOOGLE_CHECK(EXPRESSION)
#define GOOGLE_DCHECK_OK(E) GOOGLE_DCHECK(::google::protobuf::internal::IsOk(E))
#define GOOGLE_DCHECK_EQ(A, B) GOOGLE_DCHECK((A) == (B))
#define GOOGLE_DCHECK_NE(A, B) GOOGLE_DCHECK((A) != (B))
#define GOOGLE_DCHECK_LT(A, B) GOOGLE_DCHECK((A) < (B))
#define GOOGLE_DCHECK_LE(A, B) GOOGLE_DCHECK((A) <= (B))
#define GOOGLE_DCHECK_GT(A, B) GOOGLE_DCHECK((A) > (B))
#define GOOGLE_DCHECK_GE(A, B) GOOGLE_DCHECK((A) >= (B))
#else // NDEBUG
#define GOOGLE_DLOG GOOGLE_LOG
#define GOOGLE_DCHECK GOOGLE_CHECK
#define GOOGLE_DCHECK_OK GOOGLE_CHECK_OK
#define GOOGLE_DCHECK_EQ GOOGLE_CHECK_EQ
#define GOOGLE_DCHECK_NE GOOGLE_CHECK_NE
#define GOOGLE_DCHECK_LT GOOGLE_CHECK_LT
#define GOOGLE_DCHECK_LE GOOGLE_CHECK_LE
#define GOOGLE_DCHECK_GT GOOGLE_CHECK_GT
#define GOOGLE_DCHECK_GE GOOGLE_CHECK_GE
#endif // !NDEBUG
typedef void LogHandler(LogLevel level, const char* filename, int line,
const std::string& message);
// The protobuf library sometimes writes warning and error messages to
// stderr. These messages are primarily useful for developers, but may
// also help end users figure out a problem. If you would prefer that
// these messages be sent somewhere other than stderr, call SetLogHandler()
// to set your own handler. This returns the old handler. Set the handler
// to nullptr to ignore log messages (but see also LogSilencer, below).
//
// Obviously, SetLogHandler is not thread-safe. You should only call it
// at initialization time, and probably not from library code. If you
// simply want to suppress log messages temporarily (e.g. because you
// have some code that tends to trigger them frequently and you know
// the warnings are not important to you), use the LogSilencer class
// below.
PROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func);
// Create a LogSilencer if you want to temporarily suppress all log
// messages. As long as any LogSilencer objects exist, non-fatal
// log messages will be discarded (the current LogHandler will *not*
// be called). Constructing a LogSilencer is thread-safe. You may
// accidentally suppress log messages occurring in another thread, but
// since messages are generally for debugging purposes only, this isn't
// a big deal. If you want to intercept log messages, use SetLogHandler().
class PROTOBUF_EXPORT LogSilencer {
public:
LogSilencer();
~LogSilencer();
};
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_STUBS_LOGGING_H_
| 8,915 | 35.842975 | 80 | h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.