Archive

Posts Tagged ‘Code Snippets’

std::tie

April 15th, 2015 No comments
struct S { A a; B b; C c; };
auto const S_fields = [](S const& obj) -> auto { return std::tie(obj.a, obj.b, obj.c); };
bool operator == (S const& lhs, S const& rhs) { return S_fields(lhs) == S_fields(rhs); }
bool operator < (S const& lhs, S const& rhs) { return S_fields(lhs) < S_fields(rhs); }

Hyperpolyglot

March 30th, 2015 No comments

Programming Languages – commonly used features in a side-by-side format.

Pocket C++

April 24th, 2014 No comments

Portable and easy to use editor to write and test C++11 snippets. It integrates Notepad++ and Stephan T. Lavavej’s MinGW Distro (GCC 4.8.1). You can use F9 key to compile C++ files, and Ctrl+F9 to execute the compiled program.

homepage

Complex initialization for a const variable

April 13th, 2013 No comments
int main()
{
    bool someFlag = false;
    const auto value = [&]{
                               if(someFlag)
                                   return -1;
                               else
                                   return 1;
                              } ();

    std::cout << "value == " << value << std::endl;
    return 0;
}

Complex initialization for a const variable

Clean memory

February 20th, 2012 No comments
// Swaps the process out of physical RAM memory
SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T)-1, (SIZE_T)-1);

Можно ещё делать так, когда память процесса превышает некую “норму”:

EmptyWorkingSet(GetCurrentProcess());

HexToInt

March 5th, 2011 No comments

Several implementations of HexToInt function:

1. This implementation was in Chrome

inline unsigned char HexToInt(unsigned char c)
{
DCHECK(IsHexDigit(c));
static unsigned char kOffset[4] = {0, 0x30u, 0x37u, 0x57u};
return c - kOffset[(c >> 5) & 3];
}

2. From SQLite

return (c + 9 * (1 & (c >> 6))) & 15;

3. another version

return c - (0x57373000 >> (c >> 5) * 8);

or

return c - (0x57373000 >> ((c >> 5) << 3));

4.  nobody will understand

return c - 128 + (c >> 5 & 3)["(PI)"];

or

return c - 128 + "(PI)"[(c >>5) & 3]

Fast memory copy (SSE4)

January 29th, 2011 No comments

Visual Studio 2008 has supports “Enable Instruction Functions” options (see a project settings -> C/C++ -> Optimization). Note that this option can enlarge code.

Also memcpy function implementation has written with using sse2 (movdqa).

int CopyMemSSE4(int* piDst, int* piSrc, unsigned long SizeInBytes)
{
// Initialize pointers to start of the USWC memory

_asm
{
mov esi, piSrc
mov edx, piSrc

// Initialize pointer to end of the USWC memory
add edx, SizeInBytes

// Initialize pointer to start of the cacheable WB buffer
mov edi, piDst

// Start of Bulk Load loop
inner_start:
// Load data from USWC Memory using Streaming Load
MOVNTDQA xmm0, xmmword ptr [esi]
MOVNTDQA xmm1, xmmword ptr [esi+16]
MOVNTDQA xmm2, xmmword ptr [esi+32]
MOVNTDQA xmm3, xmmword ptr [esi+48]

// Copy data to buffer
MOVDQA xmmword ptr [edi], xmm0
MOVDQA xmmword ptr [edi+16], xmm1
MOVDQA xmmword ptr [edi+32], xmm2
MOVDQA xmmword ptr [edi+48], xmm3

// Increment pointers by cache line size and test for end of loop
add esi, 040h
add edi, 040h
cmp esi, edx
jne inner_start
}
// End of Bulk Load loop

return 0;
}

#define DATA_SIZE 0x01000000

int main(int argc, char* argv[])
{
int *piSrc = NULL;
int *piDst = NULL;
unsigned long dwDataSizeInBytes = sizeof(int) * DATA_SIZE;

piSrc = (int *)_aligned_malloc(dwDataSizeInBytes, dwDataSizeInBytes);
piDst = (int *)_aligned_malloc(dwDataSizeInBytes, dwDataSizeInBytes);

memset(piSrc, 255, dwDataSizeInBytes);
memset(piDst, 0, dwDataSizeInBytes);

CopyMemSSE4(piDst, piSrc, dwDataSizeInBytes);

_aligned_free(piSrc);
_aligned_free(piDst);
}

Additional links:

Is process a member of the Administrators local group

January 29th, 2011 No comments

The CheckTokenMembership function determines whether a specified security identifier (SID) is enabled in an access token.

/*
Routine Description: This routine returns TRUE if the caller's
process is a member of the Administrators local group. Caller is NOT
expected to be impersonating anyone and is expected to be able to
open its own process and process token.
Arguments: None.
Return Value:
TRUE - Caller has Administrators local group.
FALSE - Caller does not have Administrators local group.
*/
BOOL IsUserAdmin(void)
{
 BOOL bResult;
 SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
 PSID AdministratorsGroup;
 bResult = AllocateAndInitializeSid(&amp;NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                                    DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
                                    &amp;AdministratorsGroup);
 if(bResult)
 {
  if(!CheckTokenMembership(NULL, AdministratorsGroup, &amp;bResult))
  {
   bResult = FALSE;
  }
  FreeSid(AdministratorsGroup);
 }
 return(bResult);
}

MSDN

Using QString effectively

October 12th, 2010 No comments

Vigenere Cipher Algorithm (Delphi Implementation)

August 30th, 2010 Comments off

Here’s the Vigenere crypto algorithm as suggested by Allan:

function Vigenere(Src, Key : string; Encrypt : boolean) : string;
const
  OrdMinChar : integer = Ord('A');
  OrdMaxChar : integer = Ord('Z');
  IncludeChars : set of char = ['A'..'Z'];
var
  CharRangeCount, i, j, KeyLen, KeyInc, SrcOrd, CryptOrd : integer;
  SrcA : string;
begin
  CharRangeCount := OrdMaxChar - OrdMinChar + 1;
  KeyLen := Length(Key);
  SetLength(SrcA, Length(Src));
  If Encrypt then
  begin
    // transfer only included characters to SrcA for encryption
    j := 1;
    for i := 1 to Length(Src) do
    begin
      if (Src[i] in IncludeChars) then
      begin
        SrcA[j] := Src[i];
        inc(j);
      end;
    end;
    SetLength(SrcA, j - 1);
  end;
  SetLength(Result, Length(SrcA));
  if Encrypt then
  begin
    // Encrypt to Result
    for i := 1 to Length(SrcA) do
    begin
      SrcOrd := Ord(Src[i]) - OrdMinChar;
      KeyInc := Ord(Key[((i - 1 ) mod KeyLen)+ 1]) - OrdMinChar;
      CryptOrd := ((SrcOrd + KeyInc) mod CharRangeCount) + OrdMinChar;
      Result[i] := Char(CryptOrd);
    end;
  end;
  else
  begin
    // Decrypt to Result
    for i := 1 to Length(SrcA) do
    begin
      SrcOrd := Ord(Src[i]) - OrdMinChar;
      KeyInc := Ord(Key[((i - 1 ) mod KeyLen)+ 1]) - OrdMinChar;
      CryptOrd := ((SrcOrd - KeyInc + CharRangeCount)
                   mod CharRangeCount) + OrdMinChar;
      // KeyInc may be larger than SrcOrd
      Result[i] := Char(CryptOrd);
    end;
  end;
end;