string.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const protocol = require("devtools/shared/protocol");
  6. const {Arg, RetVal, generateActorSpec} = protocol;
  7. const promise = require("promise");
  8. const {Class} = require("sdk/core/heritage");
  9. const longStringSpec = generateActorSpec({
  10. typeName: "longstractor",
  11. methods: {
  12. substring: {
  13. request: {
  14. start: Arg(0),
  15. end: Arg(1)
  16. },
  17. response: { substring: RetVal() },
  18. },
  19. release: { release: true },
  20. },
  21. });
  22. exports.longStringSpec = longStringSpec;
  23. /**
  24. * When a caller is expecting a LongString actor but the string is already available on
  25. * client, the SimpleStringFront can be used as it shares the same API as a
  26. * LongStringFront but will not make unnecessary trips to the server.
  27. */
  28. const SimpleStringFront = Class({
  29. initialize: function (str) {
  30. this.str = str;
  31. },
  32. get length() {
  33. return this.str.length;
  34. },
  35. get initial() {
  36. return this.str;
  37. },
  38. string: function () {
  39. return promise.resolve(this.str);
  40. },
  41. substring: function (start, end) {
  42. return promise.resolve(this.str.substring(start, end));
  43. },
  44. release: function () {
  45. this.str = null;
  46. return promise.resolve(undefined);
  47. }
  48. });
  49. exports.SimpleStringFront = SimpleStringFront;
  50. // The long string actor needs some custom marshalling, because it is sometimes
  51. // returned as a primitive rather than a complete form.
  52. var stringActorType = protocol.types.getType("longstractor");
  53. protocol.types.addType("longstring", {
  54. _actor: true,
  55. write: (value, context, detail) => {
  56. if (!(context instanceof protocol.Actor)) {
  57. throw Error("Passing a longstring as an argument isn't supported.");
  58. }
  59. if (value.short) {
  60. return value.str;
  61. }
  62. return stringActorType.write(value, context, detail);
  63. },
  64. read: (value, context, detail) => {
  65. if (context instanceof protocol.Actor) {
  66. throw Error("Passing a longstring as an argument isn't supported.");
  67. }
  68. if (typeof (value) === "string") {
  69. return new SimpleStringFront(value);
  70. }
  71. return stringActorType.read(value, context, detail);
  72. }
  73. });