]> granicus.if.org Git - python/commitdiff
Backport r54786:
authorWalter Dörwald <walter@livinglogic.de>
Sat, 21 Apr 2007 10:31:43 +0000 (10:31 +0000)
committerWalter Dörwald <walter@livinglogic.de>
Sat, 21 Apr 2007 10:31:43 +0000 (10:31 +0000)
Fix utf-8-sig incremental decoder, which didn't recognise a BOM when the
first chunk fed to the decoder started with a BOM, but was longer than 3 bytes.

Lib/encodings/utf_8_sig.py
Lib/test/test_codecs.py
Misc/NEWS

index d751da69c41585778d5a92783381d0c737b094c4..92678d20a8736820740acfde332bdbc2659132c7 100644 (file)
@@ -44,14 +44,19 @@ class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
         self.first = True
 
     def _buffer_decode(self, input, errors, final):
-        if self.first and codecs.BOM_UTF8.startswith(input): # might be a BOM
+        if self.first:
             if len(input) < 3:
-                # not enough data to decide if this really is a BOM
-                # => try again on the next call
-                return (u"", 0)
-            (output, consumed) = codecs.utf_8_decode(input[3:], errors, final)
-            self.first = False
-            return (output, consumed+3)
+                if codecs.BOM_UTF8.startswith(input):
+                    # not enough data to decide if this really is a BOM
+                    # => try again on the next call
+                    return (u"", 0)
+                else:
+                    self.first = None
+            else:
+                self.first = None
+                if input[:3] == codecs.BOM_UTF8:
+                    (output, consumed) = codecs.utf_8_decode(input[3:], errors, final)
+                    return (output, consumed+3)
         return codecs.utf_8_decode(input, errors, final)
 
     def reset(self):
index 185670bb19e817a5cd7ad5c858c95f10eb8ab90e..8c2a9799233cc7bda2786196f50bdf56d6f17dbc 100644 (file)
@@ -430,6 +430,11 @@ class UTF8SigTest(ReadTest):
         # SF bug #1601501: check that the codec works with a buffer
         unicode("\xef\xbb\xbf", "utf-8-sig")
 
+    def test_bom(self):
+        d = codecs.getincrementaldecoder("utf-8-sig")()
+        s = u"spam"
+        self.assertEqual(d.decode(s.encode("utf-8-sig")), s)
+
 class EscapeDecodeTest(unittest.TestCase):
     def test_empty(self):
         self.assertEquals(codecs.escape_decode(""), ("", 0))
index 450bbce60a0a1338898ccc6a8a434287a71c982d..a0892751a141a2edbd5bb5477e4ff163c22bd721 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -602,6 +602,8 @@ Tests
 - Fix bsddb test_basics.test06_Transactions to check the version
   number properly.
 
+- Fix utf-8-sig incremental decoder, which didn't recognise a BOM when the
+  first chunk fed to the decoder started with a BOM, but was longer than 3 bytes.
 
 Documentation
 -------------