BOM - Is it part of the data?

This is a post in response to a comment at Ben Nadel’s blog by PaulH which I think is an interesting and important discussion, but sufficiently off-topic to the blog entry at hand that I didn’t want to completely derail the on-topic discussion.

Whereas initially BOM (Byte Order Marker U+FEFF) was intended to indicate the order of the bytes when dealing with systems which may have had little-endian or big-endian CPU’s, and so written characters in a byte order for which they are most suited while potentially interoperating with systems with opposite endianness. Their use in recent years has mostly been as a hint to byte stream -> character array string parsers as to the encoding of the string. For example, you can identify UTF-8 encoded files with a leading BOM because they will start with 0xEF 0xBB 0xBF (Unicode U+FEFF). UTF-16BE will start with 0xFE 0xFF, UTF-16LE will start with 0xFF 0xEF, and so on.

At a conceptual sense, byte order markers are not considered to be part of the data. In fact, U+FEFF is a Zero Width Non-Breaking Space, and is considered obviated within data because of its use as a BOM. You’re supposed to use U+2060 WORD JOINER instead of U+FEFF ZWNBSP. The fact that U+FEFF is a zero-width character is part of why it was chosen as BOM - if a system reads the encoding correctly but doesn’t know how to deal with BOM, it will be interpreted instead as an invisible character - exactly what we’re seeing with CFHTTP.

The problem in this case is that no character, not even zero-width characters are permitted before the processing instruction in an XML document. ColdFusion’s cfhttp function preserves the BOM as part of the data, while it’s xmlParse() function fails to handle it correctly. This is an inconsistency, and I suspect you may be able to start a holy war over which feature has the bug.

I Googled around for a while to see if I could find a source that said definitively whether a BOM is considered part of the Unicode data, or simply a hint which is intended to be dropped as part of the Unicode decoding (eg, we convert multiple bytes into single characters in the case of characters greater than U+00EF, likewise we consume the hint as a means of informing us how the file is encoded, and nothing else). This latter case has always been my understanding of it, and indeed this behavior is reinforced by many systems, including ColdFusion itself in some arenas (eg, reading a file with cffile that contains a leading BOM - the BOM will be discarded). Unfortunately other systems do seem to retain BOM, but it’s impossible to say for those systems whether this was a design decision or failure to address BOM at all as they would look the same to an outside observer.

I couldn’t find much in the way of a definitive statement for or against BOM being retained as part of the character array. The closest I could find is something you alluded to - XML 1.0 specifies that BOM is not considered to be part of the data, and should be used only to identify the endianness of the data being passed to it, and otherwise ignored. That wording is a bit ambiguous since in its original context, it’s talking about how to handle BOM at the start of a byte stream.

As to the applicability of this part of the XML standard to ColdFusion’s XML parser - ColdFusion’s XML parser isn’t dealing with a byte stream, it’s dealing with a character array. By the point we call xmlParse(), we have gotten past our need for the BOM (if we’ve already parsed the byte stream as characters, BOM can no longer affect what we do with those characters), so the XML standard on dealing with BOM no longer applies.

So this all comes down to: Is BOM part of the data or just metadata? Conceptually it’s part of the metadata, whereas the question is should it be preserved in the character array. I land firmly in the camp of it being purely metadata, and with it being desirable to discard it as part of character parsing. ColdFusion treats it as metadata in some instances and as part of the data in other instances, this inconsistency is where we see the original error.

Some software even provides an option as to whether or not BOM should be preserved as part of the data: http://www.webhostingsearch.com/blogs/richard/bom-byte-order-mark-in-biztalk-output/

In any event, CF should be consistent with how it handles BOM, and if it considers it as part of the data, then its string functions should consistently handle it as such (ie, xmlParse() should ignore it). If it considers it to be metadata, then it should always be discarded when parsing the byte stream into a character array. The fact that in some cases it discards BOM when parsing characters says to me that the design decision by Macrodobeia was to discard it when parsing characters, since someone had to have written code to this effect, but that it wasn’t applied consistently throughout.

, , ,

No Comments

Unicode: The absolute minimum every developer should know.

Over the past few years, I’ve been engaged in a few projects which have required international support. Via trial and fire, I’ve learned a fair amount about Unicode and character encoding. I now consider this to be essential knowledge for all programmers - web programmers especially. This becomes particularly important when you start dealing with strict schemas such as XML, which may care greatly what the individual characters are, and whose schema may be broken by invalidly encoding some characters.

There’s a great article here with the absurdly long yet very much accurate title of The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky of Joel on Software fame.

It’s important to realize that Unicode is just a really big alphabet. It’s a collection of letters, glyphs, and symbols from a lot of different languages, some non-languages (eg, there’s a smiley with an eyepatch), and even some fake languages (I believe there’s some Klingon in there). It specifies nothing about what bytes you use to represent a given Unicode character, it just says that character 12345 should be such and such a symbol.

Next comes encoding. Encoding defines how we map a given Unicode character into bytes. There are many encoding schemes out there, some of them favor one language or another (ISO-8859-1, which is common in Microsoft applications favors European languages).

Not all encodings are able to represent the entire Unicode character set. The characters which can be represented by a given character set is known as that set’s character repertoir. The encoding specifies both how to represent characters in terms of bytes on a disk, and also which subset of the Unicode character set this encoding represents. The same bytes interpreted as a different character encoding will yield different glyphs.

Some encodings specify that each character is made up of some pre-determined, fixed number of bytes, while others specify that different characters are made up of different numbers of bytes - usually the most common characters are a single byte, and less common characters are multiple bytes.

One of the most common encodings is UTF-8. This is an incredibly popular character encoding, and for good reason - it’s very flexible, and uses only a single byte for the most common characters, making it also one of the most compact. I’ll talk about it some more tomorrow.

6 Comments

Adobe opens the file formats for SWF and FLA

Adobe is opening up the file formats for SWF and FLA, which is major news! SWF is the format run by Flash Player, and FLA is the source format which is used to create SWF’s. With this documentation, anyone will be able to create their own FLA and SWF creation software. Previously this had been substantially reverse engineered, but there were still bits and pieces which had not been figured out.

, , ,

No Comments

CFThread and dividing up work

CFThread is a wonderful addition to ColdFusion 8. It lets you perform parallel actions within your code. However, parallel programming is a complex beast under the best of circumstances.

One of the early things to realize in CF8’s threading support is that it makes a deep copy of the local variables (ala Duplicate()) when you start the thread. In this way you have a lot of thread safety, you can access and change even variables defined outside the thread space, and you really have a copy of that variable local to your thread. You don’t have to worry about other threads changing the value while you’re using it, and you don’t even have to worry about goofing it up for the parent page (the page thread).

Dividing Up the Work
A common use for threading is to divide up a lot of work so that it can be done in parallel. For example, let’s say you have a script which aggregates RSS feeds from 1,000 external sites. All that HTTP stuff is pretty quiet work, you spend a lot of time waiting for responses and the like. It’s a good candidate for parallelizing the work.

With 1,000 requests to make, it’s not a good idea to just create 1,000 threads - you’ll tie up a lot of TCP connections on your server, plus you’ll use up a lot of memory (remember, each thread is going to operate in its own memory space). So let’s decide somewhat arbitrarily that we’re only going to run 10 requests in parallel.

// How many feeds will each thread handle?
eachThreadDoesCount = ceiling(ArrayLen(feedURLs) / parallelThreads);

threadID - 1) * eachThreadDoesCount + 1>
threadID * eachThreadDoesCount, ArrayLen(feedURLs))>

Looks pretty easy, eh? There’s a critical error there though which is not obvious even by Adobe’s documentation. I’ve bolded it for you. This will end up with the earliest URLs getting fetched numerous times, and the later URLs not getting fetched at all.

The reason for this has to do in some way with how ColdFusion initiates its threads under the hood. To me, it looks like when tag is encountered, it actually spawns an initial thread to do the local variable copying. All threads which are started before this initial thread finishes the copying will get an identical set of local variables - this includes the threadID variable used in the loop. I’m not certain if that’s actually what’s going on under the hood, but the behavior is similar as if that is the case. In any event, you cannot rely on variables changed by the parent page (”page thread” by Adobe’s documentation) appearing in your cfthreads, even if that change was made before your specific thread was launched, but after the initial thread was launched.

It seems bizarre, but let me give you a piece of sample code which demonstrates it. This code is non-deterministic for me - that is to say some times I see a “correct” result, but then I immediately refresh it and get a different result.


Here you should see each worker thread having a unique loopID. Instead, for example, my code shows Worker 1 has a loopID of 1, Worker 2 = 2, Worker 3 = 3, Worker 4 = 4, but Workers 5 through 20 have a loopID of 5. If I refresh, it’s different. I’ve seen all 20 workers starting with a loopID of 1, and I’ve seen the first fiew having a loopID of 1, then the next few having a loopID of 5, then the next few having a loopID of 8, etc.

So how do you safely determine which worker you are so you know which of the set of work you should be doing? The answer, as Ray posted in a comment (and contrary to my more elaborate work-around involving locking), is to use the attributes scope:


Basically the idea is you can pass additional custom attributes to and these show up as values in a structure named “attributes” available only within the scope of your thread.

,

2 Comments

ColdFusion 8.0.1 - Nested Array/Struct Shorthand

As you probably know, ColdFusion 8 gave us a long-needed shorthand for creating arrays and structures:


Unfortunately you couldn’t nest those constructs. With the 8.0.1 updater though, you now can:

This is fantastic when you’re trying to make configurable code - a chunk of code whose basic function is tweakable by updating a few settings variables at the top instead of hard-coding them in throughout the code (for example - URLs, filesystem paths, data sources, etc).

No Comments

Follow up to Real Time Command Execution Feedback Post

With ColdFuison 8.0.1 Adobe has introduced errorVariable and/or errorFile to the attributes of the tag. You can only use one of the two in the same tag.

This will give some insight once the tag has completed execution if there is an error. Before there was no way for CF to report errors to a file or to the browser.

No Comments

Speed Limiter

Once in a while you need to simulate what a user experience will be at a certain connection speed. I’ve added up data sizes and times and did some math to figure out what the numbers will be, but this ignores tcp and http header overhead.

Fortunately there exists a simple tool for Windows to let you simulate any connection speed to any TCP port from any TCP client. Notably, web browsers are TCP clients which connect to TCP ports.


The tool is called Speed Limiter, and it’s freeware (an English download page can be found here). It includes some special functions related to HTTP, but it can be used for any protocol.

,

No Comments

ColdFusion Preserve POST variable name case

ColdFusion provides access to POSTed data via the FORM structure. Unfortunately ColdFusion always upper-cases the names of these variables. Recently a chunk of code I was working on needed to know the original case of these keys. At first I worked on passing a hidden form field with the original field name text, but this bothered me as way too much of a work-around.

This chunk of code will give you a structure called FormContent where the case of the field names is preserved.

Unfortunately this code will not distinguish between two fields with the same name but different case. To do that, you’ll want to use a case-sensitive StructNew() alternative. I recommend CreateObject(”java”, “java.util.LinkedHashMap”).init(). This has the added value of preserving the order that the fields appeared in the calling form when you iterate over it for output. It has the disadvantage that you’ll have to properly match case of the keys when you retrieve them in your code.

4 Comments

ColdFusion REMatchAll

This ColdFusion method offers functionality similar to PHP’s preg_match_all function. It searches for the supplied regular expression in the supplied text. The return value is an array with one entry for each time the pattern matches the string. The array entries are structs with a numbered element for each parenthesized sub-expression within the match, and a zero-entry for the whole match.

It’s probably easier to see example data.


Screenshot of the dump result from a ReMatchAll call

As you can see, it returns every match, position, and full text of the match, as well as each parenthesized subexpression. The example pattern basically matches {foo|bar|baz}, {foo|bar}, or {foo}, and returns the alphabetical sub-components as the sub-expressions.

Here is the code.

, ,

No Comments

Spry Email Validation

First you have to include the js and css files for the spry framework. In this example taken from the spry demos we have two files. Both are designed for text fields.

The actual form field will be wrapped in a div or span tag with an id. Any messaging then gets its own span class within the div.

Below the form on the page, the following scripting is added. This will validate that there is a correct email typed into the text field. Validating on change checks the field on each character entered. For emails it would be better to validate on blur. The user will not get constant reminders as they type.


Notice that there’s no Regex on the screen. I didn’t need any, the Spry framework took care of it.

, ,

1 Comment