UTF-8 String Validation Responsibility

Started by
50 comments, last by Ectara 11 years, 1 month ago

Sorry if I've come across as trying to convince you to do something different. It's your code, your choice. I'm just providing my perspective. :)

It provides the same securities as a full-blown string class with more efficiency. Even if I allowed adding a plain integer to the string, that would have the same implications.

Apologies - I misread the access levels and thought it was possible to construct a character with validity of your choosing.

Otherwise, _every_ function must now check to see if the character is valid; with this class, it checks in one place only, and the result can be re-used without the caller tampering with it. I see absolutely no reason why this is an inferior solution.

Sure, since you effectively cache the complex validation in a single bool it's superior if you have a situation where you need to use a character outside of a string multiple times. But I said I can't see such a situation, which is why I believe it would be more trouble than it's worth.

Keep in mind, this string class is not Unicode only; it handles other string types like a simple char string.

I would reiterate my belief that direct character access in strings is almost always the wrong thing to do and is a sign of a bug. The main reason we've done it so often in the C++ world is partly because we've been ignorant of internationalisation and also our vector and array types have rather poor interfaces. Ideally I would be fixing the other container classes, not making text classes double up as better containers.

If I read a configuration file into a char string, and I go to parse it, it would be ridiculous to treat every single character as its own string. It would be horridly inefficient.

Certainly. It would also be ridiculous to treat each char as an instance of its own class! You don't need to work on a per-character level here. Instead you'd treat that as batched-up byte input to the string. This is pretty standard in other languages:

C# example:


byte[] utf16data = ReadFileAsBytes();
string unicodeText = System.Text.UTF16Encoding.UTF16.GetString(utf8data); 

Python 2 example (although really you could use the codecs module to read and decode it directly):


utf16data = ReadFileAsBytes()
unicodeText = unicode(utf8data, 'UTF-16')

Java:


byte[] utf16Bytes = ReadFileAsBytes();
String unicodeText = new String(utf16Bytes, "UTF16");

If for some reason you can't handle it all in one chunk (eg. it's too large, or coming over slow I/O), you'd have a little stream-reader wrapper which maintains its own byte buffer and yields up strings where possible. That would encapsulate the one bit of character-specific logic (ie. checking whether you have enough bytes at the end of the buffer to form a full character) and would be running the validation routine on as many bytes at a time as possible, for almost maximum efficiency.

in the factory method, should I use the string's allocator to allocate its own instance?

This is a bit out of my area of expertise unfortunately. Might be worth starting a new thread about that since we've probably scared everybody out of this one with boring details of surrogate pairs and code points! Can you use the string's own allocator as a default argument to the factory method, just as with the std::basic_string constructor?

Advertisement

Sorry if I've come across as trying to convince you to do something different. It's your code, your choice. I'm just providing my perspective. smile.png


I understand, and I am open to hearing different ways of doing things, so long as the things are actually done. :)

Apologies - I misread the access levels and thought it was possible to construct a character with validity of your choosing.


Understandable; I briefly entertained the thought of explicitly placing access specifiers to aid in mentally parsing the member declarations, but I decided against it. I added that constructor so that the BasicString class can return a character that can be used in another function call without needing to validate the strictly valid character; the ValidatedCharacter class is part of the BasicString class, so it can access this constructor. This is for good reason, both for this special constructor, and because it uses the types aliased from the BasicString's traits class, so each instance of the ValidatedCharacter class is paired directly to an instance of the BasicString templated class. I'm not a fan of nested class declarations, but this seems like the best way.

Sure, since you effectively cache the complex validation in a single bool it's superior if you have a situation where you need to use a character outside of a string multiple times. But I said I can't see such a situation, which is why I believe it would be more trouble than it's worth.


Well, one example could be a naive algorithm for counting newlines in a normalized line ending ASCII string, which would be repeatedly scanning for the next newline. Additionally, it could be several characters, like parsing a simple key-value file format, where it looks for the terminating control character at the end of the key name, then it looks for the character marking the end of the value, like the end of the line. This is one use per line, but there could be several lines in a loop where the characters are used repeatedly, though out of order. An ASCII CSV file might search for the next comma to find the length of the field, or to seek to the next field or line. A markup language parser that is looking for a particular record might continuously search for a character that would mark the beginning of a closing tag so that it could quickly advance to the next record.

A lot of these uses are for text where the character set is constrained intentionally, and thus there is only one representation of the character to be sought. I do concede that it has little regular use in Unicode, due to localization differences, but someone still could if they wanted to, and the feature is more valuable for strings of other types.

I would reiterate my belief that direct character access in strings is almost always the wrong thing to do and is a sign of a bug.

Almost always. Something like printing out a normalized string to a GUI text box is a valid use. Copying code points from one string to another of the same encoding is perfectly valid; converting from UTF16 to UTF-8 requires more complex operations than a memory copy, so it'd be acceptable to convert it to a common code point, and then convert it to the destination format one character at a time, because both transformation formats are defined to be able to encode the same values. There are edge cases that make it worth using, so while I wouldn't use it in most workloads, those few times are worth implementing it.

You don't need to work on a per-character level here.


Where is "here"? This string is on a much larger scope than just holding text; before BasicString, I am using no string implementation, so this means that any functionality that I need will be necessary, even if it will only be an implementation detail hidden away from everyday use.

Instead you'd treat that as batched-up byte input to the string.


Which would make sense, if the code unit datatype was a byte. However, that is part of what I am implementing, so behind the scenes, this is what is being used. I've seen the source code for clang, and its routines for converting from one Unicode format to another are little more than efficiently converting from one format to a code point, and then from that code point to the other format, repeatedly in a loop. This is essentially what I am enabling, which has only a little more overhead if you stick to using iterators in the tight loop, because subscripting repeatedly means seeking through the string each time.

In the absence of everything, nothing is redundant.

This is pretty standard in other languages:


The code snippets probably didn't come out as intended, but I know what you mean. However, I do agree that a lot of these things are best done in batches. However, none of these things exist yet in my library, until I finish the string class. :) No matter how high I get in my abstraction, at some point I need to implement the character to character functionality to implement the higher level details.

This is a bit out of my area of expertise unfortunately. Might be worth starting a new thread about that since we've probably scared everybody out of this one with boring details of surrogate pairs and code points! Can you use the string's own allocator as a default argument to the factory method, just as with the std::basic_string constructor?


I understand, entirely. I think the thread has gone on long enough that nobody will try to trudge through it. So far, the function prototypes look like this:


static BasicString<charT_, traits_, alloc_> * create(const storageType * other,
                                                     const allocatorType & alloc = allocatorType());

static BasicString<charT_, traits_, alloc_> * create(const storageType * other,
                                                     sizeType span,
                                                     const allocatorType & alloc = allocatorType());

static bool create(BasicString<charT_, traits_, alloc_> & str, const storageType * other);

static bool create(BasicString<charT_, traits_, alloc_> & str, const storageType * other, sizeType span);

The factories that create a new instance accept an allocator, and the factories that use an existing instance will use the string's allocator. All of the constructors but the copy constructor take an optional allocator parameter, as well. I'm not sure that I understand the question, however; all of std::basic_string's constructors but the copy constructor default to using a new instance of its allocator type, which might not be the same underlying heap or pool, if it is implemented to have a unique state. The only one that uses the same exact allocator instance is the copy constructor, which doesn't allow you to provide your own. So, if you were wondering if the factory defaults to using an allocator instance that looks just like the one any other BasicString of the same type would use, then yes, that is the default.

This topic is closed to new replies.

Advertisement