<< Back to previous view

[CLJ-893] crafted `vec' call allows created vector to be mutated Created: 08/Dec/11  Updated: 18/May/12  Resolved: 18/May/12

Status: Closed
Project: Clojure
Component/s: None
Affects Version/s: Release 1.3, Release 1.4
Fix Version/s: Release 1.5

Type: Defect Priority: Major
Reporter: Stephen Compall Assignee: Unassigned
Resolution: Completed Votes: 1
Labels: None

Found in 1.3.0; tested in 1.4.0-alpha2 as well.

Attachments: Text File clj-893-doc-vec-aliases-java-array-patch3.txt    
Patch: Code
Approval: Ok

user> (let [a (to-array (repeat 31 0)), v (vec a)]
        [(v 2) (do (aset a 2 'no) (v 2))])
[0 no]
user> (let [a (to-array (repeat 33 0)), v (vec a)]
        [(v 2) (do (aset a 2 'no) (v 2))])
[0 0]

While a relaxation of when different changes to the environment are made may impact the resulting value of the vector, as it is with lazy seqs, it oughtn't be possible to get two different results for the same access, just as with lazy seqs.

Comment by Stuart Halloway [ 09/Dec/11 9:34 AM ]

The code path followed here lets vec assume (without copying) a passed-in array. to-array just returns the array, and createOwning doesn't copy either.

Seems like we need a defensive copy somewhere

Comment by Rich Hickey [ 22/Jan/12 12:26 PM ]

Just document that, when passed an array, vec aliases it, and it should not be changed. Then only people that can't ensure that must copy it first.

Comment by Andy Fingerhut [ 24/Feb/12 8:33 PM ]

Proposed patch to document the existing behavior, and briefly suggest safe ways to use vec with mutable collections.

Comment by Stuart Sierra [ 23/Mar/12 9:00 AM ]

I think the docstring in the 24/Feb/12 patch is too long. Also not entirely correct: calling vec on a mutable java.util.List, for example, will create an immutable vector from the contents of the List.

Instead just say that Java arrays may be aliased by vec and should not be modified.

Comment by Andy Fingerhut [ 26/Mar/12 5:16 PM ]

clj-893-doc-vec-aliases-java-array-patch2.txt of Mar 26, 2012 is shorter than the previous attempt, and avoids the error Stuart Sierra found.

Comment by Rich Hickey [ 13/Apr/12 8:09 AM ]

I'd prefer it said will alias and "should not be modified" vs "should be copied".

Comment by Andy Fingerhut [ 14/Apr/12 4:22 PM ]

Would someone better at writing Clojure style doc strings take a crack at this? I'm too verbose. I have added a (verbose) note about this behavior on clojuredocs.org.

Comment by Brenton Ashworth [ 21/Apr/12 4:12 PM ]

Added patch


With this patch the doc string would be:

Creates a new vector containing the contents of coll. Java arrays
will be aliased and should not be modified.
Comment by Andy Fingerhut [ 24/Apr/12 7:42 PM ]

Removed non-preferred patch clj-893-doc-vec-aliases-java-array-patch2.txt of Mar 26, 2012.

Generated at Sat Jan 20 01:41:33 CST 2018 using JIRA 4.4#649-r158309.