Tuesday, September 29, 2009

Краткая памятка по битовым операциям


Setting a bit

Use the bitwise OR operator (|) to set a bit.

 number |= 1 << x;

That will set bit x.

Clearing a bit

Use the bitwise AND operator (&) to clear a bit.

 number &= ~(1 << x);

That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.

Toggling a bit

The XOR operator (^) can be used to toggle a bit.

 number ^= 1 << x;

That will toggle bit x.

Checking a bit

You didn't ask for this but I might as well add it.

To check a bit, AND it with the bit you want to check:

 bit = number & (1 << x);

That will put the value of bit x into the variable bit.


Toggling a bit and leaving all other bits unchanged

x = x ^ mask;
(or shorthand x ^= mask;)

Bits that are set to 1 in the mask will be toggled in x.
Bits that are set to 0 in the mask will be unchanged in x.

Toggling means that if the bit is 1, it is set to 0, and if the bit is 0, it is set to 1.

XOR truth table
0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1
1 ^ 1 = 0


Setting a bit to zero and leaving all other bits unchanged

x = x & mask;
(or x &= mask;)

Bits that are set to 1 in the mask will be unchanged in x.
Bits that are set to 0 in the mask will be set to zero in x.

AND truth table
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1

Common Flags Values
Binary
(base2)
Hexadecimal
(base16)
Decimal
(base10)
0000 0000 0x00 0
0000 0001 0x01 1
0000 0010 0x02 2
0000 0100 0x04 4
0000 1000 0x08 8
0001 0000 0x10 16
0010 0000 0x20 32
0100 0000 0x40 64
1000 0000 0x80 128

Example macros:

Imagine there are two flags in the program that are independent of each other. We might implement macros to manipulate them as shown in the code sample below. It would probably be wise to put the macros in a header file.


// the flag definitions
#define CAR_LOCKED 0x01 // 0000 0001
#define CAR_PARKED 0x02 // 0000 0010
#define CAR_RESET 0x00 // 0000 0000

// macros to manipulate the flags
#define RESET_CAR(x) (x = CAR_RESET)

#define SET_LOCKED(x) (x |= CAR_LOCKED)
#define SET_PARKED(x) (x |= CAR_PARKED)

#define UNSET_LOCKED(x) (x &= (~CAR_LOCKED))
#define UNSET_PARKED(x) (x &= (~CAR_PARKED))

#define TOGGLE_LOCKED(x) (x ^= CAR_LOCKED)
#define TOGGLE_PARKED(x) (x ^= CAR_PARKED)

// these evaluate to non-zero if the flag is set
#define IS_LOCKED(x) (x & CAR_LOCKED)
#define IS_PARKED(x) (x & CAR_PARKED)

// a short program that demonstrates how to use the macros
int main(void)
{
unsigned char fMercedes, fCivic;

RESET_CAR(fMercedes);
RESET_CAR(fCivic);

SET_LOCKED(fMercedes);

if( IS_LOCKED(fMercedes) != 0 )
{
UNSET_PARKED(fCivic);
}

TOGGLE_LOCKED(fMercedes);

return 0;
}

Использование std::bitset и boost::dynamic_bitset

#include
#include

int main()
{
std
::bitset<5> x;
x
[1] = 1;
x
[2] = 0;
// Note x[0-4] valid
std
::cout << x << std::endl;
}

The other option is to use bit fields:

struct bits {
unsigned int a:1;
unsigned int b:1;
unsigned int c:1;
};

struct bits mybits;

This defines a 3-bit field (actually, it's three 1-bit felds).
Bit operations now become a bit (haha) simpler:

To set or clear a bit:

mybits
.b = 1;
mybits
.c = 0;

To toggle a bit:

mybits
.a = !mybits.a;
mybits
.b = ~mybits.b;
mybits
.c ^= 1; /* all work */

Checking a bit:

if
(mybits.c)
This only works with bits in fixed positions. Otherwise you have to
resort to the bit-twiddling techniques described in previous posts.


It is sometimes worth using an enum to name the bits:
enum ThingFlags = {
ThingMask = 0x0000,
ThingFlag0
= 1 << 0,
ThingFlag1
= 1 << 1,
ThingError = 1 << 8,
}

Then use the names later on. I.e. write

 thingstate |= ThingFlag1;
thingstate
&= ~ThingFlag0;
if (thing | ThingError) {...}

to set, clear and test. This way you hide the magic numbers from the rest of your code.

From snip-c.zip's bitops.how:

/*
** Bit set, clear, and test operations
**
** public domain snippet by Bob Stout
*/
typedef enum {ERROR = -1, FALSE, TRUE} LOGICAL;

#define BOOL(x) (!(!(x)))

#define BitSet(arg,posn) ((arg) | (1L << (posn)))
#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))
#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))
#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))

OK, let's analyze things...

The common expression in all of these that you seem to be having problems with is "(1L << (posn))". All this does is create a mask with a single bit on and which will work with any integer type. The "posn" argument specifies the position where you want the bit. If posn==0, then this expression will evaluate to:

0000 0000 0000 0000 0000 0000 0000 0001 binary.

If posn==8, it will evaluate to

0000 0000 0000 0000 0000 0001 0000 0000 binary.

In other words, it simply creates a field of 0's with a 1 at the specified position. The only tricky part is in the BitClr() macro where we need to set a single 0 bit in a field of 1's. This is accomplished by using the 1's complement of the same expression as denoted by the tilde (~) operator.

Once the mask is created it's applied to the argument just as you suggest, by use of the bitwise and (&), or (|), and xor (^) operators. Since the mask is of type long, the macros will work just as well on char's, short's, int's, or long's.

The bottom line is that this is a general solution to an entire class of problems. It is, of course, possible and even appropriate to rewrite the equivalent of any of these macros with explicit mask values every time you need one, but why do it? Remember, the macro substitution occurs in the preprocessor and so the generated code will reflect the fact that the values are considered constant by the compiler - i.e. it's just as efficient to use the generalized macros as to "reinvent the wheel" every time you need to do bit manipulation.

Unconvinced? Here's some test code - I used Watcom C with full optimization and without using _cdecl so the resulting disassembly would be as clean as possible:

----[ TEST.C ]----------------------------------------------------------------

#define BOOL(x) (!(!(x)))

#define BitSet(arg,posn) ((arg) | (1L << (posn)))
#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))
#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))
#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))

int bitmanip(int word)
{
word
= BitSet(word, 2);
word
= BitSet(word, 7);
word
= BitClr(word, 3);
word
= BitFlp(word, 9);
return word;
}

----[ TEST.OUT (disassembled) ]-----------------------------------------------

Module: C:\BINK\tst.c Group: 'DGROUP' CONST,CONST2,_DATA,_BSS

Segment: TEXT BYTE 00000008 bytes
0000 0c 84 bitmanip
or al,84H 0002 80 f4 02 xor ah,02H 0005 24 f7 and al,0f7H 0007 c3 ret

No disassembly errors

еще:
/* a=target variable, b=bit number to act upon 0-n */
#define BIT_SET(a,b) ((a) |= (1<<(b)))
#define BIT_CLEAR(a,b) ((a) &= ~(1<<(b)))
#define BIT_FLIP(a,b) ((a) ^= (1<<(b)))
#define BIT_CHECK(a,b) ((a) & (1<<(b)))

/* x=target variable, y=mask */
#define BITMASK_SET(x,y) ((x) |= (y))
#define BITMASK_CLEAR(x,y) ((x) &= (~(y)))
#define BITMASK_FLIP(x,y) ((x) ^= (y))
#define BITMASK_CHECK(x,y) ((x) & (y))

еще:

The bitfield approach has other advantages in the embedded arena. You can define a struct that maps directly onto the bits in a particular hardware register.
struct HwRegister {
unsigned int errorFlag:1; // one-bit flag field
unsigned int Mode:3; // three-bit mode field
unsigned int StatusCode:4; // four-bit status code
};

struct HwRegister CR3342_AReg;

You need to be aware of the bit packing order - I think it's MSB first, but this may be implementation-dependent. Also, verify how your compiler handlers fields crossing byte boundaries.

You can then read, write, test the individual values as before.

const unsigned char TQuickByteMask[8] =
{
0x01, 0x02, 0x04, 0x08,
0x10, 0x20, 0x40, 0x80,
};

еще:

If you're doing a lot of bit twiddling you might want to use masks
which will make the whole thing quicker. The following functions are
very fast and still flexible (they allow bit twiddling in bit maps of
any size)

/** Set bit in any sized bit mask.
*
* @return none
*
* @param bit - Bit number.
* @param bitmap - Pointer to bitmap.
*/

void TSetBit( short bit, unsigned char *bitmap)
{
short n, x;

x
= bit / 8; // Index to byte.
n
= bit % 8; // Specific bit in byte.

bitmap
[x] |= TQuickByteMask[n]; // Set bit.
}

/** Reset bit in any sized mask.
*
* @return None
*
* @param bit - Bit number.
* @param bitmap - Pointer to bitmap.
*/

void TResetBit( short bit, unsigned char *bitmap)
{
short n, x;

x
= bit / 8; // Index to byte.
n
= bit % 8; // Specific bit in byte.

bitmap
[x] &= (~TQuickByteMask[n]); // Reset bit.
}

/** Toggle bit in any sized bit mask.
*
* @return none
*
* @param bit - Bit number.
* @param bitmap - Pointer to bitmap.
*/

void TToggleBit( short bit, unsigned char *bitmap)
{
short n, x;

x
= bit / 8; // Index to byte.
n
= bit % 8; // Specific bit in byte.

bitmap
[x] ^= TQuickByteMask[n]; // Toggle bit.
}

/** Checks specified bit.
*
* @return 1 if bit set else 0.
*
* @param bit - Bit number.
* @param bitmap - Pointer to bitmap.
*/

short TIsBitSet( short bit, const unsigned char *bitmap)
{
short n, x;

x
= bit / 8; // Index to byte.
n
= bit % 8; // Specific bit in byte.

// Test bit (logigal AND).
if (bitmap[x] & TQuickByteMask[n])
return 1;

return 0;
}

/** Checks specified bit.
*
* @return 1 if bit reset else 0.
*
* @param bit - Bit number.
* @param bitmap - Pointer to bitmap.
*/

short TIsBitReset( short bit, const unsigned char *bitmap)
{
return TIsBitSet( bit, bitmap) ^ 1;
}

/** Count number of bits set in a bitmap.
*
* @return Number of bits set.
*
* @param bitmap - Pointer to bitmap.
* @param size - Bitmap size (in bits).
*
* @note Not very efficient in terms of execution speed. If you are doing
* some computationally intense stuff you may need a more complex
* implementation which would be faster (especially for big bitmaps).
* See (http://graphics.stanford.edu/~seander/bithacks.html).
*/

int TCountBits( const unsigned char *bitmap, int size)
{
int i, count=0;

for (i=0; i<size; i++)
if (TIsBitSet( i, bitmap)) count++;

return count;
}

Note, to set bit 'n' in a 16 bit integer you do the following:

TSetBit( n, &my_int);

It's up to you to ensure that the bit number is within the range of the bit map that you pass. Note that for little endian processors that bytes, words, dwords,qwords etc, map correctly to each other in memory (main reason that little endian processors are 'better' than big-endian processors, ah, I feel a flame war coming on...).

Дополнительные ссылки:
bits.stephan-brumme.com
aggregate.org/MAGIC
realtimecollisiondetection.net/blog/?p=78
graphics.stanford.edu/~seander/bithacks.html
www.somacon.com/p125.php
stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c

VOIP SDK

www.voipdevkit.com
VOIP приложение за 10 мин.
www.voipdevkit.com/docs/vdk.flv

How to count bits to save a number

template
struct NBits
{
enum { value = NBits<(n >> 1)>::value + 1 };
};

template<>
struct NBits<0>
{
enum { value = 0 };
};

Thursday, September 24, 2009

Singletons in C#

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons
is that they are created lazily - i.e. that the instance isn't created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.

All these implementations share four common characteristics, however:A single constructor, which is private and parameterless.

  • This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type,
    but the exact type isn't known until runtime.

  • The class is sealed. This is unnecessary, strictly speaking, due to the above point,
    but may help the JIT to optimise things more.

  • A static variable which holds a reference to the single created instance, if any.

  • A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static property Instance

as the means of accessing the instance. In all cases, the property could easily be converted
to a method, with no impact on thread-safety or performance.

First version - not thread-safe


// Bad code! Do not use!

public sealedclass Singleton
{
static Singleton instance=null;

Singleton()
{
}

public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}


As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety


public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();

Singleton()
{
}

public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}

This implementation is thread-safe. The thread takes out a lock on a shared
object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false).
Unfortunately, performance suffers as a lock is acquired every time the instance is requested.


Note that instead of locking on typeof(Singleton) as some versions of this
implementation do, I lock on the value of a static variable which is private to the class.
Locking on objects which other classes can access and lock on (such as the type) risks
performance issues and even deadlocks. This is a general style preference of mine - wherever
possible, only lock on objects specifically created for the purpose of locking, or which
document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue).
Usually such objects should be private to the class they are used in. This helps to make
writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking


// Bad code! Do not use!
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();

Singleton()
{
}

public static Singleton Instance
{
get
{
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time.
Unfortunately, there are four downsides to the pattern:

  • It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).

  • Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!

  • It's easy to get wrong. The pattern needs to be pretty much exactly as above - any
    significant changes are likely to impact either performance or correctness.

  • It still doesn't perform as well as the later implementations.


Fourth version - not quite as lazy, but thread-safe without using lock


public sealed class Singleton
{
static readonly Singleton instance=new Singleton();

// Explicit static constructor to tell C# compiler

// not to mark type as beforefieldinit
static Singleton()
{
}

Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it?
Well, static constructors in C# are specified to execute only when an instance of the class is
created or a static member is referenced, and to execute only once per AppDomain. Given that
this check for the type being newly constructed needs to be executed whatever else happens, it
will be faster than adding extra checking as in the previous examples. There are a couple of
wrinkles, however:

  • It's not as lazy as the other implementations. In particular, if you have static members
    other than Instance, the first reference to those members will involve
    creating the instance. This is corrected in the next implementation.

  • There are complications if one static constructor invokes another which invokes the
    first again. Look in the .NET specifications (currently section 9.5.3 of partition II)
    for more details about the exact nature of type initializers - they're unlikely to bite you,
    but it's worth being aware of the consequences of static constructors which refer to each
    other in a cycle.

  • The laziness of type initializers is only guaranteed by .NET when the type isn't
    marked with a special flag called beforefieldinit. Unfortunately,
    the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types
    which don't have a static constructor (i.e. a block which looks
    like a constructor but is marked static) as beforefieldinit. I now
    have a discussion page with more details about
    this issue. Also note that it affects performance, as discussed near the bottom of this article.


One shortcut you can take with this implementation (and only this one) is to just make
instance a public static readonly variable, and get rid of the property entirely.
This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a
property in case further action is needed in future, and JIT inlining is likely to make
the performance identical. (Note that the static constructor itself is still required
if you require laziness.)

Fifth version - fully lazy instantiation

public sealed class Singleton
{
Singleton()
{
}

public static Singleton Instance
{
get
{
return Nested.instance;
}
}

class Nested
{
// Explicit static constructor to tell C# compiler

// not to mark type as beforefieldinit
static Nested()
{
}

internal static readonly Singleton instance = new Singleton();
}
}

Here, instantiation is triggered by the first reference to the static member of the nested

class, which only occurs in Instance. This means the implementation is fully
lazy, but has all the performance benefits of the previous ones. Note that although nested
classes have access to the enclosing class's private members, the reverse is not true, hence
the need for instance to be internal here. That doesn't raise any other problems,
though, as the class itself is private. The code is a bit more complicated in order to make
the instantiation lazy, however.

Performance vs laziness

In many cases, you won't actually require full laziness - unless your class initialization
does something particularly time-consuming, or has some side-effect elsewhere, it's probably
fine to leave out the explicit static constructor shown above. This can increase performance
as it allows the JIT compiler to make a single check (for instance at the start of a method)
to ensure that the type has been initialized, and then assume it from then on. If your
singleton instance is referenced within a relatively tight loop, this can make a (relatively)
significant performance difference. You should decide whether or not fully lazy instantiation
is required, and document this decision appropriately within the class. (See below for more on
performance, however.)

Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but
might not be fatal to the whole application. Potentially, your application may be able to
fix the problem and want to try again. Using type initializers to construct the singleton
becomes problematic at this stage. Different runtimes handle this case differently,
but I don't know of any which do the desired thing (running the type initializer again), and
even if one did, your code would be broken on other runtimes. To avoid these problems, I'd
suggest using the second pattern listed on the page - just use a simple lock, and go through
the check each time, building the instance in the method/property if it hasn't already been
successfully built.


Thanks to Andriy Tereshchenko for raising this issue.

A word on performance

A lot of the reason for this page stemmed from people trying to be clever, and thus coming
up with the double-checked locking algorithm. There is an attitude of locking being expensive
which is common and misguided. I've written a very quick benchmark
which just acquires singleton instances in a loop a billion ways, trying different variants.
It's not terribly scientific, because in real life you may want to know how fast it is if each
iteration actually involved a call into a method fetching the singleton, etc. However, it does
show an important point. On my laptop, the slowest solution (by a factor of about 5) is the locking one (solution 2). Is that important? Probably not, when you bear in mind that it still managed to acquire the singleton a billion times in under 40 seconds. That means that if you're "only" acquiring the singleton four hundred thousand times per second, the cost of the acquisition is going to be 1% of the performance - so improving it isn't going to do a lot. Now, if you are acquiring the singleton that often - isn't it likely you're using it within a loop? If you care
that much about improving the performance a little bit, why not declare a local variable outside the loop, acquire the singleton once and then loop. Bingo, even the slowest implementation becomes easily adequate.

I would be very interested to see a real world application where the difference between using
simple locking and using one of the faster solutions actually made a significant performance difference.

Conclusion

There are various different ways of implementing the singleton pattern in C#.
A reader has written to me detailing a way he has encapsulated the synchronization aspect,
which while I acknowledge may be useful in a few very particular situations (specifically where you want very high performance, and the ability to determine whether or not the singleton has been created, and full laziness regardless of other static members being called).

My personal preference is for solution 4: the only time I would normally go away from it
is if I needed to be able to call other static methods without triggering initialization, or
if I needed to know whether or not the singleton has already been instantiated. I don't remember the last time I was in that situation, assuming I even have. In that case, I'd probably go for solution 2, which is still nice and easy to get right.

Solution 5 is elegant, but trickier than 2 or 4, and as I said above, the benefits it provides
seem to only be rarely useful.

(I wouldn't use solution 1 because it's broken, and I wouldn't use solution 3 because it has no
benefits over 5.)

Источник: www.yoda.arachsys.com/csharp/singleton.html

Wednesday, September 23, 2009

Признаки равенства, сравнения и их отличия

IEquatable:

This interface is implemented by types whose values can be equated (for example, the numeric and string classes). A value type or class implements the Equals method to create a type-specific method suitable for determining equality of instances.

The IComparable<T> interface defines the CompareTo method, which determines the sort order of instances of the implementing type. The IEquatable<T> interface defines the Equals method, which determines the equality of instances of the implementing type.

bool Equals(
T other
)

IComparable
:

This interface is implemented by types whose values can be ordered; for example, the numeric and string classes. A value type or class implements the CompareTo method to create a type-specific comparison method suitable for purposes such as sorting.

The IComparable<T> interface defines the CompareTo method, which determines the sort order of instances of the implementing type. The IEquatable<T> interface defines the Equals method, which determines the equality of instances of the implementing type.

int CompareTo(
T other
)

IEqualityComparer:

This interface allows the implementation of customized equality comparison for collections. That is, you can create your own definition of equality for type T, and specify that this definition be used with a collection type that accepts the IEqualityComparer<T> generic interface. In the .NET Framework, constructors of the Dictionary<TKey, TValue> generic collection type accept this interface.
bool Equals(
T x,
T y
)

Implementations are required to ensure that if the Equals method returns true for two objects x and y, then the value returned by the GetHashCode method for x must equal the value returned for y.

The Equals method is reflexive, symmetric, and transitive. That is, it returns true if used to compare an object with itself; true for two objects x and y if it is true for y and x; and true for two objects x and z if it is true for x and y and also true for y and z.

IComparer:

This interface is used with the List<T>.Sort and List<T>.BinarySearch methods. It provides a way to customize the sort order of a collection. Classes that implement this interface include the SortedDictionary<TKey, TValue> and SortedList<TKey, TValue> generic classes.

int Compare(
T x,
T y
)

Friday, September 18, 2009

Миф 20/80

Стоимость дискового пространства
www.littletechshoppe.com/ns1625/winchest.html

Статья by Joel.

Thursday, September 17, 2009

Source code reading

Builder

Assigning pointer to pointer in Objective-C

Pointer variable is a variable itself, so it has an address. So &str1 results in the address of the pointer variable, and str1 is an expression that results in whatever the pointer variable is holding - the address of the object it's pointing to.

Assume that:

  • the object holding the NSString "one" is at address 0x00000100
  • the object holding the NSString "two" is at address 0x00000200

Then your pointers might look something like this:

At initialization:

str1
0xbfffd3c8 +---------------+
| |
| 0x00000100 |
| ("one") |
+---------------+

str2
0xbfffd3cc +---------------+
| |
| 0x00000200 |
| ("two") |
+---------------+

=======================================

After the str1 = str2; assignment:

str1
0xbfffd3c8 +---------------+
| |
| 0x00000200 |
| ("two") |
+---------------+

str2
0xbfffd3cc +---------------+
| |
| 0x00000200 |
| ("two") |
+---------------+

Дополнительная ссылка:
stackoverflow.com/questions/529482/objective-c-pointers

Static variables in Objective-C

// MyClass.h
@interface
MyClass : NSObject {
}
+ (NSString*)str;
+ (void)setStr:(NSString*)newStr;
@end

// MyClass.m
#import "MyClass.h"

static NSString* str;

@implementation
MyClass

+ (NSString*)str {
return str;
}

+ (void)setStr:(NSString*)newStr {
if (str != newStr) {
[str release];
str
= [newStr copy];
}
}
@end

Дополнительная ссылка на обсуждение:
http://discussions.apple.com/thread.jspa?threadID=1592519

Чтобы сделать доступным эту переменную за пределами m файла,
следует объявить переменную как extern:
http://www.omnigroup.com/mailman/archive/macosx-dev/2002-April/037869.html

Singleton in Objective-C

Mac recommendations to create singlton:

static MyGizmoClass *sharedGizmoManager = nil;

+ (MyGizmoClass*)sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}

+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone
{
return self;
}

- (id)retain
{
return self;
}

- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}

- (void)release
{
//do nothing
}

- (id)autorelease
{
return self;
}



#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [[self alloc] init]; \
} \
} \
\
return shared##classname; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [super allocWithZone:zone]; \
return shared##classname; \
} \
} \
\
return nil; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return self; \
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return NSUIntegerMax; \
} \
\
- (void)release \
{ \
} \
\
- (id)autorelease \
{ \
return self; \
}


If you #import this header at the top of a class implementation, then all you need to do is write:

SYNTHESIZE_SINGLETON_FOR_CLASS(MyClassName);

inside the @implementation MyClassName declaration and your class will become a singleton. You will also need to add the line:

+ (MyClassName *)sharedMyClassName;

to the header file for MyClassName so the singleton accessor method can be found from other source files if they #import the header.

Once your class is a singleton, you can access the instance of it using the line:

[MyClassName sharedMyClassName];
Note: A singleton does not need to be explicitly allocated or initialized (the alloc and init methods will be called automatically on first access) but you can still implement the default init method if you want to perform initialization.

How to Create, Load, and Use Multiple Nib Files

In Mac OS X, application management is a single drag & drop operation: drop the application into /Applications to install, and drop it into the Trash to uninstall. This simplicity and power is just the tip of the iceberg. What we're seeing is just one use of a more general facility Cocoa calls bundles.

This article is about Nib files, and how to use them in your applications. Nib files are just specialized bundles, so we'll talk about bundles first.

// Bundles

A bundle is a directory containing code and resources. Applications, frameworks, Interface Builder (IB) Interface Palettes, and Nibs are all bundle types. The NSBundle Foundation class, along with the NSBundle Additions found in Cocoa, allow you to easily access and load a bundle's contents.

Getting a reference for your application's NSBundle is easy:

NSBundle * b = [NSBundle mainBundle];

Getting a reference for a given bundle inside your application is equally easy:

NSBundle * c = [NSBundle bundleWithPath:
[b pathForResource:@"TestBundle" ofType:@"bundle"]];

pathForResource:ofType: finds a given resource inside the receiving NSBundle's bundle directory, whether that resource is represented on disk as a file or directory.

Also, you can load a bundle's Principal Class, which is typically the first class listed in Project Builder(PB)'s "Files" tab for non-.app bundles. Say I had a class called BundleClass, and I ran the following code (after running all the code above):

bundleClass = NSAllocateObject([c principalClass], 0, NSDefaultMallocZone());
NSLog(@"loaded class %@", bundleClass);
[bundleClass init];

The output of my program would have been:

2002-03-23 15:29:20.637 Test[4709]  loaded class 

Suffice it to say, NSBundle is cool, and is the basis for applications, frameworks, Nibs, and a few other types of packaged data. There are plenty of useful methods for dealing with NSBundles, so do yourself a favor and check out the documentation.

// Nibs: A Special Type of Bundle

Now we come to the meat of this article: Nib files. Nib files are bundles that contain resources created by Interface Builder (IB). When you create a new Cocoa project, one Nib, MainMenu.nib, is automatically created for you. In MainMenu.nib, you can setup a menu bar (duh) and any additional windows, panels, or drawers you want.

Nibs contain archived instances of all the objects you built in IB. This includes instances of NSMenu, NSWindow, and any of your own classes you instanciate in IB. Once the Nib is loaded, every instance archived within it is unarchived into a running instance.

But, what do you do when you want a variable number of instances for a given window or set of windows? For example, for the document window in MDI applications like TextEdit? This is where we have to use more than one Nib file.

// Making a New Nib

Using a Nib is simple, in fact we all do it every time we make a new Cocoa application. Using more than one Nib is almost as simple: just create one with your original application in Project Builder (PB). Choose "Cocoa Document-based Application" under File..New Project. Under the "Resources" group in your newly-created project, you'll see MyDocument.nib. MyDocument.nib is a Nib loaded for each individual document opened in the application.

The other way to add a Nib is just to create a new one in Interface Builder (IB) and add it to your project. In IB, just hit File -> New -> Cocoa -> Empty, save it, and add it to your project.

// Multiple Client Windows Made Easy

Now that you've got a bright shiny new Nib, it would probably help to be able to do something with it. But how do you get references to all the stuff inside the Nib once you load it? In your new Nib, you'll see an object instance called "File Owner." This instance is there to hold a set of references for the newly created objects unarchived from the Nib you just loaded. You can add outlets and actions to it like any other object.

So, build your Nib like any other, and then connect everything you need externally accessible to File Owner. You can also set File Owner's class to anything you want. You can leave it as NSObject, set it to NSDocument like in the MyDocument.nib created in Project Builder (PB), or make it your own class. It's infinitely flexible, go have some fun with it.

So, all this talk and still no code? Here's how you load the Nib into your application:

- (void) newDocument:(id) sender {
MyDocument *d = [[MyDocument alloc] init];
if (![NSBundle loadNibNamed:@"MyDocument" owner:d]) {
NSLog(@"Error loading Nib for document!");
} else {
[d doSomething];
[_list_of_open_documents addObject:d];
}
}

Ok, so only the single call to loadNibNamed:owner: is necessary, but error checking never hurt nobody.

The code above fills in d's outlets with those specified in the Nib. d becomes the File Owner, and so it takes on all the File Owner's connections in the Nib.

источник: www.cocoadevcentral.com

Thursday, September 10, 2009

Математика

Cephes
http://articles.org.ru/docum - здесь набор описаний форматов файлов, в том числе JPEG и дискретно-косинусное преобразование.
http://matlab.exponenta.ru/imageprocess/index.php - Обработка сигналов и изображений в Matlab. Понравилось хорошее описание математики.

http://matlab.exponenta.ru/imageprocess/book5/10_0.php - Отличная статья по реконструкции изображений и FFT.

Wednesday, September 9, 2009

If architects had to work like software developers

http://blog.monochrome.co.uk/2009/02/if-architects-had-to-work-like-software-developers

Powered by Blogger.