Skip to content

Commit

Permalink
Merge pull request #3715 from chkn/add-system-array-resize
Browse files Browse the repository at this point in the history
[JS] Add support for System.Array.Resize
  • Loading branch information
MangelMaxime authored Jan 25, 2024
2 parents 88003be + 2d4720d commit dc4b07e
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Fable.Cli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* `DateTime.TryParse`
* `DateTime.SpecifyKind`

#### JavaScript

* [GH-3715](https://github.com/fable-compiler/Fable/pull/3715) Add support for System.Array.Resize (by @chkn)

## 4.9.0 - 2023-12-14

### Fixed
Expand Down
16 changes: 16 additions & 0 deletions src/Fable.Transforms/Replacements.fs
Original file line number Diff line number Diff line change
Expand Up @@ -3369,6 +3369,22 @@ let arrays
)
|> Some
| "GetEnumerator", Some arg, _ -> getEnumerator com r t arg |> Some
| "Resize", None, args ->
let args =
args @ [ getZero com ctx (List.head i.GenericArgs) ]
|> injectArg com ctx r "Array" "resize" i.GenericArgs

Helper.LibCall(
com,
"Array",
"resize",
Unit,
args,
i.SignatureArgTypes,
genArgs = i.GenericArgs,
?loc = r
)
|> Some
| _ -> None

let arrayModule
Expand Down
1 change: 1 addition & 0 deletions src/Fable.Transforms/ReplacementsInject.fs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ let fableReplacementsModules =
"insertAt", (Types.arrayCons, 0)
"insertManyAt", (Types.arrayCons, 0)
"updateAt", (Types.arrayCons, 0)
"resize", (Types.arrayCons, 0)
]
"List",
Map
Expand Down
26 changes: 26 additions & 0 deletions src/fable-library/Array.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1405,3 +1405,29 @@ let updateAt
xs.[i]

target

let resize
(xs: byref<'T[]>)
(newSize: int)
([<OptionalArgument>] zero: 'T option)
([<OptionalArgument; Inject>] cons: Cons<'T>)
: unit
=
if newSize < 0 then
invalidArg "newSize" "The input must be non-negative."

let len = xs.Length

if newSize < len then
xs <- subArrayImpl xs 0 newSize

elif newSize > len then
let target = allocateArrayFromCons cons newSize
copyTo xs 0 target 0 len

xs <-
fillImpl
target
(defaultArg zero Unchecked.defaultof<_>)
len
(newSize - len)
9 changes: 9 additions & 0 deletions tests/Js/Main/ArrayTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1190,4 +1190,13 @@ let tests =
equal c1 true
equal c2 -1
equal c3 1

testCase "Array.Resize works" <| fun () ->
let mutable xs = [|1; 2; 3; 4; 5|]
Array.Resize(&xs, 3)
xs |> equal [|1; 2; 3|]
Array.Resize(&xs, 7)
xs |> equal [|1; 2; 3; 0; 0; 0; 0|]
Array.Resize(&xs, 0)
xs |> equal [||]
]

0 comments on commit dc4b07e

Please sign in to comment.