Skip to content

Commit

Permalink
extend setAttribute to specify type
Browse files Browse the repository at this point in the history
  • Loading branch information
patrick-zippenfenig committed Nov 23, 2021
1 parent d89670c commit 6cf1b42
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
11 changes: 7 additions & 4 deletions Sources/SwiftNetCDF/AttributeProvidable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,14 @@ extension AttributeProvidable {
try setAttribute(name, [value])
}

/// Define a new attribute by name. The value must be a supported external type.
public func setAttribute<T: NetcdfConvertible>(_ name: String, _ value: [T]) throws {
let type = T.netcdfType.typeId
/// Define a new attribute by name. The value must be a supported external type. The type parameter can be set to enfore
public func setAttribute<T: NetcdfConvertible>(_ name: String, _ value: [T], type: ExternalDataType = T.netcdfType) throws {
guard T.canRead(type: type) else {
throw NetCDFError.datatypeNotCompatible
}

try T.withPointer(to: value) { ptr in
try setAttributeRaw(name: name, type: type, length: value.count, ptr: ptr)
try setAttributeRaw(name: name, type: type.typeId, length: value.count, ptr: ptr)
}
}

Expand Down
1 change: 1 addition & 0 deletions Sources/SwiftNetCDF/Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public enum NetCDFError: Error {
case hdf5Error
case netCDF4MetedataError
case alreadyExists
case datatypeNotCompatible

/// Init from NetCDF error code
/// TODO find NetCDF definiton for code 2 "no such file"
Expand Down
3 changes: 3 additions & 0 deletions Tests/SwiftNetCDFTests/SwiftNetCDFTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ final class SwiftNetCDFTests: XCTestCase {
let file = try NetCDF.create(path: "test.nc", overwriteExisting: true)
try file.setAttribute("TITLE", "My data set")

// Write attribute as [Char] instead of string with 0 terminator
try file.setAttribute("TITLE_CHAR", Array("My data set".utf8CString), type: .char)

let dimensions = [
try file.createDimension(name: "LAT", length: 10),
try file.createDimension(name: "LON", length: 5)
Expand Down

0 comments on commit 6cf1b42

Please sign in to comment.