acmerobotics / road-runner

Wheeled mobile robot motion planning library designed for FTC
MIT License
209 stars 75 forks source link

Make `DualNum` `double[]` constructor public #108

Open BD103 opened 5 days ago

BD103 commented 5 days ago

Hello!

While writing a few extension functions for DualNum, I find myself writing this:

val out = DualNum<Param>(DoubleArray(min(this.size(), other.size())).toList())

I create a DoubleArray to initialize all of its values to zero, but then I have to convert it to a list in order to construct a DualNum. This is inefficient, because DualNum's constructor is:

constructor(values: List<Double>) : this(values.toDoubleArray())

Essentially, I'm forced to convert an array to a list and back again because the primary constructor is internal. This gets even worse when you look at Kotlin's implementations of these functions:

public fun List<Double>.toDoubleArray(): DoubleArray {
    val result = DoubleArray(size)
    var index = 0
    // Copy each item, one at a time.
    for (element in this)
        result[index++] = element
    return result
}

public fun DoubleArray.toList(): List<Double> {
    val list = ArrayList<Double>(size)
    // Copy each item, one at a time.
    for (item in this) list.add(item)
    return list
}

This pull request fixes this by making the primary DoubleArray constructor public, to avoid unnecessary copying and conversion.