Padding Length

Quite a lot of modern protocols have padding requirements. One great example is Diameter. All attribute values there are aligned on 4-byte boundary. Reason behind such complication is in data structure alignment. While only benefit on x86 architecture is (usually minor) speed increase, on RISC processor it makes difference between doing some work or crashing in flames.

Most common alignment is on 4-byte boundaries. If we have something with length of 5, aligned length will be 8. However for length of 4, aligned length is also 4. Code is as simple as it gets:

public int GetPaddedLength(int len) {
    if ((len % 4) == 0) {
        return len;
    } else {
        return len + 4 - (len % 4);
    }
}

Lengths that fall into alignment by their own devices are not touched while all other get small boost. Of course that code can be a bit shorter if one is comfortable with C# ternary operator (present in almost all C-like languages):

public int GetPaddedLength(int len) {
    return ((len % 4) == 0) ? len : len + 4 - (len % 4);
}

And, if other alignment is needed, small generalization is all it takes:

public int GetPaddedLength(int len, int align) {
    return ((len % align) == 0) ? len : len + align - (len % align);
}

Null Object Pattern

One of more dangerous patterns that I have seen is Null object pattern. Premise is simple enough: Instead of your function returning null (e.g. when it cannot find an item) it should return special empty object. This avoids null references exception if such object is accidentally used. With simple change to way how we return object we just got rid of crashes. What could go wrong?

Well, someone might implement new functionality a year down the road. Not knowing about this behavior he will check for null in some border line case. Since change is small, no one will do full testing (of course, in real world, any change triggers full retesting :)). His borderline behavior just went from well defined (check for null and take action) to pray that empty object does not get inserted into main program flow.

Exceptions are your friend. That kind of friend that will kick you in the arse when you do something wrong. Having empty object instead of null will indeed stop the crash. However, there is now empty object floating around. Programs are complex and this object is bound to get into wrong place. Best case scenario is that no data gets corrupted.

Null reference exceptions that you would get traditionally are probably among simplest exceptions that you can find in the wild. From stack trace you can see where object is null and just backtrack from there. And probability of data corruption is quite low since program crashed before actually doing anything with affected object. Even if something wrong got inside, crash is quite a clear signal that something is amiss.

Debugging any errors produced by this pattern is not a trivial task. You will probably only notice that something is wrong on data. And you will not notice that error immediately. No, it will be in database for days, weeks if not years until some TPS report exposes it to public. And then you need to find offending code. Talk about needle in haystack…

I view using this pattern as telling someone to kick you in the balls. Maybe there is good reason to take such action, maybe there are even some benefits. Nevertheless there will be some pain involved and one should better be sure that this is really action that is needed.

QText 3.20

QText screen

New version of QText has one feature that I planned for a while now.

Just right-click on any tab, select encrypt and chose your password. Upon first access to tab you will get password prompt and file will be decrypted and left open in order to be used. As soon as program is closed and taken to tray, file will be locked again. Other than password prompt, look and feel of encrypted files should be same as it was before.

For those that like three-letter abbreviations, 256-bit AES in CBC mode is name of the game. Security-wise it might not be a best choice since (in chosen implementation) it derives key and IV directly from password. Since that operation is very fast, unfortunately this also means that is very fast to mount brute-force attack. Of course, the longer password, the more resilient it will be. I wouldn’t save my nuclear-launch codes here, but everything else should be safe.

I always tried to keep data accessible to user even without QText installed. That was main reason driving decision to use text files and folder structure as storage mechanism instead of single file. Availability of user data is what also drove me to use OpenSSL encryption here. OpenSSL is available on virtually every platform. Because of same algorithm it is possible to manually decrypt each file if need arises:

openssl aes-256-cbc -d -in file.txt.aes256cbc -out file.txt -k "password"

I consider this a good trade.

As always, upgrade is available from within application or at these pages.

Choose Your Poison

When dealing with programs there are almost always multiple ways to write same thing. Rule of thumb is usually to write it in most readable way. And there people start disagreeing what exactly is readable. Let’s take simple condition:

if (object.equals(obj1, obj2)) {
    ...
}
if (object.equals(obj1, obj2) == true) {
    ...
}

Both these statements do exactly same thing. Heck, they even get compiled to same code. However most programmers I have ever met prefer first one. It just makes intention clear in shorter form.

It’s negative cousin would be:

if (!object.equals(obj1, obj2)) {
    ...
}
if (object.equals(obj1, obj2) == false) {
    ...
}

Again, both statements are same. But I can bet that they will do almost perfect split among programmers. Half of them will prefer concise form with other half preferring longer form. Reasons will vary. For some exclamation mark is too easy to omit when scanning code. For some longer form just sticks out for no good reason.

Personally I passionately hate negative statements and I will avoid them whenever I can. If I really need them I am in group that strongly believes that later form, while longer, is superior as readability goes. For me that is worth seven additional characters. Strangely enough, in positive cases, I omit true.

P.S. One more variation of negative case would be:

if (!(object.equals(obj1, obj2))) {
    ...
}

It might as well be in goldilocks zone. It gives a bit more visibility to exclamation mark by enclosing everything in another set of brackets. Of course, given statement long enough, it can look rather crowded.

Selecting a LDO Voltage Regulator

Illustration

I am in process of creating new USB board for my personal nefarious purposes and I needed nice 3.3V voltage regulator. Usually I just use LD1117DT33TR. It has decent maximum current, works up to 15V and it comes in nice DPAK package that helps to keep it cool. However, for this occasion, it was just too big. I wanted something smaller.

While simplest thing would be to pick one that would suit me in this project. However, I always like to spend a bit more time in order to get a chip that I can reuse in bunch of other projects. Here were things that I desired:

  • 3.3 V
  • at least 50 mA
  • SMD
  • LDO
  • easily available in Croatia
  • very simple
  • preferably cheap

First I searched on RS Croatia site for all LDO 3.3V regulators in SOT-23 package. Sorting them by price gave me few candidates. They were AP7313, TS9011SCX, TC1014, SP6201EM5 and MCP1700. All others that were cheap enough were variations of same basic devices. Quick search on DigiKey didn’t find TS9011SCX so it was automatically disqualified. High cost removed SP6201EM5. If I am searching for jelly bean component, I want to have one that is always available and very cheap.

Another odd-man out was TC1014. I haven’t had anything against it’s specifications. They were good enough and in some parts better than chips that stayed in competition. However, it had five leads. I wanted my final choice to be as simple as possible. That left two SOT-23-3 devices in race: AP7313 and MCP1700.

Both these devices satisfy all my needs. And then some. Both have short-circuit protection, thermal protection and both are stable with 1 μF ceramic (nice!) output capacitor. For most parameters where MCP1700 was slightly better they were close enough not to really matter. Great example would be quiescent current. While on first glance there is huge difference in favor of MCP1700 (40x) that only matters in case of extremely optimized battery-powered device. Since almost all devices I do revolve around computer, it is just parameter that I do not care about. For all jelly bean 5 to 3.3 V LDO purposes they are equivalent.

After spending some time going back and forth I decided to use MCP1700T-3302E/TT. Reason was stability. While both regulators work with ceramic capacitors, AP7313 requires output capacitor ESR to be 20 to 200 mΩ. This does cover wide range of ceramics, but for MCP1700 is even better. It’s output capacitor can have ESR anywhere from 0 to 2000 mΩ. That range covers pretty much all capacitor types that I would find on my shelf.

If something comes up where AP7313 would be great fit (e.g. no minimum load), I am fine with that also. You see, AP7313 comes in two different footprints. In case of AP7313-33SRG-7 footprint is same as one that MCP1700 uses. You can mix and match them based on cost and availability as much as your heart desires (just watch for those capacitors!). And that gives real lesson of this post: whenever you can try not to limit yourself to single supplier.