javascriptf#inlinewebsharper

Converting between integer types in WebSharper


It seems that WebSharper has some difficulties converting between integer types (say, int32 to uint64). I get this:

error : Failed to translate a method call: ToUInt64(..) [Microsoft.FSharp.Core.Operators]

The same happens to int32 -> uint32, int16 -> int32 and many others (only byte <-> int32 seems to be working).

So, the question is: how do I get around this issue? I've got an integer i (which is int32 since I can't get anything else) and now I want to get i-th element from Uint8Array. Uint8Array.Get wants an uint64. How do I convert my i to uint64?

I was going to use an [<Inline>] cheat but that doesn't work either, because I get this error even if I try to return or to pass as an argument any integer different form int32.


Solution

  • From your comments it sounds like you are on the right track. WebSharper currently does not implement any binary handling .NET API so it is right to implement it yourself. Using numeric types for compile-time sanity while keeping in mind that they are all represented as Number in JavaScript is also a good idea. If you are missing conversion proxies from the standard library, you can add those or use Inline definition, I believe this should work:

    [<AutoOpen>]
    module Conversions =
    
        [<Inline "$0">]
        let inline int64 x = int64 x
    
        [<Inline "$0">]
        let inline int32 x = int32 x
    
        [<Inline "$0">]
        let inline uint32 x = uint32 x
    
        [<Inline "$0">]
        let inline uint64 x = uint64 x
    

    Of course the above implementations do not do the truncation that these operators are doing in F#/.NET.