|
| 1 | +/** |
| 2 | + * @file |
| 3 | + * @copyright Copyright (c) 2020 Jesús González del Río |
| 4 | + * @license See LICENSE.txt |
| 5 | + */ |
| 6 | + |
| 7 | +using System; |
| 8 | +using System.IO; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +namespace FirmwareFile |
| 12 | +{ |
| 13 | + /** |
| 14 | + * Loader for binary firmware files (i.e., a block of contiguous memory without |
| 15 | + * an explicit address). |
| 16 | + */ |
| 17 | + public class BinaryFileLoader |
| 18 | + { |
| 19 | + /*=========================================================================== |
| 20 | + * PUBLIC METHODS |
| 21 | + *===========================================================================*/ |
| 22 | + |
| 23 | + /** |
| 24 | + * Loads a firmware from the file at the given path. |
| 25 | + * |
| 26 | + * @param [in] filePath Path to the file containing the firmware |
| 27 | + */ |
| 28 | + public static Firmware Load( string filePath ) |
| 29 | + { |
| 30 | + return LoadAsync( filePath ).GetAwaiter().GetResult(); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Loads a firmware from the file at the given stream. |
| 35 | + * |
| 36 | + * @param [in] stream Stream to provide the firmware file contents |
| 37 | + */ |
| 38 | + public static Firmware Load( Stream stream ) |
| 39 | + { |
| 40 | + return LoadAsync( stream ).GetAwaiter().GetResult(); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Loads asynchronously a firmware from the file at the given path. |
| 45 | + * |
| 46 | + * @param [in] filePath Path to the file containing the firmware |
| 47 | + */ |
| 48 | + public static Task<Firmware> LoadAsync( string filePath ) |
| 49 | + { |
| 50 | + var fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read ); |
| 51 | + |
| 52 | + return LoadAsync( fileStream ); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Loads asynchronously a firmware from the file at the given stream. |
| 57 | + * |
| 58 | + * @param [in] stream Stream to provide the firmware file contents |
| 59 | + */ |
| 60 | + public static async Task<Firmware> LoadAsync( Stream stream ) |
| 61 | + { |
| 62 | + var fwFile = new Firmware( false ); |
| 63 | + |
| 64 | + int dataSize = (int) stream.Length; |
| 65 | + |
| 66 | + byte[] data = new byte[dataSize]; |
| 67 | + |
| 68 | + if( await stream.ReadAsync( data, 0, dataSize ) != dataSize ) |
| 69 | + { |
| 70 | + throw new Exception( "Couldn't read binary file contents" ); |
| 71 | + } |
| 72 | + |
| 73 | + fwFile.SetData( 0, data ); |
| 74 | + |
| 75 | + return fwFile; |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments