database column limits and utf8 strings

September 11th, 2009 by Sarah Leave a reply »

Wolf and I fixed a bug today where we needed to truncate a string of text that we use internally to annotate the database.  Now, the annotation is just for our reference, so we limit it to 50 bytes — that’s bytes, mind you, not characters, even though the PostgreSQL database will tell you it is “character varying(50)”

We use unicode internally, specifically UTF8, which is a fabulous and widely used standard.  However, it does have a challenging property where a character may be 1-4 bytes long. We were frustrated with what we thought ought to be a simple problem of truncating a string so that it would be no more than 50 bytes.  The tricky part, of course, was that the 49th byte might actually fall in the middle of a character.

To solve the problem, we added a method to the Rails Multibyte::Chars class, which is part of ActiveSupport.  For those who speak Ruby, Rails and RSpec, below is the solution we came up with (first the spec, then the implementation).

The solution we came up with was borrowed from the private translate_offset method. The key interesting part is that you can discover whether you’ve chopped up a string in the middle of a character by calling chunk.unpack(’U*’) — the unpack method on String in Ruby will throw an exception when you ask it to interpret the UTF-8 characters as unsigned integers with the “U” directive.

describe "Chars#limit_bytes" do
  it 'should return "" on ""' do
    "".mb_chars.limit_bytes(0).should == ""
    "".mb_chars.limit_bytes(1).should == ""
  end

  it 'should truncate single byte character strings as expected' do
    a = "abcd"
    a.mb_chars.limit_bytes(0).should == ''
    a.mb_chars.limit_bytes(1).should == 'a'
    a.mb_chars.limit_bytes(50).should == 'abcd'
  end

  it 'should truncate multi-byte character strings at character boundaries' do
    k = "こんいちわ"
    k.mb_chars.limit_bytes(0).should == ''
    k.mb_chars.limit_bytes(1).should == ''
    k.mb_chars.limit_bytes(3).should == 'こ'
    k.mb_chars.limit_bytes(4).should == 'こ'
    k.mb_chars.limit_bytes(5).should == 'こ'
    k.mb_chars.limit_bytes(6).should == 'こん'
    k.mb_chars.limit_bytes(7).should == 'こん'
    k.mb_chars.limit_bytes(50).should == 'こんいちわ'
  end
end

module ActiveSupport #:nodoc:
  module Multibyte #:nodoc:
    class Chars
      def limit_bytes(limit)
        limit -= 1 while !valid_boundary?(limit)
        s = @wrapped_string.slice(0,limit)
        s.mb_chars
      end

      def valid_boundary?(length)
        chunk = @wrapped_string.slice(0,length)
        begin
          chunk.unpack('U*')
          true
        rescue
          false
        end
      end
    end
  end
end

We’ve written this up as a Lighthouse ticket in case the Rails folk want to add it to the platform or if other people developing multi-lingual database apps run into the same challenge and look there.

2 Responses

  1. emoglen says:

    That was downright nifty. And here I thought that the “Nifty Fifty” simply referred to the elite (and unofficial) group of LA session players that play on the majority of all of the major Hollywood films…

    Nifty fifty, 50 bytes indeed!

  2. Sarah Allen says:

    In Rails 3.1 (and maybe Rails 3 also), ActiveSupport Multibyte::Chars class has a limit method that does the right thing for Ruby 1.8.7 and above. Yay!

Leave a Reply