title: Detect if a string was double-encoded in UTF-8
body: <p>I need to process a large list of short strings (mostly in Russian, but any other language is possible, including random garbage from a cat walking on keyboard).</p>
  
  <p>Some of these strings will be encoded in UTF-8 twice.</p>
  
  <p>I need to reliably detect if a given string is double-encoded, and fix it. I should do this without using any external libraries, just by inspecting the bytes. The detection should be as fast as possible.</p>
  
  <p>The question is: how to detect that a given string was encoded in UTF-8 twice?</p>
  
  <p><em>Update:</em></p>
  
  <p>Original strings are in UTF-8. Here is the AS3 code that does the second encoding (unfortunately I don't have control on the client code, so I can't fix this):</p>
  
  <pre><code>private function toUTF8(s : String) : String {
         var byteArray : ByteArray = new ByteArray();
         byteArray.writeUTFBytes(s);
         byteArray.position = 0;
  
         var res : String = "";
  
         while(byteArray.bytesAvailable){
             res += String.fromCharCode(byteArray.readUnsignedByte());
         }
  
         return res;
  }
  
  myString = toUTF8(("" + myString).toLowerCase().substr(0, 64));
  </code></pre>
  
  <p>Note <code>toLowerCase()</code> call. Maybe this may help?</p>