uuidgen.h

来自「一个简单实用的开源C++消息中间件SAFMQ - [软件开发] - [开源 消息」· C头文件 代码 · 共 98 行

H
98
字号
/*
 Copyright 2005 Matthew J. Battey

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software distributed
	under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
	CONDITIONS OF ANY KIND, either express or implied. See the License for the
	specific language governing permissions and limitations under the License.




This software implements a platform independent UUID generator and iostream insertion
and extraction operators.
*/
#ifndef _UUIDGEN_H_
#define _UUIDGEN_H_
#ifdef __cplusplus
extern "C" {
#endif

struct uuid {	union {		unsigned char raw[16];		struct {			unsigned long  d1;			unsigned short d2;			unsigned short d3;
			unsigned char  d4[8];		} guid;	};};void uuidgen(struct uuid* puuid);
void setuuidconf(const char* uuidconf);

#ifdef __cplusplus
};

#include <ostream>
#include <iomanip>
#include <memory.h>
#include <stdlib.h>

inline std::ostream& operator<<(std::ostream& o, const uuid& u)
{
	std::ios::fmtflags oldflags = o.flags();
	char oldfill = o.fill('0');
	o << std::hex << std::setw(8) << u.guid.d1 << '-' << std::setw(4) << u.guid.d2 << '-' << std::setw(4) << u.guid.d3 << '-' << std::setw(4) << *(short*)u.guid.d4 << '-';
	o << std::setw(2) << (short)u.guid.d4[2];
	o << std::setw(2) << (short)u.guid.d4[3];
	o << std::setw(2) << (short)u.guid.d4[4];
	o << std::setw(2) << (short)u.guid.d4[5];
	o << std::setw(2) << (short)u.guid.d4[6];
	o << std::setw(2) << (short)u.guid.d4[7];
	o.flags(oldflags);
	o.fill(oldfill);
	return o;
}

inline std::istream& operator>>(std::istream& i, uuid& u)
{
	char	buffer[37];
	int		start = i.gcount();
	
	i.read(buffer,36);

	if ((i.gcount()-start) == 36) {
		char	tmp[3];
		char*	p;

		buffer[8] = 0;
		buffer[13] = 0;
		buffer[18] = 0;
		buffer[23] = 0;
		u.guid.d1 = strtoul(buffer,&p,16);
		u.guid.d2 = strtoul(buffer+9,&p,16);
		u.guid.d3 = strtoul(buffer+14,&p,16);
		*(short*)u.guid.d4 = strtoul(buffer+19,&p,16);

		for(int x=0;x<6;x++) {
			memcpy(tmp,buffer+24+(x*2),2);
			u.guid.d4[x+2] = strtoul(tmp,&p,16);
		}
	}
	return i;
}

#endif

#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?