Uploaded image for project: 'Swift'
  1. Swift
  2. SR-5873

Incorrect implementation of hashValue and slices by the Data structure in Swift 4

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Closed
    • Priority: Medium
    • Resolution: Done
    • Labels:
      None
    • Environment:

      This bug can be reproduced in Xcode 9 beta 6, as well as under Linux, using Swift version 4.0-dev.

      Description

      As illustrated by the following code snippet, we identified two bugs in the implementation of Data slices:

      • Computing the hashValue of a Data slice returns the same hash value as the "full" Data object.
      • Modifying an element of the slice may modify the subsequent elements of the slice.

       

      import Foundation
      
      var bytes1: [UInt8] = [1, 2, 3]
      var bytes2: [UInt8] = [2, 3, 4]
      
      var data1 = Data(bytes1)
      var data2 = Data(bytes2)
      
      var subData1 = data1[1..<3]
      var subData2 = data2[0..<2]
      
      debugPrint(subData1 == subData2) // Prints true, as expected
      
      debugPrint([UInt8](subData1), data1.hashValue, subData1.hashValue) // Unexpectedly, data1.hashValue == subData1.hashValue
      debugPrint([UInt8](subData2), data2.hashValue, subData2.hashValue) // Unexpectedly, data2.hashValue == subData2.hashValue
      
      // Unexpectedly, subData1.hashValue != subData2.hashValue, although we had subData1 == subData2
      
      subData1[subData1.startIndex] = UInt8(2)
      subData2[subData2.startIndex] = UInt8(2)
      
      debugPrint([UInt8](subData1)) // Unexpectedly, subData1 == [2, <some random byte>] under Linux, [2, 0] under macOS
      debugPrint([UInt8](subData2)) // subData2 == [2, 3], as expected
      

      Running this code gives the "surprising" following output:

       

      true
      [2, 3] 291 291
      [2, 3] 564 564
      [2, 254]
      [2, 3]
      

       

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            tbaigner Thomas Baigneres
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: