Convert old To new MemoryBlock

Convert old To new MemoryBlock

My current code is:
Dim memBlock As MemoryBlock = DecodeBase64(pdfData, encodings.UTF8)
Dim stream As BinaryStream
stream = BinaryStream.Create(f, True) // Overwrite if exists
stream.Write(memBlock)
stream.Close

If I Add on top:
Using Xojo.Core
Using Xojo.IO

  Dim t As String = DecodeBase64(pdfData, Encodings.UTF8)
  Dim memBlock As MemoryBlock = TextEncoding.UTF8.ConvertTextToData(t.ToText)
  Dim stream As BinaryStream
  stream = BinaryStream.Create(pdfFile) // Overwrite if exists
  stream.Write(memBlock)
  stream.Close

… code dosn’t work (Error: Invalid Encoding)

Any idea?

If it’s Base64-encoded, it likely represents binary data, not human-readable text, so it wouldn’t be UTF8-encoded, and cannot be represented by the Text type, hence the error.

String, on the other hand, can hold bytes that are invalid for the specified encoding, but you shouldn’t be referencing any encoding at all for binary data.

Curious why you need to convert your code at all?

I don’t know, If this is directly connected to this topic, but I found out yesterday, that‘s possible for Desktop projects, to convert Text Type to the Classic MemoryBlock.

Var txt As Text = "Hello World" Var mb As MemoryBlock = txt
It returned the same bytes as Xojo.Core.MemoryBlock in my tests.

Text auto converts to a UTF8 string, and String will auto convert to MemoryBlock, and vice versa sans encoding.

This is what I use to test my encryption on iOS. It converts any binary (text or otherwise) to a Xojo.Core.MemoryBlock:

Dim InputString As String = RandomBytesStringMBS(1024 * 1000) 'set your binary input here Dim tempMemoryBlock As MemoryBlock = InputString Dim InputCoreMB As New Xojo.Core.MemoryBlock(tempMemoryBlock, InputString.LenB) 'use this in encryption …

If memory serves, you have to keep that temp MemoryBlock around. If you let it go out of scope, the new MemoryBlock will become invalid.

That’s fine for me, I encrypt the string, return the Base64, then don’t care about the MemoryBlock anymore. That said, I do find your warning troubling, especially if we ask for a New Xojo.Core.MemoryBlock.

That only means you’re creating a new instance, but that Constructor does not clone. (Again, based on recollection.)

But in Martin’s example there, would that involve the data being copied twice?

Assuming no compiler optimizations, that would be my expectation.