Archive

Posts Tagged ‘Code Snippets’

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(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                                    DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
                                    &AdministratorsGroup);
 if(bResult)
 {
  if(!CheckTokenMembership(NULL, AdministratorsGroup, &bResult))
  {
   bResult = FALSE;
  }
  FreeSid(AdministratorsGroup);
 }
 return(bResult);
}

MSDN

Using QString effectively

October 12th, 2010 No comments

[slideshare id=5425657&doc=qt004-usingqstringeffectively-101012124512-phpapp01]

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;

Saving Window Size State

August 30th, 2010 No comments
class MainWindow : public QMainWindow
{
 Q_OBJECT;
public:
 MainWindow(QWidget *parent = 0) : QMainWindow(parent)
 {
   QSettings settings;
   restoreGeometry(settings.value("mainWindowGeometry").toByteArray());
   // create docs, toolbars, etc...
   restoreState(settings.value("mainWindowState").toByteArray());
 }

 void closeEvent(QCloseEvent *event)
 {
   QSettings settings;
   settings.setValue("mainWindowGeometry", saveGeometry());
   settings.setValue("mainWindowState", saveState());
 }
};

int main(int argc, char *argv[])
{
 QApplication a(argc, argv);
 QCoreApplication::setOrganizationDomain("OrgDomain");
 QCoreApplication::setOrganizationName("OrgName");
 QCoreApplication::setApplicationName("AppName");
 QCoreApplication::setApplicationVersion("1.0.0");

 MainWindow w;
 w.show();

 return a.exec();
}

The above code will save and restore window position, size, toolbar visibility, toolbar docking area, dock states, locations and sizes. It saves using QSettings which will store your settings in a platform correct way.

Source

97 Things Every Programmer Should Know

August 18th, 2010 No comments

97 Things Every Programmer Should KnowGet 97 short and extremely useful tips from some of the most experienced and respected practitioners in the industry, including Uncle Bob Martin, Scott Meyers, Dan North, Linda Rising, Udi Dahan, Neal Ford, and many more. They encourage you to stretch yourself by learning new languages, looking at problems in new ways, following specific practices, taking responsibility for your work, and becoming as good at the entire craft of programming as you possibly can.

O’Relly homepage

There is the 97 Things Every Programmer Should Know project, pearls of wisdom for programmers collected from leading practitioners. You can read through the Contributions Appearing in the Book.

Russian translation of these tips.

Levenshtein distance

July 28th, 2010 No comments

In information theory and computer science, the Levenshtein distance is a metric for measuring the amount of difference between two sequences (i.e. an edit distance). The term edit distance is often used to refer specifically to Levenshtein distance.

The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. It is named after Vladimir Levenshtein, who considered this distance in 1965. (wikipedia with code, russian version)

Using QString effectively

June 22nd, 2010 No comments

QLatin1String : Avoid mallocs in operator ”==”

Creating a QString from a C-string involves a malloc. For example, there is a hidden-malloc cost in the following code.
if (fruit== "apple") { ... } // hidden malloc
In the code above, “apple” gets converted into a QString using QString::fromAscii(). This means that QString will allocate memory for the string “apple” and creates a deep copy of the C-style string. This deep copy is not really necessary and can be avoided by not creating a QString to start with and if the encoding of the C-string was somehow known. Since Latin-1 string comparisons are most common, Qt provides a special class called QLatin1String that just holds a pointer to the C-string provided in it’s constructor. In addition, QString provides a QString::operator==(const QLatin1String &) overload that has special code to compare without malloc+deep copy. We can make the above code fast by writing it instead as,
if (fruit== QLatin1String("apple")) { ... } // fast and mentions encoding

QStringRef : String manipulation without the malloc

QString has various methods for string manipulations like mid(), left(), right(). All of them create a new QString and hence a malloc/deep copy of data in an existing QString. Instead, one can use QString::midRef(), QString::leftRef() and QString::rightRef() to obtain a QStringRef. A QStringRef is a reference of a portion of a QString. QString also provides many overloads like QString::operator==(const QStringRef &) for optimizations with QStringRef.

QString::reserve and QString::squeeze

If you expect a QString to grow, it’s better to call QString::reserve to allocate extra memory in advance so that every call to QString::append() does not result in a malloc. Extra memory can be reclaimed using QString::squeeze.

QStringBuilder : Fast QString concatenation

The code below requires atleast 2 mallocs.
if (foo.startsWith("(" + type + ") 0x"))
Qt 4.6 introduces an internal class called QStringBuilder that “reserves” memory for a concatenation chain in a single shot. It does so by having each of the + operations above return a different class (not QString). This class keeps track of the string’s that are being appended and the required memory at each step. At the final step, where the concatenation operation gets converted into a QString it allocates memory in a single shot and copies all the strings in the chain one after another. This features can be enabled by using QT_USE_FAST_CONCATENATION. With this defined, one can use the operator ’%’ instead of ’+’. One would now write,
if (foo.startsWith("(" % type % ") 0x"))
If we want to use ’+’ itself instead of ’%’, one can also define QT_USE_FAST_OPERATOR_PLUS. See Fast concatenation for more details

Use QStringMatcher to match a string repetitively

If you are looking for a string repetitively in many strings or in the same string many times, you should use QStringMatcher. It uses Boyer-Moore string search algorithm to perform fast searches.