Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data slicing a slice produces incorrect Data #76449

Open
jasonbobier opened this issue Sep 13, 2024 · 3 comments
Open

Data slicing a slice produces incorrect Data #76449

jasonbobier opened this issue Sep 13, 2024 · 3 comments
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels

Comments

@jasonbobier
Copy link

jasonbobier commented Sep 13, 2024

Description

Passing sliced data to a function that slices further doesn't result in a correct data slice.

Reproduction

let d = Data([0x02, 0x00, 0x00, 0x00, 0x00, 0x00])

func test(data: Data) {
	let d1 = data[4...]  // this should be 0 bytes, but is 2 bytes
}

test(data: d[2...])

Expected behavior

Slicing would work when slicing a slice of Data since it returns Data.

Environment

Xcode 16 RC

Additional information

No response

@jasonbobier jasonbobier added bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels labels Sep 13, 2024
@oscbyspro
Copy link
Contributor

A Data subsequence shares indices with its base sequence, so the current behavior is correct. Subsequence index sharing is required by protocols such as Collection. data[4...] requests a subsequence starting at index 4. data.dropFirst(4) is what you're looking for.

let data = Data(repeating: 0, count: 12)
print(data[2...].startIndex) // 2
print(data[2...][4...].startIndex) // 4
print(data[2...].dropFirst(4).startIndex) // 6

@jasonbobier
Copy link
Author

jasonbobier commented Sep 14, 2024

This doesn't seem correct because func test(data: Data) could be anywhere. It just takes a Data and has no idea that it is a slice. From its point of view, it is just Data to take bytes from. The other sequences deal with this by having dedicated slice types.

I would argue that the slicing behavior isn't a very good design, but in Data's case, there isn't even a type difference.

@jasonbobier
Copy link
Author

(btw... this just bit me because I spaced wrapping the Data slice in a Data and passed it on. The compiler was completely fine with it and then produced the wrong values several layers down in a common function that expected Data.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels
Projects
None yet
Development

No branches or pull requests

2 participants