Browse Source

QuickProto documentation comments

Tim Burks 9 years ago
parent
commit
e00d88c227

+ 5 - 4
Examples/StickyNotes/StickyNotes/AppDelegate.swift

@@ -40,6 +40,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
   @IBOutlet weak var window: NSWindow!
 
   func applicationDidFinishLaunching(_ aNotification: Notification) {
+    gRPC.initialize()
     startServer(address:"localhost:8081")
   }
 
@@ -51,7 +52,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
 
     if let fileDescriptorSetProto =
       NSData(contentsOfFile:Bundle.main.path(forResource: "stickynote", ofType: "out")!) {
-      // load a FileDescriptorSet that includes a descriptor for the message to be created
+      // load a FileDescriptorSet that includes a descriptor for the messages we create and read
       let fileDescriptorSet = FileDescriptorSet(proto:fileDescriptorSetProto)
 
       DispatchQueue.global().async {
@@ -120,11 +121,11 @@ class AppDelegate: NSObject, NSApplicationDelegate {
                               NSRectFill(rect)
                               NSColor.black.set()
                               let string = NSString(string:message)
-                              var s = CGFloat(300.0)
-                              let trialFont = NSFont.userFont(ofSize:s)!
+                              let trialS = CGFloat(300.0)
+                              let trialFont = NSFont.userFont(ofSize:trialS)!
                               let trialAttributes = [NSFontAttributeName: trialFont]
                               let trialSize = string.size(withAttributes: trialAttributes)
-                              s = s * 300 / trialSize.width;
+                              let s = trialS * 300 / trialSize.width;
                               let font = NSFont.userFont(ofSize:s)!
                               let attributes = [NSFontAttributeName: font]
                               let size = string.size(withAttributes: attributes)

+ 0 - 6
Examples/StickyNotes/StickyNotes/StickyNoteViewController.swift

@@ -31,7 +31,6 @@
  *
  */
 import AppKit
-
 import gRPC
 import QuickProto
 
@@ -39,10 +38,6 @@ class StickyNoteViewController : NSViewController, NSTextFieldDelegate {
   @IBOutlet weak var messageField: NSTextField!
   @IBOutlet weak var imageView: NSImageView!
 
-  override func viewDidLoad() {
-    gRPC.initialize()
-  }
-
   @IBAction func messageReturnPressed(sender: NSTextField) {
     callServer(address:"localhost:8081")
   }
@@ -94,7 +89,6 @@ class StickyNoteViewController : NSViewController, NSTextFieldDelegate {
         self.log("Received status: \(response.status) " + response.statusDetails)
         if let responsemessage = response.message {
           let data = responsemessage.data()
-          // re-read it
           if let message = fileDescriptorSet.readMessage(name:"StickyNoteResponse",
                                                          proto:data) {
             message.forOneField(name:"image") {(field) in

+ 1 - 1
Packages/CgRPC/Sources/byte_buffer.c

@@ -85,7 +85,7 @@ const void *cgrpc_byte_buffer_as_data(cgrpc_byte_buffer *bb, size_t *length) {
   }
   gpr_slice slice = grpc_byte_buffer_reader_readall(&reader);
   *length = (size_t) GPR_SLICE_LENGTH(slice);
-  const void *result = malloc(*length);
+  void *result = malloc(*length);
   memcpy(result, GPR_SLICE_START_PTR(slice), *length);
   gpr_slice_unref(slice);
   grpc_byte_buffer_reader_destroy(&reader);

+ 5 - 0
QuickProto/QuickProto.xcodeproj/project.pbxproj

@@ -33,6 +33,7 @@
 		D35C9F791D74A4BA000443CD /* MessageDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3DCB48A1D6F4C7A00C6A8AE /* MessageDescriptor.swift */; };
 		D35C9F7A1D74A4BA000443CD /* MessageReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3DCB48E1D6F4D0100C6A8AE /* MessageReader.swift */; };
 		D35C9F7B1D74A4BA000443CD /* NSMutableData+Proto.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3DCB49D1D6FCF6000C6A8AE /* NSMutableData+Proto.swift */; };
+		D3930CBE1D74E9DC00F1A9BE /* WireType.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3930CBD1D74E9DC00F1A9BE /* WireType.swift */; };
 /* End PBXBuildFile section */
 
 /* Begin PBXCopyFilesBuildPhase section */
@@ -54,6 +55,7 @@
 		D35C9F371D74A1C0000443CD /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
 		D35C9F691D74A4AB000443CD /* QuickDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = QuickDemo; sourceTree = BUILT_PRODUCTS_DIR; };
 		D35C9F6B1D74A4AB000443CD /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
+		D3930CBD1D74E9DC00F1A9BE /* WireType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WireType.swift; sourceTree = "<group>"; };
 		D3DCB4861D6F4C6400C6A8AE /* Message.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Message.swift; sourceTree = "<group>"; };
 		D3DCB4881D6F4C6E00C6A8AE /* Field.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Field.swift; sourceTree = "<group>"; };
 		D3DCB48A1D6F4C7A00C6A8AE /* MessageDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageDescriptor.swift; sourceTree = "<group>"; };
@@ -136,6 +138,7 @@
 				D3DCB48A1D6F4C7A00C6A8AE /* MessageDescriptor.swift */,
 				D3DCB48E1D6F4D0100C6A8AE /* MessageReader.swift */,
 				D3DCB49D1D6FCF6000C6A8AE /* NSMutableData+Proto.swift */,
+				D3930CBD1D74E9DC00F1A9BE /* WireType.swift */,
 			);
 			path = QuickProto;
 			sourceTree = "<group>";
@@ -246,6 +249,7 @@
 			files = (
 				D35C9F3C1D74A1DC000443CD /* _FileDescriptor.swift in Sources */,
 				D35C9F3D1D74A1DC000443CD /* CodeBuilder.swift in Sources */,
+				D3930CBE1D74E9DC00F1A9BE /* WireType.swift in Sources */,
 				D35C9F3E1D74A1DC000443CD /* Field.swift in Sources */,
 				D35C9F3F1D74A1DC000443CD /* FieldDescriptor.swift in Sources */,
 				D35C9F401D74A1DC000443CD /* FieldLabel.swift in Sources */,
@@ -457,6 +461,7 @@
 				D35C9F6E1D74A4AB000443CD /* Release */,
 			);
 			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
 		};
 		D3D1C8551D6D15D9002F1B53 /* Build configuration list for PBXProject "QuickProto" */ = {
 			isa = XCConfigurationList;

+ 5 - 5
QuickProto/QuickProto/CodeBuilder.swift

@@ -41,20 +41,20 @@ public class CodeBuilder {
     return code
   }
 
+  /// the initializer builds a code representation from a message
   public init(_ message: Message) {
-    // build the code representation
     code = ""
     code += "import Foundation\n"
     code += "\n"
     code += "var _FileDescriptor : [[String:Any]] = [\n"
     message.forEachField(path:["file","message_type"]) {(field) in
-      printProtoDescription(field:field)
+      generateProtoDescription(field:field)
     }
     code += "];\n"
   }
 
-  // print code for a dictionary literal describing a proto
-  private func printProtoDescription(field: Field) {
+  /// generate code for a dictionary literal describing a proto
+  private func generateProtoDescription(field: Field) {
     field.message().forEachField(path:["name"]) {(field) in
       code += "  [\"name\": \"\(field.string())\",\n"
       code += "   \"fields\": [\n"
@@ -86,7 +86,7 @@ public class CodeBuilder {
     }
     code += "    ]],\n"
     field.message().forEachField(path:["nested_type"]) {(field) in
-      printProtoDescription(field:field)
+      generateProtoDescription(field:field)
     }
   }
 }

+ 8 - 11
QuickProto/QuickProto/Field.swift

@@ -32,6 +32,7 @@
  */
 import Foundation
 
+/// A representation of a protocol buffer field that can be used to read and build protobufs
 public class Field {
   private var descriptor: FieldDescriptor
   private var value: Any!
@@ -45,6 +46,7 @@ public class Field {
     self.descriptor = descriptor
   }
 
+  /// display a field for testing and debugging
   func display(indent: String) {
     let type = self.descriptor.type
 
@@ -61,24 +63,19 @@ public class Field {
     if let value = value as? Int {
       line += "\(value)"
       print(line)
-    }
-    else if let value = value as? Int32 {
+    } else if let value = value as? Int32 {
       line += "\(value)"
       print(line)
-    }
-    else if let value = value as? Int64 {
+    } else if let value = value as? Int64 {
       line += "\(value)"
       print(line)
-    }
-    else if let value = value as? Bool {
+    } else if let value = value as? Bool {
       line += "\(value)"
       print(line)
-    }
-    else if let value = value as? String {
+    } else if let value = value as? String {
       line += "\(value)"
       print(line)
-    }
-    else if let message = value as? Message {
+    } else if let message = value as? Message {
       line += " {"
       print(line)
       for field in message.fields {
@@ -108,7 +105,7 @@ public class Field {
     return descriptor.tag
   }
 
-  public func wireType() -> Int {
+  public func wireType() -> WireType {
     return descriptor.wireType()
   }
 

+ 20 - 20
QuickProto/QuickProto/FieldDescriptor.swift

@@ -32,7 +32,7 @@
  */
 import Foundation
 
-// Describes a field in a message
+/// A description of a field in a protocol buffer message
 public class FieldDescriptor {
   var type : FieldType
   var label : FieldLabel
@@ -58,26 +58,26 @@ public class FieldDescriptor {
     label = FieldLabel(rawValue:message.oneField(name:"label")!.integer())!
   }
 
-  func wireType() -> Int {
+  func wireType() -> WireType {
     switch type {
-    case FieldType.DOUBLE   : return 1
-    case FieldType.FLOAT    : return 5
-    case FieldType.INT64    : return 0
-    case FieldType.UINT64   : return 0
-    case FieldType.INT32    : return 0
-    case FieldType.FIXED64  : return 1
-    case FieldType.FIXED32  : return 5
-    case FieldType.BOOL     : return 0
-    case FieldType.STRING   : return 2
-    case FieldType.GROUP    : return 3
-    case FieldType.MESSAGE  : return 2
-    case FieldType.BYTES    : return 2
-    case FieldType.UINT32   : return 0
-    case FieldType.ENUM     : return 0
-    case FieldType.SFIXED32 : return 5
-    case FieldType.SFIXED64 : return 1
-    case FieldType.SINT32   : return 0
-    case FieldType.SINT64   : return 0
+    case FieldType.DOUBLE   : return WireType.FIXED64
+    case FieldType.FLOAT    : return WireType.FIXED32
+    case FieldType.INT64    : return WireType.VARINT
+    case FieldType.UINT64   : return WireType.VARINT
+    case FieldType.INT32    : return WireType.VARINT
+    case FieldType.FIXED64  : return WireType.FIXED64
+    case FieldType.FIXED32  : return WireType.FIXED32
+    case FieldType.BOOL     : return WireType.VARINT
+    case FieldType.STRING   : return WireType.LENGTH_DELIMITED
+    case FieldType.GROUP    : return WireType.START_GROUP
+    case FieldType.MESSAGE  : return WireType.LENGTH_DELIMITED
+    case FieldType.BYTES    : return WireType.LENGTH_DELIMITED
+    case FieldType.UINT32   : return WireType.VARINT
+    case FieldType.ENUM     : return WireType.VARINT
+    case FieldType.SFIXED32 : return WireType.FIXED32
+    case FieldType.SFIXED64 : return WireType.FIXED64
+    case FieldType.SINT32   : return WireType.VARINT
+    case FieldType.SINT64   : return WireType.VARINT
     }
   }
 }

+ 1 - 0
QuickProto/QuickProto/FieldLabel.swift

@@ -32,6 +32,7 @@
  */
 import Foundation
 
+/// The "label" of a protocol buffer field
 public enum FieldLabel: Int {
   case OPTIONAL      = 1
   case REQUIRED      = 2

+ 1 - 0
QuickProto/QuickProto/FieldType.swift

@@ -32,6 +32,7 @@
  */
 import Foundation
 
+/// The "type" of a protocol buffer field
 public enum FieldType: Int {
   case DOUBLE         = 1
   case FLOAT          = 2

+ 1 - 0
QuickProto/QuickProto/FileDescriptor.swift

@@ -32,6 +32,7 @@
  */
 import Foundation
 
+/// A collection of descriptors that were read from a compiled .proto file
 class FileDescriptor {
   var messageDescriptors : [MessageDescriptor] = []
 

+ 1 - 0
QuickProto/QuickProto/FileDescriptorSet.swift

@@ -32,6 +32,7 @@
  */
 import Foundation
 
+/// A collection of descriptors that were read from a group of one or more compiled .proto files
 public class FileDescriptorSet {
   var fileDescriptors : [FileDescriptor] = []
 

+ 13 - 3
QuickProto/QuickProto/Message.swift

@@ -32,14 +32,17 @@
  */
 import Foundation
 
+/// zigzag-encode 32-bit integers
 func zigzag(_ n:Int32) -> (Int32) {
   return (n << 1) ^ (n >> 31)
 }
 
+/// zigzag-encode 64-bit integers
 func zigzag(_ n:Int64) -> (Int64) {
   return (n << 1) ^ (n >> 63)
 }
 
+/// A representation of a protocol buffer message that can be used to read and build protobufs
 public class Message {
   var descriptor: MessageDescriptor
   var fields: [Field]
@@ -49,6 +52,7 @@ public class Message {
     self.fields = fields
   }
 
+  /// add a field and perform the specified action
   public func addField(name: String, action:((Field) -> Void)) {
     // look up the field descriptor
     for fieldDescriptor in descriptor.fieldDescriptors {
@@ -62,6 +66,7 @@ public class Message {
     }
   }
 
+  /// get one field with the specified name
   public func oneField(name: String) -> Field? {
     for field in fields {
       if field.name() == name {
@@ -71,6 +76,7 @@ public class Message {
     return nil
   }
 
+  /// perform an action on one field with the specified name
   public func forOneField(name: String, action:((Field) -> Void)) {
     for field in fields {
       if field.name() == name {
@@ -80,6 +86,7 @@ public class Message {
     }
   }
 
+  /// perform an action on each field with the specified name
   public func forEachField(name:String, action:(Field) -> (Void)) {
     for field in fields {
       if field.name() == name {
@@ -88,6 +95,7 @@ public class Message {
     }
   }
 
+  /// perform an action on each field following the specified path of field names
   public func forEachField(path:[String], action:(Field) -> (Void)) {
     for field in fields {
       if field.name() == path[0] {
@@ -102,16 +110,18 @@ public class Message {
     }
   }
 
+  /// display a message for testing and debugging
   public func display() {
     for field in fields {
       field.display(indent:"")
     }
   }
 
-  public func serialize() -> (NSMutableData) {
+  /// generate the serialized protocol buffer representation of a message
+  public func serialize() -> (NSData) {
     let data = NSMutableData()
     for field in fields {
-      data.appendVarint(field.tag() << 3 + field.wireType())
+      data.appendVarint(field.tag() << 3 + field.wireType().rawValue)
 
       switch field.type() {
       case FieldType.DOUBLE:
@@ -147,7 +157,7 @@ public class Message {
       case FieldType.UINT32:
         data.appendVarint(field.integer())
       case FieldType.ENUM:
-        assert(false)
+        assert(false) // TODO
       case FieldType.SFIXED32:
         data.appendInt32(field.integer())
       case FieldType.SFIXED64:

+ 2 - 1
QuickProto/QuickProto/MessageDescriptor.swift

@@ -32,7 +32,7 @@
  */
 import Foundation
 
-// Describes a message
+/// A description of a protocol buffer message
 public class MessageDescriptor {
   var name: String = ""
   var fieldDescriptors: [FieldDescriptor] = []
@@ -67,6 +67,7 @@ public class MessageDescriptor {
     }
   }
 
+  /// lookup the field descriptor for a specified tag
   func fieldDescriptor(tag: Int) -> FieldDescriptor? {
     for fieldDescriptor in fieldDescriptors {
       if (fieldDescriptor.tag == tag) {

+ 1 - 2
QuickProto/QuickProto/MessageReader.swift

@@ -32,7 +32,7 @@
  */
 import Foundation
 
-// Reads a protocol buffer
+// A reader for protocol buffers. Used internally.
 class MessageReader {
   var fileDescriptorSet: FileDescriptorSet
   var messageName: String
@@ -103,7 +103,6 @@ class MessageReader {
     return result
   }
 
-
   private func nextVarint() -> (Int) {
     var sum : Int = 0
     var shift : Int = 0

+ 1 - 0
QuickProto/QuickProto/NSMutableData+Proto.swift

@@ -32,6 +32,7 @@
  */
 import Foundation
 
+// Extensions that support serialization of protocol buffers
 extension NSMutableData {
 
   func appendVarint(_ value: Int) {

+ 43 - 0
QuickProto/QuickProto/WireType.swift

@@ -0,0 +1,43 @@
+/*
+ *
+ * Copyright 2016, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+import Foundation
+
+/// The "wire type" of a protocol buffer field
+public enum WireType: Int {
+  case VARINT = 0
+  case FIXED64 = 1
+  case LENGTH_DELIMITED = 2
+  case START_GROUP = 3
+  case END_GROUP = 4
+  case FIXED32 = 5
+}

+ 3 - 0
QuickProto/QuickProto/_FileDescriptor.swift

@@ -30,6 +30,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  */
+
+// GENERATED CODE
+
 import Foundation
 
 var _FileDescriptor : [[String:Any]] = [