- 1
masko xor_eq mask;
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+24
masko xor_eq mask;
А вообще жаль, что эту дельфитню включили в стандарт.
+25
uint32 originalDamage = damage;
if (absorb && originalDamage > damage)
*absorb += (originalDamage - damage);
Вытащил из 1 эмулятора игры World of WarCraft
+20
class NetGetPlmnListReply: public Message {
public:
virtual uint8_t command() const;
virtual uint8_t subcommand() const;
virtual RequestType requestType() const;
virtual bool deliver(IUnsolicitedReceiver *receiver);
static inline bool isTypeOf(Message *message) {
return message->command() == 8 && message->subcommand() == 4;
}
std::string inspect() const;
bool writeToStream(DataStream &stream);
bool readFromStream(DataStream &stream);
inline uint8_t count() const { return m_count; }
inline void setCount(uint8_t count) { m_count = count; }
class PlmnListItem {
public:
std::string inspect() const;
bool writeToStream(DataStream &stream);
bool readFromStream(DataStream &stream);
enum Status {
Available = 2,
Current = 3,
Forbidden = 4,
};
inline Status status() const { return (Status) m_status; }
inline void setStatus(Status status) { m_status = (uint8_t) status; }
inline const std::vector<unsigned char> &plmn() const { return m_plmn; }
inline void setPlmn(const std::vector<unsigned char> &plmn) { m_plmn = plmn; }
private:
uint8_t m_status;
std::vector<unsigned char> m_plmn;
};
inline const std::vector<PlmnListItem> &plmnList() const { return m_plmnList; }
inline void setPlmnList(const std::vector<PlmnListItem> &plmnList) { m_plmnList = plmnList; }
private:
uint8_t m_count;
std::vector<PlmnListItem> m_plmnList;
};
Один из тысячи сгенерированных классов.
+20
#include <iostream>
#include <string>
int main(void)
{
char arr[] = "All's well that ends well";
std::string s(arr, 3000);
std::cout << s << std::endl;
return(0);
}
Первое что пришло на ум, когда смотрел конструкторы string.
Собирал: g++-4.5 -Wall -Wextra -pedantic-errors
ideone.com и liveworkspace.org фильтруют.
+7
TPrimitive a((TLine())), b((TCircle()));
Вынужденный говнокод.
Должно быть:
TPrimitive a(TLine()), b(TCircle());
+28
byte* GetBuffer0(bool free = false)
{
static std::auto_ptr<byte> transferBuffer;
if (free)
{
delete [] transferBuffer.release();
}
else
{
if (!transferBuffer.get())
{
transferBuffer.reset(new byte[BUFFER_SIZE]);
}
}
return transferBuffer.get();
}
byte* GetBuffer1(bool free = false)
{
static std::auto_ptr<byte> transferBuffer;
if (free)
{
delete [] transferBuffer.release();
}
else
{
if (!transferBuffer.get())
{
transferBuffer.reset(new byte[BUFFER_SIZE]);
}
}
return transferBuffer.get();
}
legacy-дебри
+18
template <typename TYPE> class Ptr
{
public:
Ptr():
Pointer_(0),
IsValid_(false)
{
}
Ptr( const Ptr<TYPE> &other )
{
this->Pointer_ = other.Pointer_;
this->IsValid_ = other.IsValid_;
}
Ptr( TYPE* &ptr ):
IsValid_(true)
{
if ( std::find( Ptr<TYPE>::List_.begin(), Ptr<TYPE>::List_.end(), ptr ) == Ptr<TYPE>::List_.end() )
Ptr<TYPE>::List_.push_back( ptr );
this->Pointer_ = ptr;
}
~Ptr()
{
}
inline Ptr<TYPE>& operator = ( const Ptr<TYPE> &other )
{
this->Pointer_ = other.Pointer_;
this->IsValid_ = other.IsValid_;
return *this;
}
inline Ptr<TYPE>& operator = ( TYPE* &ptr )
{
if ( std::find( Ptr<TYPE>::List_.begin(), Ptr<TYPE>::List_.end(), ptr ) == Ptr<TYPE>::List_.end() )
Ptr<TYPE>::List_.push_back( ptr );
this->Pointer_ = ptr;
this->IsValid_ = true;
return *this;
}
inline bool operator == ( const Ptr<TYPE> &other )
{
return (this->Pointer_ == other.Pointer_) ? true:false;
}
inline bool operator != ( const Ptr<TYPE> &other )
{
return (this->Pointer_ != other.Pointer_) ? true:false;
}
inline TYPE* operator -> ()
{
return this->Pointer_;
}
inline bool isValid() const
{
if (!this->IsValid_)
return false;
return this->IsValid_ = ( (std::find( Ptr<TYPE>::List_.begin(), Ptr<TYPE>::List_.end(), this->Pointer_ ) == Ptr<TYPE>::List_.end() ) ? false:true );
}
inline void release()
{
if ( this->isValid() )
{
Ptr<TYPE>::List_.erase( std::find( Ptr<TYPE>::List_.begin(), Ptr<TYPE>::List_.end(), this->Pointer_ ) );
delete this->Pointer_;
}
this->Pointer_ = 0;
this->IsValid_ = false;
}
inline TYPE* get()
{
return this->Pointer_;
}
private:
TYPE* Pointer_;
mutable bool IsValid_;
static std::list < TYPE* > List_;
};
template <typename TYPE> std::list < TYPE* > Ptr<TYPE>::List_;
+8
bool ASN1Parser::ConvertOID(const ASN1Block &blk, char *oid, unsigned int bufSize) {
int a = 0;
bool first = true;
char tmp[32];
oid[0] = 0;
for (unsigned int i=0;i<blk.size;i++) {
unsigned char c = data[blk.offset+i];
if (c & 0x80) {
a = (a << 7) | (c & 0x7F);
} else {
a = (a << 7) | (c & 0x7F);
if (!first) {
sprintf(tmp,".%d",a);
} else {
sprintf(tmp,"%d.%d",a/40,a%40);
}
a=0;
first = false;
if (strlen(tmp) >= bufSize) return false;
strcat(oid, tmp);
}
}
return true;
}
И еще один говнокодец на тему ASN.1 - распаковка OID'а.
Кто найдет ошибку - получит пирожок с полочки ;)
+24
#include <stdio.h>
#include "gost.h"
int main() {
MemoryFile mf("root.cer");
MemoryFile mf2("test.cer");
ASN1Parser parser(mf);
ASN1Parser parser2(mf2);
ASN1Block e1[2];
parser.Split("30{30{A0#,02$1,30#,30#,30#,30#,30{30#,03$2},A3#},30#,03#}", e1);
unsigned char px[32], py[32], r[32], s[32], h[32];
for (int i=0;i<32;i++) {
px[i] = mf.data[e1[1].offset+i+3];
py[i] = mf.data[e1[1].offset+i+35];
}
parser2.Split("30{30$1,30#,03$2}", e1);
for (int i=0;i<32;i++) {
r[i] = mf2.data[e1[1].offset+64-i];
s[i] = mf2.data[e1[1].offset+32-i];
}
Gost3411 hash;
hash.AddData(mf2.data+e1[0].offset-4, e1[0].size+4);
hash.Finish(h);
Gost3410 g;
if (!g.VerifySignature(h, px, py, r, s)) {
printf("Invalid!");
} else {
printf("Valid!");
}
return 0;
}
Продолжение http://govnokod.ru/11528. Вот так я проверял валидность сертификата...
Прекрасные говорящие имена переменных...
Удобный парсер ASN.1...
Отличная инкапсуляция...
Ни одного магического числа...
+20
//Вколите мне каплю никотина, а когда меня разорвет - сожгите ошметки напалмом.
//Только это смоет мой позор.
//Примерно так у меня выглядит вся обработка исключений:
int main(int, char**) //или wWinMain, не важно
{
try
{
//all stuff here
}
catch(std::exception e)
{
MessageBoxA(NULL, e.what(), "oops", MB_OK | MB_ICONERROR);
}
catch(...)
{
MessageBoxA(NULL, "Unknown error", "oops", MB_OK | MB_ICONERROR);
}
return 0;
}
//А еще у меня есть свой класс строки:
class MyString
{
wchar_t * data;
size_t length;
MyString(wchar_t * _data, size_t _length) : data(_data), length(_length) { }
public:
//...
static MyString MyString::fromNumber(int num)
{ //Грешен, определяю функции в заголовочном, хотя это и не тот случай.
wchar_t * data = new wchar_t[16];
HRESULT hr = StringCchPrintfW(data, 16, L"%d", num);
if(FAILED(hr))
{
throw std::exception("shit happend inside MyString::fromNumber(int)");
}
size_t len = 0;
hr = StringCchLengthW(data, 16, &len);
if(FAILED(hr))
{
throw std::exception("shit happend inside MyString::fromNumber(int)");
}
return MyString(data, len);
}
};
//А вкупе с обработкой исключений чуть выше...
//Чуть не забыл про auto_ptr. Укорочено до сути.
class Base
{
protected:
std::auto_ptr<SomeType> data; //А где он инициализируется?...
public:
virtual ~Base() { }
};
class Deriv : public Base
{
public:
Deriv() : Base()
{
data = std::auto_ptr<SomeType>(new SomeType(args)); //...а вот тут он инициализируется!
}
virtual ~Deriv() { }
};
//Паттерны!
class Single
{
Single(); //Без реализации.
template<typename T> Single(T); //Без реализации.
template<typename T1, typename T2> T1 operator = (T2); //Без реализации.
class Ton
{
//...
};
static Ton object;
static Ton initObject();
public:
Ton & instance() { return object; }
};
//Мне стыдно.