Skip to content

[Proposal] Temporary uninitialized buffers #1379

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

Merged
merged 1 commit into from
Aug 26, 2021
Merged

Conversation

grynspan
Copy link
Contributor

@grynspan grynspan commented Jun 1, 2021

This proposal introduces some new stdlib functions for manipulating temporary memory.

Pitch thread: https://forums.swift.org/t/pitch-temporary-uninitialized-buffers/48954/
Swift implementation PR: swiftlang/swift#37666

@grynspan
Copy link
Contributor Author

grynspan commented Jun 4, 2021

@benrimmington Thanks for the suggestions!


extension taco_t {
public static func consume(count: Int, filledWith fillings: taco_fillings_t) throws {
withUnsafeUninitializedMutableBufferPointer(to: taco_t.self, capacity: count) { buffer in
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FIXME: try needed here.


The proposed functions do _not_ guarantee that their buffers will be stack-allocated. This omission is intentional: guaranteed stack-allocation would make this feature equivalent to C99's variable-length arrays—a feature that is extremely easy to misuse and which is the cause of many [real-world security vulnerabilities](https://duckduckgo.com/?q=cve+variable-length+array). Instead, the proposed functions should stack-promote aggressively, but heap-allocate (just as `UnsafeMutableBufferPointer.allocate(capacity:)` does today) when passed overly large sizes.

This fallback heuristic is an implementation detail and may be architecture- or system-dependent. A common C approach is to say "anything larger than _n_ bytes uses `calloc()`. The Standard Library could refine this approach by checking information available to it at runtime, e.g. the current thread's available stack space. Because the Standard Library would own this heuristic, all adopters would benefit from it and, subject to a recompile, from any enhancements made in future Swift revisions.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FIXME: Missing closing quote.

@jckarter jckarter merged commit 4ed15ba into swiftlang:main Aug 26, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
standard library addition Additive changes to the standard library
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants