Skip to content

Commit 1505862

Browse files
committed
Add unsafeToArray function for getting the underlying boxed Array. Fixes #245
1 parent 2ec9d87 commit 1505862

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

vector/changelog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
* Add `groupBy` and `group` for `Data.Vector.Generic` and the specialized
4848
version in `Data.Vector`, `Data.Vector.Unboxed`, `Data.Vector.Storable` and
4949
`Data.Vector.Primitive`.
50+
* Add `unsafeToArray` function for getting the underlying boxed `Array`.
5051

5152
# Changes in version 0.12.3.1
5253

vector/src/Data/Vector.hs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ module Data.Vector (
163163
toList, Data.Vector.fromList, Data.Vector.fromListN,
164164

165165
-- ** Arrays
166-
fromArray, toArray,
166+
fromArray, toArray, unsafeToArray,
167167

168168
-- ** Other vector types
169169
G.convert,
@@ -2147,6 +2147,17 @@ toArray (Vector offset size arr)
21472147
| offset == 0 && size == sizeofArray arr = arr
21482148
| otherwise = cloneArray arr offset size
21492149

2150+
-- | /O(1)/ Extract the underlying `Array`, offset where vector starts and the
2151+
-- total number of elements in the vector. Below property always holds:
2152+
--
2153+
-- > let (array, offset, size) = unsafeToArray v
2154+
-- > v === unsafeTake size (unsafeDrop offset (`fromArray` array))
2155+
--
2156+
-- @since 0.13.0.0
2157+
unsafeToArray :: Vector a -> (Array a, Int, Int)
2158+
{-# INLINE unsafeToArray #-}
2159+
unsafeToArray (Vector offset size arr) = (arr, offset, size)
2160+
21502161
-- Conversions - Mutable vectors
21512162
-- -----------------------------
21522163

vector/tests/Tests/Vector/UnitTests.hs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ tests =
9191
, testGroup "Data.Vector"
9292
[ testCase "MonadFix" checkMonadFix
9393
, testCase "toFromArray" toFromArray
94+
, testCase "toFromArrayUnsafe" toFromArrayUnsafe
9495
, testCase "toFromMutableArray" toFromMutableArray
9596
]
9697
]
@@ -202,6 +203,14 @@ toFromArray =
202203
mkArrayRoundtrip $ \name v ->
203204
assertEqual name v $ Boxed.fromArray (Boxed.toArray v)
204205

206+
toFromArrayUnsafe :: Assertion
207+
toFromArrayUnsafe =
208+
mkArrayRoundtrip $ \name v ->
209+
case Boxed.unsafeToArray v of
210+
(arr, off, n) ->
211+
assertEqual name v $
212+
Boxed.unsafeTake n (Boxed.unsafeDrop off (Boxed.fromArray arr))
213+
205214
toFromMutableArray :: Assertion
206215
toFromMutableArray = mkArrayRoundtrip assetRoundtrip
207216
where

0 commit comments

Comments
 (0)