Tuesday, December 6, 2016

Converting a swift object to a pointer (and back)

Sometimes it is necessary to convert a swift object to a pointer. This is required in situations, for example, where you need to pass a swift object to a C function that takes a void * (AKA UnsafeMutableRawPointer) parameter. Getting a pointer to a swift class is fairly simple, although it can take a while to find the correct syntax. The following code snipper will convert a Swift NSArray instance to an UnsafeMutableRawPointer, and back to a NSArray without changing the retain count. If you paste the code into a playground, it will print "same array".


Monday, July 4, 2016

A simple libpcap example for live packet captures

libpcap is an extremely useful library for, among other things, capturing network packets in realtime. The library has a lot of options, so I put together a simple example of how to do a packet capture. Depending on your platform, libpcap may return packets in "chunks". In other words, the kernel may wait until a certain number of packets have been received, or a certain amount of time has elapsed, before notifying your application that data is available. In this example, since I want to be notified as soon as a packet is available, I attempt to turn off those behaviors using the pcap_set_timeout() and pcap_set_immediate_mode() APIs. These APIs may behave differently across various platforms.

Sunday, May 22, 2016

Grepping for Multiple Patterns at Once

Grep is a tool with which every programmer should be familiar. It is easy to use to grep to search a text file for lines matching a particular pattern, but sometimes it useful to search a text file for multiple patterns. You can accomplish this by switching over to the egrep command. For example,

egrep 'my|example|search' myfile.txt

will search myfile.txt for all lines which contain either the string "my", "example", or "search".

Saturday, March 19, 2016

Using ArrayLiteralConvertible to initialize swift OptionSetType objects

I was recently working on a program where I needed to configure the autoresizingMask property of a CALayer object. The autoresizingMask property is a bitmask of CAAutoresizingMask enum values. I got a little bit confused because the example code I was following was no longer valid swift:

The first thing I tried was to initialize the CAAutoresizingMask manually, but this code looked ugly:

Then I discovered that OptionSetType objects implement the ArrayLiteralConvertible protocol. This gives an OptionSetType the ability to be initialized with array style syntax. The most concise way to initialize a CAAutoresizingMask object is as follows:

Sunday, February 21, 2016

Variable Coding Guidelines

One thing that separates good programmers from great programmers is the way great programmers use variables in their code. Great programmers:
  • Use clear and concise variable names. One letter variables names are acceptable when used in conventional ways recognized by everyone, like loop indices, but almost nowhere else. Variable names should use full words either in camel case (int maxTreeDepth;) or separated by underscores (int max_tree_depth;).
  •  Declare variables as close to where they are used as possible, and within the smallest scope possible. This has a number of benefits:
    • Variable "live time" is reduced. Live time can be thought of as the space between where a variable is declared, and the time it is used. Keeping this space small reduces the chance that a variable will be modified in an unexpected way, perhaps by a future maintenance programmer, before your code uses it.
    • It makes refactoring a large function into a number of smaller functions easy. If all your variables are declared at the top of the function you are refactoring, you will need to extract the variables required by each new, smaller, function one by one. If the variables are declared immediately before they are used, the refactor becomes a simple copy and paste operation. 
  • Do not reuse variables. There are some exceptions to use rule, but in general, a variable's name should be so specific that it would not make sense to reuse it for another purpose within the same scope.
  • Have empathy for people who will be reading their code in the future. I read a lot of code where programmers go to great lengths to use tiny variable names and obscure abbreviations. I think there are two possible causes for this type of programming:
    • Sheer laziness. Many stubborn programmers refuse to learn how to use modern IDEs which are capable of doing newfangled things like auto-completing variable names. As a result, these types of programmers want variable names to be as small as possible, so they do not have to type as much as if they were using good variable names.
    • Nerdy chest-thumping. Some programmers are capable of keeping all of the details of a complicated algorithm in their head using nothing but terse 1-5 character variable names. As far as I am concerned, there are only two possible explanations for this type of design. Either you don't care about the people who are going to be reading and maintaining your code in the future, or you are insecure and you want those reading the code to be impressed with how few characters your algorithm required.

Monday, February 15, 2016

NSMenuItem Troubleshooting

Every now and then I run into a problem where a NSMenuItem stays disabled when I think it should be enabled. If you are having a similar problem, here are a few things to check:

  • Make sure the NSMenuItem is hooked up to an action. If a menu item has no action it will never be enabled.
  • Check your validateMenuItem: implementation. Is it setup to reject menu items it doesn't know about?
  • Is the menu item's tag set correctly?
  • Does your application have multiple validateMenuItem: methods? If so, make sure you are debugging the correct method. The method you need to look at is the one implemented by the class whose action the NSMenuItem will trigger. This can be a bit confusing if the target of the action is the First Responder object.

Sunday, February 7, 2016

Monitoring Files Asynchronously for Reading

There are a number of ways to monitor file descriptors asynchronously to determine when data is available to be read. Calling select() directly is getting to be old fashioned, but it still gets the job done. Because select() can block until data is available to be read, it should only be called from a background thread in a GUI application. In a daemon, it can be called from the primary thread as long as the daemon doesn't need to do anything else while it waits for data to become available.

The kqueue API is similar to select, and has the same limitations with respect to blocking threads.

Using libdispatch is a better option for GUI applications. The file descriptors can be monitored on a background thread and processed on the main thread.

Using NSFileHandle is an even simpler option for GUI applications. The only caveat is that the readability handler is called on a random thread. If you need to update your UI in response to something read from the file descriptor, you will need to move over to the main thread.